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<String, Object> 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<Permission> permissions = authService.acquirePermission(account.getAccountId()); List<SimpleGrantedAuthority> 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(prePostEnabled = true) public class JwtSpringSecurityDemoApplication { public static void main(String[] args) { SpringApplication.run(JwtSpringSecurityDemoApplication.class, args); } }
第二部,在需要鉴权的接口上添加@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微信小程序登录内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Java微服务分布式调度Elastic-job环境搭建及配置
Elastic-Job在配置中提供了JobEventConfiguration,支持数据库方式配置,会在数据库中自动创建JOB_EXECUTION_LOG和JOB_STATUS_TRACE_LOG两张表以及若干索引,来记录作业的相关信息2023-02-02MyEclipse去除网上复制下来的代码带有的行号(正则去除行号)
这篇文章主要介绍了MyEclipse去除网上复制下来的代码带有的行号(正则去除行号)的相关资料,需要的朋友可以参考下2017-10-10idea maven 项目src下的配置文件没有同步至target的解决操作
这篇文章主要介绍了idea maven 项目src下的配置文件没有同步至target的解决操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-08-08Java如何将处理完异常之后的程序能够从抛出异常的地点向下执行?
今天小编就为大家分享一篇关于Java如何将处理完异常之后的程序能够从抛出异常的地点向下执行?,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧2019-04-04关于Sentinel中冷启动限流原理WarmUpController
这篇文章主要介绍了关于Sentinel中冷启动限流原理WarmUpController,具有很好的参考价值,希望对大家有所帮助。2023-04-04Springboot jdbctemplate整合实现步骤解析
这篇文章主要介绍了Springboot jdbctemplate整合实现步骤解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下2020-08-08
最新评论