![流程图](https://i-blog.csdnimg.cn/blog_migrate/0b010d2e3ae611247713c5deb410ea3d.png#pic_center)
pom.xml
<!-- https://mvnrepository.com/artifact/com.auth0/java-jwt -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.18.2</version>
</dependency>
请求拦截
InterceptorConfigure.java
@Configuration
public class InterceptorConfigure implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
List<String> excludePath = Arrays.asList("/auth/**","/error/**");
registry.addInterceptor(authenticationInterceptor())
.excludePathPatterns(excludePath)
.addPathPatterns("/**");
}
@Bean
public AuthenticationInterceptor authenticationInterceptor() {
return new AuthenticationInterceptor();
}
}
AuthenticationInterceptor.java
public class AuthenticationInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
if (!(handler instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
//检测用户接口是否不需要校验token
if (!method.isAnnotationPresent(NToken.class)) {
String token = request.getHeader(G.REQUEST_TOKEN_HEADER_KEY);
// 执行认证
if (token == null) {
throw new BsException(E.INVALID_TOKEN,"token不能为空");
}
// 解析当前token内容 如果解析失败会在上层抛出异常
return JWTUtil.verifyToken(token);
}
return true;
}
}
NToken.java (用于跳过验证标识)
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface NToken {
}
token管理工具类 JWTUtil.java
// token 过期时间 days
private static final Integer EXPIRES_DAYS = 30;
//签名
private static final String SECRET = "are you ok";
// 可用来区别不同平台登录等(附加功能)
public static String ISSUER = "Bak";
/**
* @param userId
* @return当前登录信息 ISSUser
*/
public static String genToken(String userId) {
try {
Algorithm algorithm = Algorithm.HMAC256(SECRET);
JWTCreator.Builder builder = JWT.create()
.withIssuer(ISSUER)
.withClaim(G.JWT_CLAIM_PRIMARY_KEY, userId)
.withExpiresAt(DateUtil.getAfterDate(new Date(), EXPIRES_DAYS));
return builder.sign(algorithm);
} catch (IllegalArgumentException e) {
throw new BsException(E.SYS_ERROR, "token生成失败");
}
}
/**
* @param token
* @return
* @throws Exception
*/
public static Map<String, String> mapToken(String token) {
Algorithm algorithm;
Map<String, Claim> map;
try {
algorithm = Algorithm.HMAC256(SECRET);
JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
DecodedJWT jwt = verifier.verify(token);
map = jwt.getClaims();
} catch (InvalidClaimException e) {
e.printStackTrace();
throw new BsException(E.INVALID_TOKEN, "token 已过期");
} catch (Exception e) {
e.printStackTrace();
throw new BsException(E.INVALID_TOKEN, "错误的Token 信息");
}
Map<String, String> resultMap = new HashMap<>(map.size());
map.forEach((k, v) -> resultMap.put(k, v.asString()));
return resultMap;
}
public static boolean verifyToken(String token) {
Algorithm algorithm;
try {
algorithm = Algorithm.HMAC256(SECRET);
JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
verifier.verify(token);
} catch (InvalidClaimException e) {
e.printStackTrace();
throw new BsException(E.INVALID_TOKEN, "token 已过期");
} catch (Exception e) {
e.printStackTrace();
throw new BsException(E.INVALID_TOKEN, "错误的Token 信息");
}
return true;
}
完整项目地址 https://gitee.com/xdd423/spring-boot-note.git