spring 拦截器实现token校验登录
pom文件
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.5.0</version>
</dependency>
生成token
import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.demo.entity.Role;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @author admin
*/
public class TokenUtil {
/**
* token过期时间
*/
private static final long EXPIRE_TIME = 60 * 60 * 1000;
/**
* token秘钥
*/
private static final String TOKEN_SECRET = "secret";
/**
* 生成token,30分钟过期
*
* @param username 用户名
* @param loginTime 登录时间
* @return 生成的token
*/
public static String sign(String username, LocalDateTime loginTime, Role role) {
try {
// 设置过期时间
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
// 私钥和加密算法
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
// 设置头部信息
Map<String, Object> header = new HashMap<>(3);
header.put("Type", "Jwt");
header.put("alg", "HS256");
// 返回token字符串
return JWT.create()
.withHeader(header)
// 设置token中需要加载的用户信息
.withClaim("loginName", username)
.withClaim("loginTime", loginTime.toString())
.withClaim("role", JSON.toJSONString(role))
.withExpiresAt(date)
.sign(algorithm);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 检验token是否正确
*
* @param token 需要校验的token
* @return 校验是否成功
*/
public static boolean verify(String token) {
try {
//设置签名的加密算法:HMAC256
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
JWTVerifier verifier = JWT.require(algorithm).build();
verifier.verify(token);
return true;
} catch (Exception e) {
return false;
}
}
}
拦截器
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.demo.util.JsonResult;
import com.demo.util.TokenUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author admin
*/
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String requestMethod = "OPTIONS";
if (StringUtils.equals(requestMethod, request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
return true;
}
String token = request.getHeader("Authorization");
if (StringUtils.isNotBlank(token)) {
if (TokenUtil.verify(token)) {
return true;
}
}
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
response.setStatus(401);
JsonResult jsonResult = JsonResult.failMessage("认证失败", 401);
response.getWriter().append(JSON.toJSONString(jsonResult));
return false;
}
}
设置拦截白名单
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.List;
/**
* @author admin
*/
@Component
public class IntercepterConfig implements WebMvcConfigurer {
private TokenInterceptor tokenInterceptor;
//构造方法
public IntercepterConfig(TokenInterceptor tokenInterceptor) {
this.tokenInterceptor = tokenInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
List<String> excludePath = new ArrayList<>();
//登录
excludePath.add("/system/*");
registry.addInterceptor(tokenInterceptor)
.addPathPatterns("/**")
.excludePathPatterns(excludePath);
//除了登陆接口其他所有接口都需要token验证
WebMvcConfigurer.super.addInterceptors(registry);
}
}
本文来自博客园,作者:暮雨寒冬,转载请注明原文链接:https://www.cnblogs.com/good--luck/p/15828557.html