SpringBoot集成JWT(极简版)
话不多说,直接上代码
接口统一前缀设置
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));}
}
JWT POM依赖
<dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>3.10.3</version></dependency>
JWT工具类TokenUtils.java
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.Admin;
import com.example.springboot.service.IAdminService;
import lombok.extern.slf4j.Slf4j;
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
@Slf4j
public class TokenUtils {private static IAdminService staticAdminService;@Resourceprivate IAdminService adminService;@PostConstructpublic void setUserService() {staticAdminService = adminService;}/*** 生成token** @return*/public static String genToken(String adminId, String sign) {return JWT.create().withAudience(adminId) // 将 user id 保存到 token 里面,作为载荷.withExpiresAt(DateUtil.offsetHour(new Date(), 2)) // 2小时后token过期.sign(Algorithm.HMAC256(sign)); // 以 password 作为 token 的密钥}/*** 获取当前登录的用户信息** @return user对象* /admin?token=xxxx*/public static Admin getCurrentAdmin() {String token = null;try {HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();token = request.getHeader("token");if (StrUtil.isNotBlank(token)) {token = request.getParameter("token");}if (StrUtil.isBlank(token)) {log.error("获取当前登录的token失败, token: {}", token);return null;}String adminId = JWT.decode(token).getAudience().get(0);return staticAdminService.getById(Integer.valueOf(adminId));} catch (Exception e) {log.error("获取当前登录的管理员信息失败, token={}", token, e);return null;}}
}
拦截器JwtInterceptor.java
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.JWTVerificationException;
import com.example.springboot.entity.Admin;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.service.IAdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {private static final String ERROR_CODE_401 = "401";@Autowiredprivate IAdminService adminService;@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {String token = request.getHeader("token");if (StrUtil.isBlank(token)) {token = request.getParameter("token");}// 执行认证if (StrUtil.isBlank(token)) {throw new ServiceException(ERROR_CODE_401, "无token,请重新登录");}// 获取 token 中的adminIdString adminId;Admin admin;try {adminId = JWT.decode(token).getAudience().get(0);// 根据token中的userid查询数据库admin = adminService.getById(Integer.parseInt(adminId));} catch (Exception e) {String errMsg = "token验证失败,请重新登录";log.error(errMsg + ", token=" + token, e);throw new ServiceException(ERROR_CODE_401, errMsg);}if (admin == null) {throw new ServiceException(ERROR_CODE_401, "用户不存在,请重新登录");}try {// 用户密码加签验证 tokenJWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(admin.getPassword())).build();jwtVerifier.verify(token); // 验证token} catch (JWTVerificationException e) {throw new ServiceException(ERROR_CODE_401, "token验证失败,请重新登录");}return true;}
}
拦截器设置
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class WebConfig implements WebMvcConfigurer {@AutowiredJwtInterceptor jwtInterceptor;@Overridepublic void configurePathMatch(PathMatchConfigurer configurer) {// 指定controller统一的接口前缀configurer.addPathPrefix("/api", clazz -> clazz.isAnnotationPresent(RestController.class));}// 加自定义拦截器JwtInterceptor,设置拦截规则@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(jwtInterceptor).addPathPatterns("/api/**");}
}
设置自定义头配置
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);}
}
SpringBoot集成JWT(极简版)相关推荐
- 7句话让Codex给我做了个小游戏,还是极简版塞尔达,一玩简直停不下来
点击上方"视学算法",选择加"星标"或"置顶" 重磅干货,第一时间送达 梦晨 萧箫 发自 凹非寺 量子位 | 公众号 QbitAI 什么,7 ...
- 10分钟手撸极简版ORM框架!
最近很多小伙伴对ORM框架的实现很感兴趣,不少读者在冰河的微信上问:冰河,你知道ORM框架是如何实现的吗?比如像MyBatis和Hibernte这种ORM框架,它们是如何实现的呢? 为了能够让小伙伴们 ...
- 美团推出极简版 为用户提供“米面粮油”等生活用品采购服务
近日,有用户反馈,安卓应用商店显示,美团更新推出了极简版,对主应用的功能进行了删减,保留了美团主应用中涉及生活用品采购的相关业务.用户在打开极简版后,首页会呈现出采购蔬果.米面水油等生活用品的购买入口 ...
- python3web库_基于 Python3 写的极简版 webserver
基于 Python3 写的极简版 webserver.用于学习 HTTP协议,及 WEB服务器 工作原理.笔者对 WEB服务器 的工作原理理解的比较粗浅,仅是基于个人的理解来写的,存在很多不足和漏洞, ...
- openGauss 极简版安装
openGauss 官网 openGauss 下载地址 支持的操作系统 ● ARM: ● openEuler 20.03LTS(推荐采用此操作系统) ● 麒麟V10 ● Asianux ...
- SpringBoot集成JWT实现Token登录验证
目录 1.1 JWT是什么? 1.2 JWT主要使用场景 1.3 JWT请求流程 1.4 JWT结构 二,SpringBoot集成JWT具体实现过程 2.1添加相关依赖 2.2自定义跳出拦截器的注解 ...
- JWT springboot集成jWT
1.1官网介绍 地址:https://jwt.io/ JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compac ...
- Underscore源码阅读极简版入门
看了网上的一些资料,发现大家都写得太复杂,让新手难以入门.于是写了这个极简版的Underscore源码阅读. 源码: github.com/hanzichi/un- 一.架构的实现 1.1:架构 (f ...
- 《重大人生启示录》极简版
<重大人生启示录>极简版 献给所有活着和将要死去的人们,献给所有历经悲伤的人们 本文摘录了启示录最重要的内容,不必非要看全本,不必购买书 序言 这是极为特殊的历史转折期,物质文明发展到这一 ...
- 【极简版GH60】【GH60剖析】【六】修改配列
说完了GH60的硬件部分,接下来到软件部分,我觉得,软件部分才是极简版GH60的精髓部分,毕竟仅有硬件的话GH60只是一个有手感可以按动的一堆没有功能的按键,而软件让他变成了灵活多变的键盘.通过对软件 ...
最新文章
- 微服务治理平台的RPC方案实现
- 如何看待Spring下单例模式与线程安全的矛盾
- 树与二叉树 | 实验3:由遍历序列构造二叉树
- 关于如何在Nomad中保护工作部署的工作流的简要历史
- ios 后台唤醒应用_手机应用后台不断唤醒,耗电大,荣耀手机只需简单几步就可以解决...
- mysql -s 参数_mysqldump 的常用参数。
- Misc-wireshark-1(秒懂!!)
- 问:一行Python代码到底能干多少事情?(二)
- Android ListView侧滑item,仿QQ删除效果
- 编程题: 将一个矩阵(二维数组)顺时针旋转90度
- android分辨率px跟dp,Android屏幕适配 px,dp,dpi及density的关系与深入理解
- LeetCode 153 寻找旋转排序数组中的最小值
- idea生成类中序列化id
- 理解 Delphi 的类(十) - 深入方法[15] - 调用其他单元的函数
- Visual Studio 2010全球发布会 上海站(图)
- 业界大佬患互联网手机焦虑症 圈地运动骤然爆发
- 启明星数据库批量备份与还原工具
- 全国地级市坐标、名称、编码获取 / 全球城市坐标位置
- Unity 接入百度AI - Logo商标识别
- 试题 基础练习 序列求和