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
0
投稿
猜你喜欢
- IDEA设置文档注释模板创建Class文件时自动生成的头部注释如图如何配置idea的头部注释格式,可以生成像之前的注释格式一样的文档注释?F
- spring的自动装配功能的定义:无须在Spring配置文件中描述javaBean之间的依赖关系(如配置<property>、&
- 这篇文章主要介绍了springboot 定时任务@Scheduled实现解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的
- import java.io.UnsupportedEncodingException;import java.security.Inval
- ${project.basedir}的使用<project> 是 pom.xml 的根节点,project.basedir 就是
- 今天突发奇想,想做一个智能拼图游戏来给哄女友。需要实现这些功能第一图片自定义第二宫格自定义,当然我一开始就想的是3*3 4*4 5*5,没有
- 方法一:实现Comparator接口,并重写compare方法实体类代码:import java.util.Comparator;/** *
- 排查@CacheEvict注解失效我简单看了一下《Spring实战》中的demo,然后就应用到业务代码中了,本以为如此简单的事情,竟然在代码
- 1 原码、反码、补码原码:将十进制转化为二进制即原码;反码:正数的反码与原码相同,负数的反码(除却最高位的符号位不变)与原码相反
- 一个错误:多线程使用单一消费者下图显现了一种错误的使用KafkaConsumer的方法创建多个线程用来消费kafka数据多线程使用同一个Ka
- 一,SQL注入–1,需求–1,利用jdbc查询user的信息,如果信息正确就登录,否则提示错误–1,创建user表,指定字段id name
- 本文实例讲述了Java深度复制功能与用法。分享给大家供大家参考,具体如下:写在前面:什么是深度复制?在Java里面,在创建一个对象,我们通常
- 面试题1:说说什么分布式事务?解释一下什么是CAP?现在互联网开发多使用微服务架构,一个简单的操作,在服务端可能就是由多个服务和数据库实例协
- 操作步骤如下一、dropzone导入01.dropzone官网下载其插件压缩包并复制项目;02.将CSS和JS文件在HTML文件中引入;//
- 一、前言尽管Unity有一个像样的脚本编辑器(Mono),但很多人喜欢使用另一个编辑器。这篇短文解释了如何更改脚本编辑器,并介绍了Mono的
- 在Java的线程执行中,不管是直接继承Thread的方式,还是实现Runnable接口的方式,都不会获取到线程执行的返回结果。这样如果线程在
- java 泛型方法:泛型是什么意思在这就不多说了,而Java中泛型类的定义也比较简单,例如:public class Test
- 三目条件运算公式为 x?y:z 其中x的运算结果为boolean类型,先计算x的值,若为true,则整个三目运算的结果为表达式y
- 一、No serializer found for class org.hibernate.proxy.pojo.bytebuddy.Byt
- 这篇文章主要介绍了Spring如何在一个事务中开启另一个事务,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需