SpringBoot集成JWT实现token验证
点击上方蓝色字体,选择“标星公众号”
优质文章,第一时间送达
优点
简洁: 可以通过
URL
、POST
参数或者在HTTP header
发送,因为数据量小,传输速度也很快;自包含:负载中可以包含用户所需要的信息,避免了多次查询数据库;
因为
Token
是以JSON
加密的形式保存在客户端的,所以JWT
是跨语言的,原则上任何web
形式都支持;不需要在服务端保存会话信息,特别适用于分布式微服务。
缺点
无法作废已颁布的令牌;
不易应对数据过期。
一、Jwt消息构成
1.1 组成
头部(
header
)载荷(
payload
)签证(
signature
)
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxYzdiY2IzMS02ODFlLTRlZGYtYmU3Yy0wOTlkODAzM2VkY2UiLCJleHAiOjE1Njk3Mjc4OTF9.wweMzyB3tSQK34Jmez36MmC5xpUh15Ni3vOV_SGCzJ8
1.2 header
声明类型,这里是
Jwt
声明加密的算法 通常直接使用
HMAC SHA256
JWS | 算法名称 |
---|---|
HS256 | HMAC256 |
HS384 | HMAC384 |
HS512 | HMAC512 |
RS256 | RSA256 |
RS384 | RSA384 |
RS512 | RSA512 |
ES256 | ECDSA256 |
ES384 | ECDSA384 |
ES512 | ECDSA512 |
1.3 playload
标准中注册的声明的数据;
自定义数据。
标准中注册的声明 (建议但不强制使用)
iss: jwt签发者
sub: jwt所面向的用户
aud: 接收jwt的一方
exp: jwt的过期时间,这个过期时间必须要大于签发时间
nbf: 定义在什么时间之前,该jwt都是不可用的.
iat: jwt的签发时间
jti: jwt的唯一身份标识,主要用来作为一次性token,从而回避重放攻击。
自定义数据:存放我们想放在
token
中存放的key-value
值
1.4 signature
二、Spring Boot和Jwt集成示例
2.1、项目依赖 pom.xml
com.auth0
java-jwt
3.10.3
2.2、自定义注解
//需要登录才能进行操作的注解LoginToken
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginToken {
boolean required() default true;
}
//用来跳过验证的PassToken
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface PassToken {
boolean required() default true;
}
2.3、用户实体类、及查询service
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String userID;
private String userName;
private String passWord;
}
package com.sky.springbootdemo.jwt.service;
import com.sky.springbootdemo.jwt.entity.User;
import org.springframework.stereotype.Service;
/**
* @title: UserService
* @Author gjt
* @Date: 2020-12-21
* @Description:
*/
@Service
public class UserService {
public User getUser(String userid, String password){
if ("admin".equals(userid) && "admin".equals(password)){
User user=new User();
user.setUserID("admin");
user.setUserName("admin");
user.setPassWord("admin");
return user;
}
else{
return null;
}
}
public User getUser(String userid){
if ("admin".equals(userid)){
User user=new User();
user.setUserID("admin");
user.setUserName("admin");
user.setPassWord("admin");
return user;
}
else{
return null;
}
}
}
2.4、Token生成
package com.sky.springbootdemo.jwt.service;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.sky.springbootdemo.jwt.entity.User;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
* @title: TokenService
* @Author gjt
* @Date: 2020-12-21
* @Description:
*/
@Service
public class TokenService {
/**
* 过期时间5分钟
*/
private static final long EXPIRE_TIME = 5 * 60 * 1000;
public String getToken(User user) {
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
String token="";
token= JWT.create().withAudience(user.getUserID()) // 将 user id 保存到 token 里面
.withExpiresAt(date) //五分钟后token过期
.sign(Algorithm.HMAC256(user.getPassWord())); // 以 password 作为 token 的密钥
return token;
}
}
2.5、拦截器拦截token
package com.sky.springbootdemo.jwt.interceptor;
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.sky.springbootdemo.jwt.annotation.LoginToken;
import com.sky.springbootdemo.jwt.annotation.PassToken;
import com.sky.springbootdemo.jwt.entity.User;
import com.sky.springbootdemo.jwt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
/**
* @title: JwtInterceptor
* @Author gjt
* @Date: 2020-12-21
* @Description:
*/
public class JwtInterceptor implements HandlerInterceptor{
@Autowired
private UserService userService;
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
// 如果不是映射到方法直接通过
if(!(object instanceof HandlerMethod)){
return true;
}
HandlerMethod handlerMethod=(HandlerMethod)object;
Method method=handlerMethod.getMethod();
//检查是否有passtoken注释,有则跳过认证
if (method.isAnnotationPresent(PassToken.class)) {
PassToken passToken = method.getAnnotation(PassToken.class);
if (passToken.required()) {
return true;
}
}
//检查有没有需要用户权限的注解
if (method.isAnnotationPresent(LoginToken.class)) {
LoginToken loginToken = method.getAnnotation(LoginToken.class);
if (loginToken.required()) {
// 执行认证
if (token == null) {
throw new RuntimeException("无token,请重新登录");
}
// 获取 token 中的 user id
String userId;
try {
userId = JWT.decode(token).getAudience().get(0);
} catch (JWTDecodeException j) {
throw new RuntimeException("401");
}
User user = userService.getUser(userId);
if (user == null) {
throw new RuntimeException("用户不存在,请重新登录");
}
// 验证 token
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassWord())).build();
try {
jwtVerifier.verify(token);
} catch (JWTVerificationException e) {
throw new RuntimeException("401");
}
return true;
}
}
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
2.6、注册拦截器
package com.sky.springbootdemo.jwt.config;
import com.sky.springbootdemo.jwt.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;
/**
* @title: InterceptorConfig
* @Author gjt
* @Date: 2020-12-21
* @Description:
*/
@Configuration
public class InterceptorConfig implements WebMvcConfigurer{
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jwtInterceptor())
.addPathPatterns("/**"); // 拦截所有请求,通过判断是否有 @LoginRequired 注解 决定是否需要登录
//注册TestInterceptor拦截器
// InterceptorRegistration registration = registry.addInterceptor(jwtInterceptor());
// registration.addPathPatterns("/**"); //添加拦截路径
// registration.excludePathPatterns( //添加不拦截路径
// "/**/*.html", //html静态资源
// "/**/*.js", //js静态资源
// "/**/*.css", //css静态资源
// "/**/*.woff",
// "/**/*.ttf",
// "/swagger-ui.html"
// );
}
@Bean
public JwtInterceptor jwtInterceptor() {
return new JwtInterceptor();
}
}
2.7、登录Controller
package com.sky.springbootdemo.jwt.controller;
import com.alibaba.fastjson.JSONObject;
import com.sky.springbootdemo.jwt.annotation.LoginToken;
import com.sky.springbootdemo.jwt.entity.User;
import com.sky.springbootdemo.jwt.service.TokenService;
import com.sky.springbootdemo.jwt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @title: Login
* @Author gjt
* @Date: 2020-12-22
* @Description:
*/
@RestController
public class Login {
@Autowired
private UserService userService;
@Autowired
private TokenService tokenService;
@PostMapping("login")
public Object login(String username, String password){
JSONObject jsonObject=new JSONObject();
User user=userService.getUser(username, password);
if(user==null){
jsonObject.put("message","登录失败!");
return jsonObject;
}else {
String token = tokenService.getToken(user);
jsonObject.put("token", token);
jsonObject.put("user", user);
return jsonObject;
}
}
@LoginToken
@PostMapping("/getMessage")
public String getMessage(){
return "你已通过验证";
}
}
2.8、配置全局异常捕获
package com.sky.springbootdemo.jwt.controller;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* @title: GlobalExceptionHandler
* @Author gjt
* @Date: 2020-12-22
* @Description:
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
@ResponseBody
@ExceptionHandler(Exception.class)
public Object handleException(Exception e) {
String msg = e.getMessage();
if (msg == null || msg.equals("")) {
msg = "服务器出错";
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("code", 1000);
jsonObject.put("message", msg);
return jsonObject;
}
}
三、postman测试
3.1、获取tockem
3.2、无tocken登录
3.3、有tocken登录
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:
https://blog.csdn.net/gjtao1130/article/details/111658060
粉丝福利:Java从入门到入土学习路线图
???
?长按上方微信二维码 2 秒
感谢点赞支持下哈
评论