Spring Boot 2结合Spring security + JWT实现微信小程序登录
作者:tanwubo 发布时间:2022-07-14 08:25:54
标签:Spring,Boot,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";
}
}
来源:https://blog.csdn.net/qq_22606825/article/details/100047498


猜你喜欢
- 在spring的一个controller中要把参数传到页面,只要配置视图解析器,把参数添加到Model中,在页面用el表达式就可以取到。但是
- 关于mybatis基础我们前面几篇博客已经介绍了很多了,今天我们来说一个简单的问题,那就是mybatis中的缓存问题。mybatis本身对缓
- 本文源码:GitHub·点这里 || GitEE·点这里一、Ehcache缓存简介1、基础简介EhCache是一个纯Java的进程内缓存框架
- 好久就想着好好搭建一个ssm框架,自己以后用也方便吧,但是最近的事真的是很多,很多事情都没有去干,有时候自己会怀疑一下人生自己该不该去做程序
- Android本地存储SharedPreferences详解存储位置SharedPreferences数据保存在: /data /data/
- 一、图示spring再简化:SpringBoot-jar:内嵌tomacat;微服务架构!二、springboot是什么spring是一个为
- 前言 用过微信的都知道,微信对话列表滑动删除效果是很不错的,这个效果我们也可以有。思路其实很简单,弄个ListView,然后里面的
- 一、什么是反射Java Reflaction in Action中的解释:反射是运行中的程序检查自己和软件运行环境的能力,它可以根据它发现的
- Framework如何实现Binder为了日常的使用framework层同样实现了一套binder的接口。可以肯定的是framework使用
- 目录例1: 以下代码输出什么?例2: 为什么虚函数效率低?虚继承例3: 请评价多重继承的优点和缺陷。例4: 在多继承的时候,如果一个类继承同
- 1.通过看logcat下的日志2.通过adb命令3.通过写代码获取3.1写一个工具类打印系统时间3.2 在Application启动的时候打
- 设计模式通常分为三个主要类别:创建型模式结构型模式行为型模式。这些模式是用于解决常见的对象导向设计问题的最佳实践。以下是23种常见的设计模式
- 看过阿里巴巴开发手册的同学应该都会对Integer临界值127有点印象。原文中写的是:【强制】所有整型包装类对象之间值的比较,全部使用 eq
- 前言 同源策略:判断是否是同源的,主要看这三点,协议,ip,端口。同源策略就是浏览器出于网站安全性的考虑,限制不同源之间的资源相互访问的一种
- 具体如下: XML文件:文件在MyDocument文件夹下 <?xml version="1.0" encodin
- 使用simplecommand下载网络图片,并显示到ImageView控件上。1 在app module的build.gradle将simp
- Mybatis映射文件mapper.xml的注释问题从昨天夜晚9点到今天中午,一直被项目bug所困惑,中间这段时间一直未解决这个问题,也咨询
- 目录前言Lottie案例尝试1. 集成依赖2. 添加 LottieAnimationView 加载网络资源3. 加载本地资源4. 循环播放
- 什么是断点续传用户上传大文件,网络差点的需要历时数小时,万一线路中断,不具备断点续传的服务器就只能从头重传,而断点续传就是,允许用户从上传断
- 场景:PageHelper 的默认分页方案是 select count(0) from (你的sql) table_count由于查询数据比