Spring Boot JWT 用户认证
JWT token验证后,通过 ThreadLocal 进行传值
https://jwt.io/#debugger 官网提供的 JAVA 工具还是挺多的,选了个 Star 比较多的
https://github.com/jwtk/jjwt
代码结构如图:需要源码联系QQ:47262947

1. 添加 Maven 引用
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.0</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred -->
<version>0.11.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.7</version>
</dependency>
2. 添加 annotation JwtIgnore 用于忽略不需要验证的接口
package com.vipsoft.web.boot.annotation;
import java.lang.annotation.*;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface JwtIgnore {
}
3. 添加工具类 JwtUtils
package com.vipsoft.web.boot.utils; import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; import java.util.Date; @ConfigurationProperties(prefix = "vipsoft.jwt")
@Component
public class JwtUtils {
private Logger logger = LoggerFactory.getLogger(getClass());
private String secret;
private long expire;
private String header; /**
* 生成jwt token
*/
public String generateToken(long userId) {
Date nowDate = new Date();
//过期时间
Date expireDate = new Date(nowDate.getTime() + expire * 1000); return Jwts.builder()
.setHeaderParam("typ", "JWT")
.setSubject(userId+"") //这边不加“”的话,取的时候可能会报过期
.setIssuedAt(nowDate)
.setExpiration(expireDate)
.signWith(SignatureAlgorithm.HS256, secret)
.compact();
} public Claims getClaimByToken(String token) {
try {
return Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
}catch (Exception e){
logger.debug("validate is token error ", e);
return null;
}
} /**
* token是否过期
* @return true:过期
*/
public boolean isTokenExpired(Date expiration) {
return expiration.before(new Date());
} public String getSecret() {
return secret;
} public void setSecret(String secret) {
this.secret = secret;
} public long getExpire() {
return expire;
} public void setExpire(long expire) {
this.expire = expire;
} public String getHeader() {
return header;
} public void setHeader(String header) {
this.header = header;
}
}
4. 添加拦截器 AuthorizationInterceptor
package com.vipsoft.web.boot.interceptor; import cn.hutool.core.util.StrUtil;
import com.vipsoft.web.boot.annotation.JwtIgnore;
import com.vipsoft.web.boot.exception.CustomException;
import com.vipsoft.web.boot.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; @Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired
private JwtUtils jwtUtils; public static final String USER_KEY = "userId"; @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 忽略带JwtIgnore注解的请求, 不做后续token认证校验
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
JwtIgnore jwtIgnore = handlerMethod.getMethodAnnotation(JwtIgnore.class);
if (jwtIgnore != null) {
return true;
}
} if (HttpMethod.OPTIONS.equals(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
return true;
} //获取用户凭证
String token = request.getHeader(jwtUtils.getHeader());
if (StrUtil.isBlank(token)) {
token = request.getParameter(jwtUtils.getHeader());
} //凭证为空
if (StrUtil.isBlank(token)) {
throw new CustomException(HttpStatus.UNAUTHORIZED.value(), "token 不能为空");
} Claims claims = jwtUtils.getClaimByToken(token);
if (claims == null || jwtUtils.isTokenExpired(claims.getExpiration())) {
throw new CustomException(HttpStatus.UNAUTHORIZED.value(), "token 失效,请重新登录");
} //设置userId到request里,后续根据userId,获取用户信息
request.setAttribute(USER_KEY, Long.parseLong(claims.getSubject())); return true;
}
}
5. 添加 WebConfig,启用拦截器
package com.vipsoft.web.boot.config; import com.vipsoft.web.boot.interceptor.AuthorizationInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private AuthorizationInterceptor authorizationInterceptor; /**
* 添加拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
//拦截路径可自行配置多个 可用 ,分隔开
registry.addInterceptor(authorizationInterceptor).addPathPatterns("/**");
} /**
* 跨域支持
*
* @param registry
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT", "PATCH", "OPTIONS", "HEAD")
.maxAge(3600 * 24);
} }
6. 添加返回对象 Result
package com.vipsoft.web.boot.utils; /**
* 返回的对象,项目中要移到Core中
*/
public class Result<T> {
//操作代码
int code;
//提示信息
String message; T Data; public Result(int code, String message){
this.code = code;
this.message = message;
} public Result(int code, String message,T data){
this.code = code;
this.message = message;
this.setData(data);
} public int getCode() {
return code;
} public void setCode(int code) {
this.code = code;
} public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
} public T getData() {
return Data;
} public void setData(T data) {
Data = data;
}
}
7. 添加自定义异常类 CustomException.java 用于拦截器中的异常捕获
package com.vipsoft.web.boot.exception;
public class CustomException extends RuntimeException {
private static final long serialVersionUID = 1L;
private int code;
private String msg;
public CustomException(String msg) {
super(msg);
this.code = 500;
this.msg = msg;
}
public CustomException(String msg, Throwable e) {
super(msg, e);
this.msg = msg;
}
public CustomException(int code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
public CustomException(int code, String msg, Throwable e) {
super(msg, e);
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
8. 添加全局异常处理类 GlobalExceptionHandler.java , 可以将 返回 前端的数据处理成 JSON格式
package com.vipsoft.web.boot.exception; import com.vipsoft.web.boot.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice; import java.util.List; /**
* 全局异常处理器
*/
@RestControllerAdvice
public class GlobalExceptionHandler { private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); /**
* 处理自定义异常
*/
@ExceptionHandler(CustomException.class)
public Result handleException(CustomException e) {
// 打印异常信息
logger.error("### 异常信息:{} ###", e.getMessage());
return new Result(e.getCode(), e.getMessage());
} /**
* 参数错误异常
*/
@ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
public Result handleException(Exception e) { if (e instanceof MethodArgumentNotValidException) {
MethodArgumentNotValidException validException = (MethodArgumentNotValidException) e;
BindingResult result = validException.getBindingResult();
StringBuffer errorMsg = new StringBuffer();
if (result.hasErrors()) {
List<ObjectError> errors = result.getAllErrors();
errors.forEach(p -> {
FieldError fieldError = (FieldError) p;
errorMsg.append(fieldError.getDefaultMessage()).append(",");
logger.error("### 请求参数错误:{" + fieldError.getObjectName() + "},field{" + fieldError.getField() + "},errorMessage{" + fieldError.getDefaultMessage() + "}");
});
}
} else if (e instanceof BindException) {
BindException bindException = (BindException) e;
if (bindException.hasErrors()) {
logger.error("### 请求参数错误: {}", bindException.getAllErrors());
}
}
return new Result(10001, "参数无效");
} /**
* 处理所有不可知的异常
*/
@ExceptionHandler(Exception.class)
public Result handleOtherException(Exception e) {
//打印异常堆栈信息
e.printStackTrace();
// 打印异常信息
logger.error("### 不可知的异常:{} ###", e.getMessage());
return new Result(40001, "系统内部错误");
} }
9. 配置 application.yml
vipsoft:
jwt:
# 加密秘钥
secret: d3d3LnZpcHNvZnQuY29tLmNuLjQ3MjYyOTQ3LnNwcmluZyBib290
# token有效时长,单位秒
expire: 60 # 方便测试,设成 60 秒
header: token
10. 登录测试代码
/**
* 登录
*/
@JwtIgnore
@GetMapping("login")
public Map<String, Object> login(HttpServletRequest request){ //用户登录
long userId = 47262947; //生成token
String token = jwtUtils.generateToken(userId); Map<String, Object> map = new HashMap<>();
map.put("token", token);
map.put("expire", jwtUtils.getExpire()); return map;
}



Spring Boot JWT 用户认证的更多相关文章
- spring boot+jwt 权限验证
上周看了一下jwt以前公司的开发都是使用session共享的方法.现在主流的两种方式一种是把登录信息保存在服务器,另一种则是把信息保存在客户端.在使用session 存储的时候会遇到很多的问题,随着项 ...
- 玩转spring boot——简单登录认证
前言 在一个web项目中,某些页面是可以匿名访问的,但有些页面则不能.spring mvc提供了HandlerInterceptor接口来应对,只需要重写preHandle方法便可以实现此功能.那么使 ...
- Spring Boot JWT 快速入门
本章节讨论 jwt 在 spring boot 中的应用.意在快速入门 jwt. java jdk1.8 maven 3.2+ spring boot 2.0+ JSON Web Token(JWT) ...
- DRF的JWT用户认证
目录 DRF的JWT用户认证 JWT的认证规则 JWT的格式 JWT认证的流程 JWT模块的导入为 JWT的使用 DRF的JWT用户认证 从根本上来说,JWT是一种开放的标准(RFC 7519), 全 ...
- TinyFrame尾篇:整合Spring AOP实现用户认证
创建Manager用户验证表 这一篇主要讲解使用AOP对用户操作进行验证,如果通过验证,则继续执行,反之,则不能执行.其思想和上一篇完全一致. 由于需要用到用户认证,所以我们新建一个Manager实体 ...
- [django]前后端分离之JWT用户认证
在前后端分离开发时为什么需要用户认证呢?原因是由于HTTP协定是不储存状态的(stateless),这意味着当我们透过帐号密码验证一个使用者时,当下一个request请求时它就把刚刚的资料忘了.于是我 ...
- 前后端分离之JWT用户认证(转)
在前后端分离开发时为什么需要用户认证呢?原因是由于HTTP协定是不储存状态的(stateless),这意味着当我们透过帐号密码验证一个使用者时,当下一个request请求时它就把刚刚的资料忘了.于是我 ...
- 前后端分离之JWT用户认证zf
在前后端分离开发时为什么需要用户认证呢?原因是由于HTTP协定是不储存状态的(stateless),这意味着当我们透过帐号密码验证一个使用者时,当下一个request请求时它就把刚刚的资料忘了.于是我 ...
- [转] 前后端分离之JWT用户认证
[From] http://www.jianshu.com/p/180a870a308a 在前后端分离开发时为什么需要用户认证呢?原因是由于HTTP协定是不储存状态的(stateless),这意味着当 ...
- 前后端分离之JWT用户认证
在前后端分离开发时为什么需要用户认证呢?原因是由于HTTP协定是不储存状态的(stateless),这意味着当我们透过帐号密码验证一个使用者时,当下一个request请求时它就把刚刚的资料忘了.于是我 ...
随机推荐
- .NET8 WebApplication剖析
WebApplication 是用于配置HTTP管道和路由的web应用程序,接来下我将一一拆解它的组成. /// <summary> /// The web application u ...
- 谈谈SSO单点登录的设计实现
谈谈SSO单点登录的设计实现 本篇将会讲讲单点登录的具体实现. 实现思路 其实单点登录在我们生活中很常见,比如学校的网站,有很多个系统,迎新系统,教务系统,网课系统.我们往往只需要登录一次就能在各个系 ...
- 基于springboot+vue开发的教师工作量管理系
教师工作量管理系 springboot31 摘要 随着信息技术在管理上越来越深入而广泛的应用,管理信息系统的实施在技术上已逐步成熟.本文介绍了教师工作量管理系统的开发全过程.通过分析教师工作量管理系统 ...
- EF Core预编译模型Compiled Model
前言 最近还在和 npgsql 与 EF Core 斗争,由于 EF Core 暂时还不支持 AOT,因此在 AOT 应用程序中使用 EF Core 时,会提示问题: 听这个意思,似乎使用 Compi ...
- Gmail 发送邮件报警
亲测好使 import smtplib import email.mime.text import time # my test mail mail_username = 'XXXXXXXXXXX@g ...
- 1. Shell 基本用法
重点: 条件测试. read. Shell 环境配置. case. for. find. xargs. gzip,bzip2,xz. tar. sed. 1)编程基础 Linus 说:Talk is ...
- 如何在 PyQt 中实现异步数据库请求
需求 开发软件的时候不可避免要和数据库发生交互,但是有些 SQL 请求非常耗时,如果在主线程中发送请求,可能会造成界面卡顿.这篇博客将会介绍一种让数据库请求变得和前端的 ajax 请求一样简单,且不会 ...
- [计蒜客20191103D] 坐车
n 个学生将要坐车去餐厅,每辆车最多可以坐 5 个人并且出于对环境的考虑他们不会使用多余的车.车的速度为每秒 1 个单位.现在 ii 号同学需要去 \(i\) 号点停 5 分钟(此时整车都在 i 号点 ...
- nginx 反向代理teleport
nginx 反向代理teleport 普通配置(以Nginx服务与TP服务在同一台主机上为例) # ...其他内容... server { listen 80; server_name www.you ...
- 时间加权平均价格算法(TWAP)和成交量平均算法(VWAP)在量化回测的应用
为什么要引入TWAP和 VWAP? 为了评估策略的资金容量,我们对M.trade模块里买入点和卖出点这两个参数进行了更丰富的扩展,支持了策略能够按更丰富的算法交易价格(WAP)进行撮合. 如果资金是1 ...