Spring Boot 2结合Spring security + JWT实现微信小程序登录

网友投稿 417 2022-11-05


Spring Boot 2结合Spring security + JWT实现微信小程序登录

项目源码:https://gitee.com/tanwubo/jwt-spring-security-demo

登录

通过自定义的WxAppletAuthenticationFilter替换默认的UsernamePasswordAuthenticationFilter,在UsernamePasswordAuthenticationFilter中可任意定制自己的登录方式。

用户认证

需要结合JWT来实现用户认证,第一步登录成功后如何颁发token。

public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

@Autowired

private JwtTokenUtils jwtTokenUtils;

@Override

public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

// 使用jwt管理,所以封装用户信息生成jwt响应给前端

String token = jwtTokenUtils.generateToken(((WxAppletAuthenticationToken)authentication).getOpenid());

Map result = Maps.newHashMap();

result.put(ConstantEnum.AUTHORIZATION.getValue(), token);

httpServletResponse.setContentType(ContentType.jsON.toString());

httpServletResponse.getWriter().write(JSON.toJSONString(result));

}

}

第二步,弃用spring security默认的session机制,通过token来管理用户的登录状态。这里有俩段关键代码。

@Override

protected void configure(HttpSecurity http) throws Exception {

http.csrf()

.disable()

.sessionManagement()

// 不创建Session, 使用jwt来管理用户的登录状态

.sessionCreationPolicy(SessionCreationPolicy.STATELESS)

......;

}

第二步,添加token的认证过滤器。

public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

@Autowired

private AuthService authService;

@Autowired

private JwtTokenUtils jwtTokenUtils;

@Override

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

log.debug("processing authentication for [{}]", request.getRequestURI());

String token = request.getHeader(ConstantEnum.AUTHORIZATION.getValue());

String openid = null;

if (token != null) {

try {

openid = jwtTokenUtils.getUsernameFromToken(token);

} catch (IllegalArgumentException e) {

log.error("an error occurred during getting username from token", e);

throw new BasicException(ExceptionEnum.JWT_EXCEPTION.customMessage("an error occurred during getting username from token , token is [%s]", token));

} catch (ExpiredJwtException e) {

log.warn("the token is expired and not valid anymore", e);

throw new BasicException(ExceptionEnum.JWT_EXCEPTION.customMessage("the token is expired and not valid anymore, token is [%s]", token));

}catch (SignatureException e) {

log.warn("JWT signature does not match locally computed signature", e);

throw new BasicException(ExceptionEnum.JWT_EXCEPTION.customMessage("JWT signature does not match locally computed signature, token is [%s]", token));

}

}else {

log.warn("couldn't find token string");

}

if (openid != null && SecurityContextHolder.getContext().getAuthentication() == null) {

log.debug("security context was null, so authorizing user");

Account account = authService.findAccount(openid);

List permissions = authService.acquirePermission(account.getAccountId());

List authorities = permissions.stream().map(permission -> new SimpleGrantedAuthority(permission.getPermission())).collect(Collectors.toList());

log.info("authorized user [{}], setting security context", openid);

SecurityContextHolder.getContext().setAuthentication(new WxAppletAuthenticationToken(openid, authorities));

}

filterChain.doFilter(request, response);

}

}

接口鉴权

第一步,开启注解@EnableGlobalMethodSecurity。

@SpringBootApplication

@EnableGlobalMethodSecurity(prePostEnhttp://abled = true)

public class JwtSpringSecurityDemoApplication {

public static void main(String[] args) {

SpringApplication.run(JwtSpringSecurityDemoApplication.class, args);

}

tFWNChni}

第二部,在需要鉴权的接口上添加@PreAuthorize注解。

@RestController

@RequestMapping("/test")

public class TestController {

@GetMapping

@PreAuthorize("hasAuthority('user:test')")

public String test(){

return "test success";

}

@GetMapping("/authority")

@PreAuthorize("hasAuthority('admin:test')")

public String authority(){

return "test authority success";

}

}

到此这篇关于Spring Boot 2结合Spring security + JWT实现微信小程序登录的文章就介绍到这了,更多相关Spring Boot Spring security JWT微信小程序登录内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:VMware 桥接模式下本机 PING 不通虚拟机的解决方法
下一篇:机器人微控制器编程(CoCube)-强化实践
相关文章

 发表评论

暂时没有评论,来抢沙发吧~