SpringSecurity权限认证(三)
查询数据库中信息进行用户登录
前端传入用户信息之后,在security中,有单独的类进行存储,就是UserDetails。
为了方便,直接让用户类实现UserDetails。登录时,直接传入UserDetails类即可。
之后,security,会调用UserDetailsService的loadUserByUsername进行登录。
我们需要自行登录,就需要实现UserDetailsService重写loadUserByUsername函数。
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private AdminMapper adminMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
QueryWrapper<Admin> wrapper = new QueryWrapper<>();
Admin admin = adminMapper.selectOne(wrapper.eq("username", username));
return admin;
}
}
然后在SecurityConfig配置类中设置使用自定义的登录方式。
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}
之后就开始写登录的Controller、Service、Dao层的代码。
Result是自定义的统一返回结果
Controller
@PostMapping("/login")
public Result login(LoginParam admin1){
Result result = adminService.login(admin1);
return result;
}
Service
Result login(LoginParam admin);
Dao层
@Autowired
private AdminMapper adminMapper;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private PasswordEncoder passwordEncoder;
public Result login(LoginParam loginParam){
//调用loadUserByUsername就会跳到自定义的登录函数之中
UserDetails admin = userDetailsService.loadUserByUsername(loginParam.getUsername());
if(null == admin || !passwordEncoder.matches(loginParam.getPassword(), admin.getPassword())){
System.out.println("密码不正确||不存在");
return Result.fail("用户不存在||密码不正确");
}
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(admin , null, admin.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
return Result.success("登录成功", admin);
}