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信息

相关文章
|
安全 Java Apache
微服务——SpringBoot使用归纳——Spring Boot中集成 Shiro——Shiro 身份和权限认证
本文介绍了 Apache Shiro 的身份认证与权限认证机制。在身份认证部分,分析了 Shiro 的认证流程,包括应用程序调用 `Subject.login(token)` 方法、SecurityManager 接管认证以及通过 Realm 进行具体的安全验证。权限认证部分阐述了权限(permission)、角色(role)和用户(user)三者的关系,其中用户可拥有多个角色,角色则对应不同的权限组合,例如普通用户仅能查看或添加信息,而管理员可执行所有操作。
681 0
|
安全 Java 数据安全/隐私保护
微服务——SpringBoot使用归纳——Spring Boot中集成 Shiro——Shiro 三大核心组件
本课程介绍如何在Spring Boot中集成Shiro框架,主要讲解Shiro的认证与授权功能。Shiro是一个简单易用的Java安全框架,用于认证、授权、加密和会话管理等。其核心组件包括Subject(认证主体)、SecurityManager(安全管理员)和Realm(域)。Subject负责身份认证,包含Principals(身份)和Credentials(凭证);SecurityManager是架构核心,协调内部组件运作;Realm则是连接Shiro与应用数据的桥梁,用于访问用户账户及权限信息。通过学习,您将掌握Shiro的基本原理及其在项目中的应用。
511 0
|
前端开发
SpringBoot2.3.1集成Knife4j接口文档
SpringBoot2.3.1集成Knife4j接口文档
1230 44
|
12月前
|
JSON 分布式计算 大数据
springboot项目集成大数据第三方dolphinscheduler调度器
springboot项目集成大数据第三方dolphinscheduler调度器
744 3
|
12月前
|
缓存 JSON 前端开发
第07课:Spring Boot集成Thymeleaf模板引擎
第07课:Spring Boot集成Thymeleaf模板引擎
974 0
第07课:Spring Boot集成Thymeleaf模板引擎
|
12月前
|
Java 关系型数据库 MySQL
springboot项目集成dolphinscheduler调度器 实现datax数据同步任务
springboot项目集成dolphinscheduler调度器 实现datax数据同步任务
1054 2
|
12月前
|
分布式计算 Java 大数据
springboot项目集成dolphinscheduler调度器 可拖拽spark任务管理
springboot项目集成dolphinscheduler调度器 可拖拽spark任务管理
569 2
|
缓存 安全 Java
Shiro简介及SpringBoot集成Shiro(狂神说视频简易版)
Shiro简介及SpringBoot集成Shiro(狂神说视频简易版)
954 7
|
缓存 Java 数据库
SpringBoot集成Ehcache缓存使用指南
以上是SpringBoot集成Ehcache缓存的基本操作指南,帮助你在实际项目中轻松实现缓存功能。当然,Ehcache还有诸多高级特性,通过学习和实践,你可以更好地发挥它的威力。
992 20

热门文章

最新文章