Spring Boot + Spring Security + JWT + 微信小程序登录整合教程
文章目录
整合思想
- 自定义AuthenticationToken,封装登录的相关信息,用于SecurityContext存储和验证过程
- 自定义AuthenticationProcessingFilter,代替默认的UsernamePasswordAuthenticationFilter
- 使用code获取open_id、session_key等
- 将获取到的open_id、session_key等封装成一个未认证的AuthenticationToken,传递到AuthenticationManager
- AuthenticationManager执行认证授权过程
- 查询数据库,获取用户信息
- 没有用户则写入用户
- 使用用户信息获取角色
- 封装授权信息
- 将相关信息封装成一个已认证的AuthenticationToken,这个AuthenticationToken会传递到AuthenticationSuccessHandler(认证成功的处理方法)
- 配置Spring Security配置,将UsernamePasswordAuthenticationFilter替换成自定义的AuthenticationProcessingFilter
- 在自定义的AuthenticationProcessingFilter之前添加JWTFilter
整合步骤
1. AuthenticationToken
用于存储微信小程序登录信息
@Getter
@Setter
@ToString
public class WxAppletAuthenticationToken extends AbstractAuthenticationToken {
private String openId;
private Long userId;
private String sessionKey;
private String rawData;
private String signature;
private String role;
// 使用openid和sessionKey创建一个未验证的token
public WxAppletAuthenticationToken(String openId, String sessionKey, String role) {
super(null);
this.openId = openId;
this.sessionKey = sessionKey;
this.role = role;
}
// 使用openid和sessionKey创建一个已验证的token
public WxAppletAuthenticationToken(String openId, String sessionKey, Long userId, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.openId = openId;
this.userId = userId;
this.sessionKey = sessionKey;
super.setAuthenticated(true);
}
// 使用openid创建一个已验证的token
public WxAppletAuthenticationToken(String openId, Long userId, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.openId = openId;
this.userId = userId;
super.setAuthenticated(true);
}
@Override
public Object getCredentials() {
return this.openId;
}
@Override
public Object getPrincipal() {
return this.sessionKey;
}
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
if (isAuthenticated) {
throw new IllegalArgumentException(
"Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
}
super.setAuthenticated(false);
}
@Override
public void eraseCredentials() {
super.eraseCredentials();
}
}
2. AuthenticationProcessingFilter
用于匹配的请求
@Slf4j
public class WxAppletAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public WxAppletAuthenticationFilter(String defaultFilterProcessesUrl) {
super(defaultFilterProcessesUrl);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException

最低0.47元/天 解锁文章
1万+





