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

简介: 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信息

相关文章
|
JSON 安全 Java
什么是JWT?如何使用Spring Boot Security实现它?
什么是JWT?如何使用Spring Boot Security实现它?
2134 5
|
10月前
|
安全 Java Apache
微服务——SpringBoot使用归纳——Spring Boot中集成 Shiro——Shiro 身份和权限认证
本文介绍了 Apache Shiro 的身份认证与权限认证机制。在身份认证部分,分析了 Shiro 的认证流程,包括应用程序调用 `Subject.login(token)` 方法、SecurityManager 接管认证以及通过 Realm 进行具体的安全验证。权限认证部分阐述了权限(permission)、角色(role)和用户(user)三者的关系,其中用户可拥有多个角色,角色则对应不同的权限组合,例如普通用户仅能查看或添加信息,而管理员可执行所有操作。
532 0
|
12月前
|
XML JavaScript Java
SpringBoot集成Shiro权限+Jwt认证
本文主要描述如何快速基于SpringBoot 2.5.X版本集成Shiro+JWT框架,让大家快速实现无状态登陆和接口权限认证主体框架,具体业务细节未实现,大家按照实际项目补充。
859 11
|
JSON 安全 算法
Spring Boot 应用如何实现 JWT 认证?
Spring Boot 应用如何实现 JWT 认证?
1190 8
|
SQL NoSQL 关系型数据库
|
消息中间件 监控 Java
您是否已集成 Spring Boot 与 ActiveMQ?
您是否已集成 Spring Boot 与 ActiveMQ?
428 0
|
JavaScript NoSQL Java
CC-ADMIN后台简介一个基于 Spring Boot 2.1.3 、SpringBootMybatis plus、JWT、Shiro、Redis、Vue quasar 的前后端分离的后台管理系统
CC-ADMIN后台简介一个基于 Spring Boot 2.1.3 、SpringBootMybatis plus、JWT、Shiro、Redis、Vue quasar 的前后端分离的后台管理系统
463 0
|
3月前
|
JavaScript Java 关系型数据库
基于springboot的项目管理系统
本文探讨项目管理系统在现代企业中的应用与实现,分析其研究背景、意义及现状,阐述基于SSM、Java、MySQL和Vue等技术构建系统的关键方法,展现其在提升管理效率、协同水平与风险管控方面的价值。