package com.security.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.security.domain.LoginUser; import com.security.domain.User; import com.security.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import java.util.Objects; @Component public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserMapper userMapper; @Override public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { //查询用户信息 LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.eq(User::getUserName,userName); User user = userMapper.selectOne(queryWrapper); //没有查询到用户抛出异常 if(Objects.isNull(user)){ //异常会被ExceptionTranslationFilter捕获到 throw new RuntimeException("用户名或者密码错误"); } //todo 查询对应的权限信息 //把数据封装成UserDetails返回 return new LoginUser(user); } }
访问接口时需要登录:http://localhost:8080/login
登录成功后,接口正常返回
因为UserDetailsService方法的返回值是UserDetails类型,所以需要定义一个类,实现该接口,把用户信息封装在其中。
@Data @NoArgsConstructor @AllArgsConstructor public class LoginUser implements UserDetails { private User user; @Override public Collection<? extends GrantedAuthority> getAuthorities() { return null; } @Override public String getPassword() { return user.getPassword(); } @Override public String getUsername() { return user.getUserName(); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
标签:UserDetailsService,return,实现,创建,user,Override,import,security,public From: https://www.cnblogs.com/ixtao/p/17638929.html