SpringBoot:集成JWT
JWT:是一种用于双方之间传递安全信息的简洁的、URL安全的表述性声明规范。JWT作为一个开放的标准(RFC 7519),定义了一种简洁的,自包含的方法用于通信双方之间以Json对象的形式安全的传递信息。
JWT的特点:简洁(数据量小,传输速度快)、自包含(负载中包含了所有用户所需要的信息,避免多次查询数据库)。
JWT的构成:Header(头部)、Payload(负载)、Signature(签名),用英文句号隔开。
-
头部:
包含两部分:token类型和采用的加密算法。
{ "alg": "HS256", "typ": "JWT" }
将上面内容采用base64编码,可以得到JWT的头部。
-
负载:
iss: 该JWT的签发者
sub: 该JWT所面向的用户
aud: 接收该JWT的一方
exp(expires): 什么时候过期,这里是一个Unix时间戳
iat(issued at): 在什么时候签发的除了标准定义以外,还要定义业务处理中需要用到的字段,例如用户token或者id
{ "iss": "Lefto.com", "iat": 1500218077, "exp": 1500218077, "aud": "www.leftso.com", "sub": "[email protected]", "user_id": "dc2c4eefe2d141490b6ca612e252f92e", "user_token": "09f7f25cdb003699cee05759e7934fb2" }
-
签名:
签名其实是对JWT的头部和负载整合的一个签名验证。
JWT依赖:
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.18.2</version>
</dependency>
springboot获取token(一般放在utils中,登录的时候返回生成的token):
import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import java.util.Date;
public class TokenUtils {
/*
*生成token
*
* */
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 的密钥
}
}
前端将token集成到request请求(集成过之后,每发送一次请求,都会自动带上token):
request.interceptors.request.use(config => {
config.headers['Content-Type'] = 'application/json;charset=utf-8';
config.headers['token'] = user.token; // 设置请求头
return config
}, error => {
return Promise.reject(error)
});
token拦截(一般放在config中的inteceptor文件夹下,用来拦截请求,检查token):
package com.ustb.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.ustb.springboot.entity.User;
import com.ustb.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class JwtInterceptor implements HandlerInterceptor {
@Autowired
private UserService userService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("token");
// 如果不是映射到方法直接通过
if(!(handler instanceof HandlerMethod)){
return true;
}
if (StrUtil.isBlank(token)){
throw new RuntimeException("无token,请重新登录");
}
// 获取 token 中的 user id
String userId;
try {
userId = JWT.decode(token).getAudience().get(0);
} catch (JWTDecodeException j) {
throw new RuntimeException("401");
}
//根据token中的userid查询数据库
User user = userService.getById(Integer.parseInt(userId));
if (user == null) {
throw new RuntimeException("用户不存在,请重新登录");
}
//用户密码加签验证,验证token
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
try {
jwtVerifier.verify(token); //验证token
} catch (JWTVerificationException e) {
throw new RuntimeException("401");
}
return true;
}
}
对一些请求不进行token拦截(一般放在config文件夹下):
package com.ustb.springboot.config;
import com.ustb.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 {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(newjwtInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/user/login", "/user/register", "/zhuanzheng/export", "/zhuanzheng/import", "/methods/**", "/file/**"); // 拦截所有请求, 决定判断token是否合法来决定是否需要登录
}
@Bean
public JwtInterceptor newjwtInterceptor(){
return new JwtInterceptor();
}
}