Springboot最全权限集成Redis-前后端分离-springsecurity-jwt-Token5

本文涉及的产品
服务治理 MSE Sentinel/OpenSergo,Agent数量 不受限
简介: Springboot最全权限集成Redis-前后端分离-springsecurity-jwt-Token5

3.6.6 配置token验证过滤器类

将CheckTokenFilter过滤器类交给Spring Security进行管理,在SpringSecurityConfig配置类中添加如下代 码。

private CheckTokenFilter checkTokenFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
//登录前进行过滤
http.addFilterBefore(checkTokenFilter,
UsernamePasswordAuthenticationFilter.class);
http.formLogin()
//省略后续代码....
}

3.6.7 编写自定义异常类
```package com.manong.config.security.exception;
import org.springframework.security.core.AuthenticationException;
/**

  • 自定义验证异常类
    /
    public class CustomerAuthenticationException extends AuthenticationException {
    public CustomerAuthenticationException(String message){
    super(message);
    }
    }
    3.6.8 token验证失败处理 在LoginFailureHandler用户认证失败处理类中加入判断。/*
  • 用户认证失败处理类
    */
    @Component
    public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
    HttpServletResponse response,
    AuthenticationException exception) throws
    IOException, ServletException {
    //设置客户端响应编码格式
    response.setContentType("application/json;charset=UTF-8");
    //获取输出流
    ServletOutputStream outputStream = response.getOutputStream();
    String message = null;//提示信息
    int code = 500;//错误编码
    //判断异常类型
    if(exception instanceof AccountExpiredException){
    message = "账户过期,登录失败!";
    }else if(exception instanceof BadCredentialsException){
    message = "用户名或密码错误,登录失败!";
    }else if(exception instanceof CredentialsExpiredException){
    message = "密码过期,登录失败!";
    }else if(exception instanceof DisabledException){
    message = "账户被禁用,登录失败!";
    }else if(exception instanceof LockedException){
    message = "账户被锁,登录失败!";
    }else if(exception instanceof InternalAuthenticationServiceException){
    message = "账户不存在,登录失败!";
    }else if(exception instanceof CustomerAuthenticationException){
    message = exception.getMessage();
    code = 600;
    }else{
    message = "登录失败!";
    }
    //将错误信息转换成JSON
    String result =
    JSON.toJSONString(Result.error().code(code).message(message));
    outputStream.write(result.getBytes(StandardCharsets.UTF_8));
    outputStream.flush();
    outputStream.close();
    }
    }
3.6.9 认证成功处理 修改LoginSuccessHandler登录认证成功处理类,将token保存到Redis缓存中。
```@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
@Resource
private JwtUtils jwtUtils;
@Resource
private RedisService redisService;
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication) throws IOException,
ServletException {
//省略原有代码......
//把生成的token存到redis
String tokenKey = "token_"+token;
redisService.set(tokenKey,token,jwtUtils.getExpiration() / 1000);
}
}

3.7.2 编写刷新token方法 在com.manong.controller包下创建SysUserController控制器类,并在该类中编写refreshToken刷新token的 方法。

@RequestMapping("/api/sysUser")
public class SysUserController {
@Resource
private RedisService redisService;
@Resource
private JwtUtils jwtUtils;
/**
* 刷新token
*
* @param request
* @return
*/
@PostMapping("/refreshToken")
public Result refreshToken(HttpServletRequest request) {
//从header中获取前端提交的token
String token = request.getHeader("token");
//如果header中没有token,则从参数中获取
if (ObjectUtils.isEmpty(token)) {
token = request.getParameter("token");
}
//从Spring Security上下文获取用户信息
Authentication authentication =
SecurityContextHolder.getContext().getAuthentication();
//获取身份信息
UserDetails details = (UserDetails) authentication.getPrincipal();
//重新生成token
String reToken = "";
//验证原来的token是否合法
if (jwtUtils.validateToken(token, details)) {
//生成新的token
reToken = jwtUtils.refreshToken(token);
}
//获取本次token的到期时间,交给前端做判断
long expireTime = Jwts.parser().setSigningKey(jwtUtils.getSecret())
.parseClaimsJws(reToken.replace("jwt_", ""))
.getBody().getExpiration().getTime();
//清除原来的token信息
String oldTokenKey = "token_" + token;
redisService.del(oldTokenKey);
//存储新的token
String newTokenKey = "token_" + reToken;
redisService.set(newTokenKey, reToken, jwtUtils.getExpiration() / 1000);
//创建TokenVo对象
TokenVo tokenVo = new TokenVo(expireTime, reToken);
//返回数据
return Result.ok(tokenVo).message("token生成成功");
}
}

3.7.3 接口运行测试 1. 先运行用户登录请求,生成token信息 2. 测试查询全部用户信息,预期结果是查询成功 3. 运行刷新token接口,重新生成token信息

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore     ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库 ECS 实例和一台目标数据库 RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
19天前
|
消息中间件 Java Kafka
Springboot集成高低版本kafka
Springboot集成高低版本kafka
|
25天前
|
NoSQL Java Redis
SpringBoot集成Redis解决表单重复提交接口幂等(亲测可用)
SpringBoot集成Redis解决表单重复提交接口幂等(亲测可用)
285 0
|
30天前
|
NoSQL Java Redis
SpringBoot集成Redis
SpringBoot集成Redis
427 0
|
1月前
|
NoSQL Java Redis
小白版的springboot中集成mqtt服务(超级无敌详细),实现不了掐我头!!!
小白版的springboot中集成mqtt服务(超级无敌详细),实现不了掐我头!!!
272 1
|
19天前
|
安全 数据安全/隐私保护
Springboot+Spring security +jwt认证+动态授权
Springboot+Spring security +jwt认证+动态授权
|
1天前
|
安全 关系型数据库 MySQL
node实战——后端koa结合jwt连接mysql实现权限登录(node后端就业储备知识)
node实战——后端koa结合jwt连接mysql实现权限登录(node后端就业储备知识)
10 3
|
2天前
|
Java Docker 容器
SpringBoot项目集成XXL-job
SpringBoot项目集成XXL-job
|
4天前
|
Java 关系型数据库 数据库
【SpringBoot系列】微服务集成Flyway
【4月更文挑战第7天】SpringBoot微服务集成Flyway
【SpringBoot系列】微服务集成Flyway
|
19天前
|
SQL Java 调度
SpringBoot集成quartz定时任务trigger_state状态ERROR解决办法
SpringBoot集成quartz定时任务trigger_state状态ERROR解决办法
|
19天前
|
JSON 安全 关系型数据库
SpringCloud Gateway 实现自定义全局过滤器 + JWT权限验证
SpringCloud Gateway 实现自定义全局过滤器 + JWT权限验证