SpringBoot Vue使用Jwt实现简单的权限管理

ops/2024/9/23 9:21:26/

为实现Jwt简单的权限管理,我们需要用Jwt工具来生成token,也需要用Jwt来解码token,同时需要添加Jwt拦截器来决定放行还是拦截。下面来实现:

1、gradle引入Jwt、hutool插件

    implementation 'com.auth0:java-jwt:3.10.3'implementation 'cn.hutool:hutool-all:5.3.7'

2、Jwt工具类,提供静态方法生成token,和根据请求携带的token查找user信息

package com.zzz.simple_blog_backend.utils;import ......@Component
public class JwtTokenUtils {@Autowiredprivate UserService userService;private static UserService userServiceStatic;@PostConstruct//在spring容器初始化后执行该方法public void setUserService() {userServiceStatic = userService;}//生成Tokenpublic static String genToken(String userId,String passwordSign) {return JWT.create().withAudience(userId)//放入载荷.withExpiresAt(DateUtil.offsetHour(new Date(), 2))//2小时后过期.sign(Algorithm.HMAC256(passwordSign));//密码签名作为密钥}//通过token获取当前登录用户信息public static User getCurrentUser() {String token = null;HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();//1、获取tokentoken = request.getHeader("token");if (StrUtil.isBlank(token)) {token = request.getParameter("token");}if (StrUtil.isBlank(token)) {throw new RuntimeException("没有token,请重新登录");}String userId;User user;try {userId = JWT.decode(token).getAudience().get(0);} catch (Exception e) {throw new RuntimeException("token验证失败,请重新登录!!!");}user = userServiceStatic.findById(Integer.parseInt(userId));if(user==null) {throw new RuntimeException("用户id不存在,请重新登录!!!");}//3、用密码签名,解码判断tokentry {JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();jwtVerifier.verify(token);} catch (JWTVerificationException e) {throw new CustomException(001, "token验证失败,请重新登录!!!");}return user;}
}

3、Jwt拦截器

SpringBoot添加拦截器,excludePathPatterns可以指定不拦截的页面,RestController指定了请求前缀,控制器类要用@RestController代替@ControlleraddInterceptor添加了jwtInterceptor拦截器。

package com.zzz.simple_blog_backend.config;import ...@Configuration
public class WebConfig implements WebMvcConfigurer{@Autowiredprivate JwtInterceptor jwtInterceptor;@Overridepublic void configurePathMatch(PathMatchConfigurer configurer) {//指定restcontroller统一接口前缀configurer.addPathPrefix("/api", clazz -> clazz.isAnnotationPresent(RestController.class));}@Overridepublic void addInterceptors(InterceptorRegistry registry) {// 加自定义拦截器  给特定请求放行registry.addInterceptor(jwtInterceptor).addPathPatterns("/api/**").excludePathPatterns("/api/user/login","/api/user/register");}
}

仔细的童靴会发现JwtTokenUtils.getCurrentUser()方法和JwtInterceptor的拦截方法很像,主要区别就在if(user.getRole()!=0)的判断。所以JwtInterceptor只会给管理员放行,如果需要给普通用户放行而未登录用户不放行,那请求路径先添加到excludePathPatterns,并且控制类对应的响应方法第一句就先调用JwtTokenUtils.getCurrentUser()判断是否用户已登录。

package com.zzz.simple_blog_backend.config;import ......@Component
public class JwtInterceptor implements HandlerInterceptor{@Autowiredprivate UserService userService;@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {//1、获取tokenString token = request.getHeader("token");if (StrUtil.isBlank(token)) {token = request.getParameter("token");}if (StrUtil.isBlank(token)) {throw new RuntimeException("没有token,请重新登录");}//2、开始认证    解码token,获得userIdString userId;User user;try {userId = JWT.decode(token).getAudience().get(0);} catch (Exception e) {throw new RuntimeException("token验证失败,请重新登录!!!");}user = userService.findById(Integer.parseInt(userId));if(user==null) {throw new RuntimeException("用户id不存在,请重新登录!!!");}if(user.getRole()!=0) {throw new RuntimeException("非管理员账号,无权访问!!!");}//3、用密码签名,解码判断tokentry {JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();jwtVerifier.verify(token);} catch (JWTVerificationException e) {throw new RuntimeException("token验证失败,请重新登录!!!");}//token验证成功,放行return true;
//        return HandlerInterceptor.super.preHandle(request, response, handler);}
}

4、前后端登录操作

登录后 后端返回带token不带密码的user数据

    @PostMapping("user/login")@ResponseBodypublic CommonResult<Object> login(@RequestBody User user){user = userService.findByUsernameAndPassword(user);if (user == null) {return CommonResult.failed(001, Message.createMessage("用户名或密码错误!!!"));} else {//生成用户对应的TokenString token = JwtTokenUtils.genToken(user.getId().toString(), user.getPassword());user.setToken(token);//不传输密码user.setPassword("");return CommonResult.success(user);}}

前端保存带token的user

//axios的post请求成功后操作localStorage.setItem("user",JSON.stringify(response.data.data));//保存用户信息

5、前端每次请求都携带token信息

假设已安装axios,Axios.interceptors.request拦截用户所有请求,添加token信息后再发送请求,这样后端就可以判断了。

import Axios from 'axios'Vue.prototype.$http = Axios;
//添加向后端发起请求的服务器地址前缀
Axios.defaults.baseURL=AIOS_BASE_URL;   // "http://127.0.0.1/api"
//设置请求超时时间
Axios.defaults.timeout=5000;//axios拦截器
//对接口request拦截
Axios.interceptors.request.use(function(config){//发起增删改查请求时,带上token认证var user = localStorage.getItem("user");if(user){config.headers["token"] = JSON.parse(user).token;}return config;
})
//携带证书 session id 跨域请求的话需要
Axios.defaults.withCredentials = true

总结

Jwt实现权限管理的原理是登录成功后 后端端生成token密钥,随着用户信息发送给客户端,客户端接受并保存信息到本地localStorage。以后每次需要权限验证时,根据客户端返回的携带token信息,后端进行拦截并解码校验,通过则放行,否则抛异常。如果要抛异常时,返回错误信息给前端,请看链接。


http://www.ppmy.cn/ops/84830.html

相关文章

MySQL数据库(基础篇)

&#x1f30f;个人博客主页&#xff1a;心.c 前言&#xff1a;今天讲解的是MySQL的详细知识点的&#xff0c;希望大家可以收货满满&#xff0c;话不多说&#xff0c;直接开始搞&#xff01; &#x1f525;&#x1f525;&#x1f525;文章专题&#xff1a;MySQL &#x1f63d;感…

数据分析详解

一、数据分析教程 1. 入门教程 在线课程&#xff1a;如Coursera、Udemy、网易云课堂等平台提供了大量数据分析的入门课程&#xff0c;涵盖统计学基础、Python/R语言编程、数据可视化等内容。书籍推荐&#xff1a;《Python数据分析实战》、《R语言实战》等书籍是数据分析入门的…

Redis在SpringBoot中遇到的问题:预热,雪崩,击穿,穿透

缓存预热 预热即在产品上线前&#xff0c;先对产品进行访问或者对产品的Redis中存储数据。 原因&#xff1a; 1. 请求数量较高 2. 主从之间数据吞吐量较大&#xff0c;数据同步操作频度较高,因为刚刚启动时&#xff0c;缓存中没有任何数据 解决方法&#xff1a; 1. 使用脚…

electron 网页TodoList应用打包win桌面软件数据持久化

参考&#xff1a; electron 网页TodoList工具打包成win桌面应用exe https://blog.csdn.net/weixin_42357472/article/details/140648621 electron直接打包exe应用&#xff0c;打开网页上面添加的task在重启后为空&#xff0c;历史没有被保存&#xff0c;需要持久化工具保存之前…

C++STL初阶(8):list的简易实现(上)

经过对list的使用的学习&#xff0c;我们模拟STL库中的list&#xff0c;实现自己的list 目录 1.观察库中的链表的实现 2.list的实现 2.1 基本结构 2.2 基本接口 3.迭代器&#xff08;本篇重点&#xff09; 3.1 迭代器的构建 3.2 联系list 3.3 ListIterato…

Centos安装、迁移gitlab

Centos安装迁移gitlab 一、下载安装二、配置rb修改&#xff0c;起服务。三、访问web&#xff0c;个人偏好设置。四、数据迁移1、查看当前GitLab版本2、备份旧服务器的文件3、将上述备份文件拷贝到新服务器同一目录下&#xff0c;恢复GitLab4、停止新gitlab数据连接服务5、恢复备…

Ubuntu设置时区

Ubuntu设置时区 在 Ubuntu 中设置时区可以通过以下几个步骤来完成&#xff1a; 方法一&#xff1a;使用命令行 查看当前时区设置&#xff1a; 可以使用以下命令查看当前系统的时区设置&#xff1a; timedatectl如果你想要详细信息&#xff0c;可以运行&#xff1a; timedatec…

SpringBoot3 JDK21 Vue3开源后台RBAC管理系统 | 2024年好用的开源RBAC管理系统 | 数据权限的探索

序言 项目现已全面开源&#xff0c;商业用途完全免费&#xff01; 当前版本&#xff1a;v0.7.2。 如果喜欢这个项目或支持作者&#xff0c;欢迎Star、Fork、Watch 一键三连 &#x1f680;&#xff01;&#xff01; 在构建此代码框架的过程中&#xff0c;我已投入了大量精力&…