启用spring security
- 需要一个
AuthenticationProvider
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class CustomerAuthenticationManager implements AuthenticationProvider {
private final SysUserDetailService sysUserDetailService;
public CustomerAuthenticationManager(SysUserDetailService sysUserDetailService) {
this.sysUserDetailService = sysUserDetailService;
}
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
// 获取认证的用户名 & 密码
String name = authentication.getName();
String password = authentication.getCredentials().toString();
// 认证逻辑
SysUserDetail userDetails = (SysUserDetail) sysUserDetailService.loadUserByUsername(name);
String pwd = DigestUtils.md5DigestAsHex(password.getBytes());
if (userDetails != null) {
// 密码MD5 加密 or BCryptPasswordEncoder <--- use this one
// if (encoder.matches(password, userDetails.getPassword())) {
if (pwd.equalsIgnoreCase(userDetails.getPassword())) {
// 这里设置权限和角色
Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
// 生成令牌 这里令牌里面存入了:name,password,authorities, 当然你也可以放其他内容
Authentication auth = new UsernamePasswordAuthenticationToken(name, password, authorities);
return auth;
} else {
throw new BadCredentialsException("密码错误");
}
} else {
throw new UsernameNotFoundException("用户不存在");
}
}
public boolean supports(Class<?> auth) {
return auth.equals(UsernamePasswordAuthenticationToken.class);
}
}
需要获取用户信息的service
- 示例方法从数据库中获取用户信息
1 |
|
一些帮助类
SysUserDetail
这个类继承自org.springframework.security.core.userdetails.UserDetails
1 | public class SysUserDetail implements UserDetails { |
- 基于
jwt
的帮助类
1 | public interface IJwtTokenDecoder { |
添加过滤器对请求进行拦截
1 | public class SecurityConfiguration { |
添加登陆授权接口
1 | // ignore |