SpringBoot集成JWT(极简版):

news/2024/4/24 7:34:06/文章来源:https://blog.csdn.net/weixin_53791978/article/details/127626819

文章目录

            • 1.JWT依赖
            • 2.JWT工具类TokenUtils.java
            • 3.token示例
            • 4.拦截器JwtInterceptor.java
            • 5.拦截器设置InterceptorConfig.java
            • 6.统一接口WebConfig.java
            • 7.设置自定义头配置 CorsConfig .java
            • 8.GlobalExceptionHandler.java
            • 9.ServiceException.java
            • 10.设置token:
            • 11.最终效果:


在这里插入图片描述

1.JWT依赖
<!-- JWT -->
<dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>3.10.3</version></dependency>
<!-- hutool  -->
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.7.20</version>
</dependency>
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version>
</dependency>
2.JWT工具类TokenUtils.java
package com.example.springboot.utils;import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.springboot.entity.User;
import com.example.springboot.service.IUserService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;@Component
public class TokenUtils {private static IUserService staticUserService;@Resourceprivate IUserService userService;@PostConstructpublic void setUserService() {staticUserService = userService;}/*** 生成token** @return*/public static String genToken(String userId, String sign) {return JWT.create().withAudience(userId) // 将 user id 保存到 token 里面,作为载荷.withExpiresAt(DateUtil.offsetHour(new Date(), 2)) // 2小时后token过期.sign(Algorithm.HMAC256(sign)); // 以 password 作为 token 的密钥}/*** 获取当前登录的用户信息** @return user对象*/public static User getCurrentUser() {try {HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();String token = request.getHeader("token");if (StrUtil.isNotBlank(token)) {String userId = JWT.decode(token).getAudience().get(0);return staticUserService.getById(Integer.valueOf(userId));}} catch (Exception e) {return null;}return null;}
}
3.token示例
{"username":"admin","password":"admin","nickname":"管理员11111","avatarUrl":"https://img-blog.csdnimg.cn/c6d0ece75d3f4833bd820b8aa2eb952b.png","token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxIiwiZXhwIjoxNjQ0MzgxMDI4fQ.87nwS8ENDOu6RY-4PTLBBzXfDv6-5TiQLQhBXrYGb700"}
4.拦截器JwtInterceptor.java
package com.example.springboot.config.interceptor;import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.springboot.common.Constants;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class JwtInterceptor implements HandlerInterceptor {@Autowiredprivate IUserService userService;@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {String token = request.getHeader("token");// 如果不是映射到方法直接通过if(!(handler instanceof HandlerMethod)){return true;}// 执行认证if (StrUtil.isBlank(token)) {throw new ServiceException(Constants.CODE_401, "无token,请重新登录");}// 获取 token 中的 user idString userId;try {userId = JWT.decode(token).getAudience().get(0);} catch (JWTDecodeException j) {throw new ServiceException(Constants.CODE_401, "token验证失败,请重新登录");}// 根据token中的userid查询数据库User user = userService.getById(userId);if (user == null) {throw new ServiceException(Constants.CODE_401, "用户不存在,请重新登录");}// 用户密码加签验证 tokenJWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();try {jwtVerifier.verify(token); // 验证token} catch (JWTVerificationException e) {throw new ServiceException(Constants.CODE_401, "token验证失败,请重新登录");}return true;}
}
5.拦截器设置InterceptorConfig.java
package com.example.springboot.config;import com.example.springboot.config.interceptor.JwtInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class InterceptorConfig implements WebMvcConfigurer {@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(jwtInterceptor()).addPathPatterns("/**")  // 拦截所有请求,通过判断token是否合法来决定是否需要登录.excludePathPatterns("/api/user/login", "/api/user/register", "/**/export", "/**/import");}@Beanpublic JwtInterceptor jwtInterceptor() {return new JwtInterceptor();}
}
6.统一接口WebConfig.java
package com.example.springboot.config;/*** @Author SunPeng* @Date 2022/10/31 20:26* @description 请输入描述*/
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class WebConfig implements  WebMvcConfigurer {@Overridepublic void configurePathMatch(PathMatchConfigurer configurer) {// 指定controller统一的接口前缀configurer.addPathPrefix("/api", clazz -> clazz.isAnnotationPresent(RestController.class));}
}
7.设置自定义头配置 CorsConfig .java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;@Configuration
public class CorsConfig {@Beanpublic CorsFilter corsFilter() {UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();CorsConfiguration corsConfiguration = new CorsConfiguration();corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置return new CorsFilter(source);}
}
8.GlobalExceptionHandler.java
package com.example.springboot.exception;import com.example.springboot.common.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;/*** @Author SunPeng* @Date 2022/10/28 14:56* @description 请输入描述*/
@ControllerAdvice
public class GlobalExceptionHandler {/*** 如果抛出的的是ServiceException,则调用该方法* @param se 业务异常* @return Result*/@ExceptionHandler(ServiceException.class)@ResponseBodypublic Result handle(ServiceException se){return Result.error(se.getCode(), se.getMessage());}
}
9.ServiceException.java
package com.example.springboot.exception;import lombok.Getter;/*** @Author SunPeng* @Date 2022/10/28 14:58* @description 自定义异常*/
@Getter
public class ServiceException extends RuntimeException{private String code;public ServiceException(String code,String msg){super(msg);this.code=code;}
}
10.设置token:

在这里插入图片描述

String token=TokenUtils.genToken(one.getId().toString(),one.getPassword());
userDTO.setToken(token);
11.最终效果:

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_410272.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

离线下IDEA打开拷贝的完整工程,解决工程代码大量报错的问题

一、背景 在日常工作中&#xff0c;代码工程的保存和协作开发一般是通过代码仓库实现的。但是对于正常的多人研究开发时&#xff0c;工程代码的物理拷贝也是需要的&#xff0c;这可以节省工程代码依赖环境的安装和配置&#xff0c;同时也能保证代码完整和版本一致。 在大部分企…

【测试沉思录】9. 数据工厂低代码平台探索与实践

欢迎订阅我的新专栏《现代命令行工具指南》&#xff0c;精讲目前最流行的开源命令行工具&#xff0c;大大提升你的工作效率。 作者&#xff1a;吴锺瑞、刘洪初 编辑&#xff1a;毕小烦 一. 需求背景 造数据可能是日常迭代中最频繁也是最耗时的工作。 我们在20年8月对部门内的…

HashSet实现类的使用

【1】放入Integer类型数据package com.msb.test06;import java.util.HashSet;/*** @author : liu* 日期:10:36:57* 描述:IntelliJ IDEA* 版本:1.0*/ public class TestInteger {//这是一个main方法:是程序的入口public static void main(String[] args) {//创建一个HashSet集合…

Cannon.js -- 3d物理引擎

文章目录前言一、关于Cannon.js二、Cannon.js的使用最后注意点&#xff1a;优化事件其他本文完整代码下载&#xff1a;相关链接&#xff1a;前言 本篇将介绍Cannon.js -- 3d物理引擎的基础使用&#xff0c;并用Cannon.js与three.js写一个简单的demo 一、关于Cannon.js Q&…

什么是轮廓阴影和圆角

目录 outline box-shadow 将元素设置为一个圆形 outline outline 用来设置元素的轮廓线&#xff0c;用法和border一模一样 轮廓和边框不同的点&#xff0c;就是轮廓不会影响到可见框的大小 <!DOCTYPE html> <html lang"en"> <head><meta ch…

【CV】第 6 章:使用迁移学习的视觉搜索

&#x1f50e;大家好&#xff0c;我是Sonhhxg_柒&#xff0c;希望你看完之后&#xff0c;能对你有所帮助&#xff0c;不足请指正&#xff01;共同学习交流&#x1f50e; &#x1f4dd;个人主页&#xff0d;Sonhhxg_柒的博客_CSDN博客 &#x1f4c3; &#x1f381;欢迎各位→点赞…

Protocol Buffers学习【Qt】

文章目录参考前言开发环境# 一、下载1. 打开网页2. 点击download3. 下载二、 编译1. 解压2. 用QC打开项目3. 编译并等待4. 打开 extract_includes.bat5. 新建lib文件夹三、使用1. 新建 lm.helloworld.proto2. Qt 新建 HelloProtobuf 子目录项目3. lib_protobuf 目录4. Writer 工…

腾讯云创建SVN支持多人协同办公

本文参考自&#xff1a; 如何在腾讯云轻量级服务器搭建svn_我的天才女友的博客-CSDN博客_腾讯云 svn 搭建SVN服务器-腾讯云 - 夜页子 - 博客园 一、配置要求 选择腾讯云CentOS的镜像进行安装 二、SVN服务端 1.SVN服务端的安装 yum install subversion 接下来输入y按回车继…

C语言练习---【求素数】(一篇带你掌握素数求解)

&#x1f996;作者&#xff1a;学写代码的恐龙 &#x1f996;博客主页&#xff1a;学写代码的恐龙博客主页 &#x1f996;专栏&#xff1a;【初级c语言】 &#x1f996;语录&#xff1a;❀未来的你&#xff0c;一定会感谢现在努力奋斗的自己❀ C语言练习---【求素数】&#x1…

数据分析 | Pandas 200道练习题,每日10道题,学完必成大神(7)

文章目录前期准备1. 以df的列名创建一个DataFrame2. 打印所有换手率为非数字的行3. 删除所有换手率为非数字的行4. 重置df的行号5. 绘制‘还手’密度曲线6. 计算后一天和前一天收盘价的差值7. 计算后一天与前一天收盘价的变化率8. 设置时间索引9. 使用时间索引&#xff0c;分别…

JavaScript 49 JavaScript 作用域

JavaScript 文章目录JavaScript49 JavaScript 作用域49.1 JavaScript 函数作用域49.2 局部 JavaScript 变量49.3 全局 JavaScript 变量49.4 JavaScript 变量49.5 自动全局49.6 严格模式49.7 HTML 中的全局变量49.8 警告49.9 JavaScript 变量的有效期49.10 函数参数49 JavaScrip…

Mysql深度解析(一)索引底层数据结构与算法

MySQL底层索引是用B树实现的 传送门&#xff1a;什么是B-树、B树、B*树 传送门&#xff1a;深入理解MySQL索引底层数据结构与算法 传送门&#xff1a;MySQL中Innodb的索引 1 索引是什么? 索引&#xff1a;帮助Mysql高效获取数据的排好序的数据结构。 2 Mysql索引为什么用…

Sping的IoC容器和依赖注入

IoC Inversion of Control 使用对象时&#xff0c;由主动new产生对象转换为由外部提供对象&#xff0c;此过程中对象创建控制权由程序转移到外部&#xff0c;此思想称为控制反转 Spring实现了IoC的思想&#xff0c;Spring提供了一个容器&#xff0c;称为IoC容器&#xff0c;用…

【CSS】CSS选择器全解指南【CSS基础知识详解】

&#x1f468;‍&#x1f4bb;个人主页&#xff1a;花无缺 欢迎 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! 本文由 花无缺 原创 本文章收录于专栏 【CSS】 【CSS专栏】已发布文章 &#x1f4c1;【CSS基础认知】 本文目录【CSS选择器全解指南】&#x1f319;CSS注…

SpringBoot 转发请求至指定页面

1、前言 原先的页面访问地址为&#xff1a;http://127.0.0.1:8888/office/schdule/index/&#xff0c; 重构项目&#xff0c;SpringBoot 项目&#xff0c;前后分离&#xff0c;前端文件放置静态目录&#xff08;static&#xff09;下&#xff0c;访问地址&#xff1a;http://12…

计算机毕业设计(附源码)python疫情管理系统

项目运行 环境配置&#xff1a; Pychram社区版 python3.7.7 Mysql5.7 HBuilderXlist pipNavicat11Djangonodejs。 项目技术&#xff1a; django python Vue 等等组成&#xff0c;B/S模式 pychram管理等等。 环境需要 1.运行环境&#xff1a;最好是python3.7.7&#xff0c;…

URP下的OffScreen Particle Render

【博物纳新】专栏是UWA旨在为开发者推荐新颖、易用、有趣的开源项目,帮助大家在项目研发之余发现世界上的热门项目、前沿技术或者令人惊叹的视觉效果,并探索将其应用到自己项目的可行性。很多时候,我们并不知道自己想要什么,直到某一天我们遇到了它。随着越来越多的项目使用…

jsp个人评价管理系统Myeclipse开发mysql数据库web结构java编程计算机网页项目

一、源码特点 JSP 个人评价管理系统 是一套完善的web设计系统&#xff0c;对理解JSP java编程开发语言有帮助&#xff0c;系统具有完整的源代码和数据库&#xff0c;系统主要采用B/S模式开发。开发环境为 TOMCAT7.0,Myeclipse8.5开发&#xff0c;数据库为Mysql&#xff0c;使…

多模态自编码器从EEG信号预测fNIRS静息态

导读 本研究介绍了一种深度学习架构&#xff0c;用于评估40名癫痫患者的多模态脑电图(EEG)和功能性近红外光谱(fNIRS)记录。长短期记忆网络和卷积神经网络集成在一个多模态序列到序列的自编码器中。训练后的神经网络通过从EEG全谱和特定EEG频段中分层提取深度特征&#xff0c;…