Spring Boot 2结合Spring security + JWT实现微信小程序登录
作者:tanwubo 时间:2022-07-14 08:25:54
项目源码: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";
}
}
来源:https://blog.csdn.net/qq_22606825/article/details/100047498
标签:Spring,Boot,Spring,security,JWT,微信小程序,登录
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
分享Java多线程实现的四种方式
2022-02-23 06:34:21
SpringBoot配置文件中密码属性加密的实现
2022-07-08 18:32:03
![](https://img.aspxhome.com/file/2023/8/64018_0s.jpg)
使用IDEA将Java/Kotliin工程导出Jar包的正确姿势
2022-10-18 17:39:34
![](https://img.aspxhome.com/file/2023/4/69704_0s.png)
web.xml SpringBoot打包可执行Jar运行SpringMVC加载流程
2023-11-24 07:40:52
![](https://img.aspxhome.com/file/2023/9/59929_0s.jpg)
Mybatis示例讲解注解开发中的单表操作
2023-08-20 06:20:58
![](https://img.aspxhome.com/file/2023/2/67992_0s.png)
mybatis中数据加密与解密的实现
2022-04-21 22:49:16
使用Maven搭建Hadoop开发环境
2021-09-11 07:55:45
Java超详细透彻讲解static
2021-10-13 12:18:34
![](https://img.aspxhome.com/file/2023/4/66034_0s.png)
Java基础之面向对象机制(多态、继承)底层实现
2023-11-12 02:59:59
java中文传值乱码问题的解决方法
2023-11-25 16:26:47
Mybatis使用JSONObject接收数据库查询的方法
2023-01-17 05:10:43
![](https://img.aspxhome.com/file/2023/7/62647_0s.png)
如何用Stream解决两层List属性求和问题
2022-07-31 20:32:35
Java定位问题线程解析
2023-08-09 22:04:27
![](https://img.aspxhome.com/file/2023/1/58041_0s.png)
深入理解ThreadLocal工作原理及使用示例
2022-02-27 19:24:14
![](https://img.aspxhome.com/file/2023/6/62066_0s.png)
使用SpringBoot开发Restful服务实现增删改查功能
2023-01-20 05:17:29
![](https://img.aspxhome.com/file/2023/8/61658_0s.png)
Java实现动态获取图片验证码的示例代码
2023-07-24 22:32:05
Spring框架中@PostConstruct注解详解
2021-09-20 09:35:58
Java详细讲解不同版本的接口语法和抽象类与接口的区别
2022-09-30 01:46:38
![](https://img.aspxhome.com/file/2023/5/61875_0s.png)
详解WPF中的APP生命周期以及全局异常捕获
2022-12-10 11:54:27
Unity中的PostProcessScene实用案例深入解析
2021-06-09 04:57:28