笔记本|java通过注解和拦截器实现token鉴权校验

笔记本|java通过注解和拦截器实现token鉴权校验

文章图片



第一步:pom文件引入jwt包
第二步:自定义两个注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 用于登录后才能操作
*/
@Target({ElementType.METHOD ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface UserLoginToken {
boolean required() default true;

import java.lang.annotation.*;
@Target(ElementType.PARAMETER)//Annotation所修饰的对象范围:方法参数
@Retention(RetentionPolicy.RUNTIME)//Annotation被保留时间:运行时保留(有效)
@Documented//标记注解
【笔记本|java通过注解和拦截器实现token鉴权校验】public @interface CurrentUser {

第三步:自定义拦截器
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
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 com.abby.controller.api.BaseController;
import com.abby.entity.User;
import com.abby.enums.ResultCode;
import com.abby.exceptions.APIException;
import com.abby.model.vo.LoginUser;
import com.abby.service.IUserService;
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;
public class AuthenticationInterceptor implements HandlerInterceptor {
@Autowired
private IUserService 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();
//检查有没有需要用户权限的注解
if (method.isAnnotationPresent(UserLoginToken.class)) {
UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
if (userLoginToken.required()) {
// 执行认证
if (token == null||StringUtils.isEmpty(token)) {
throw new APIException(ResultCode.AUTH.getCode()\"token is empty please login again\");

// 获取 token 中的 user id
Integer userId;
try {
String userIdStr = JWT.decode(token).getAudience().get(0);
userId = Integer.valueOf(userIdStr);
catch (JWTDecodeException j) {
throw new APIException(ResultCode.AUTH.getCode()ResultCode.AUTH.getMsg());

User user = userService.getById(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 APIException(ResultCode.AUTH.getCode()ResultCode.AUTH.getMsg());

LoginUser loginUser = new LoginUser();
loginUser.setUserId(user.getId());
loginUser.setUserName(user.getUserName());
httpServletRequest.setAttribute(\"currentUser\" loginUser);
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 {


第四步:重写HandlerMethodArgumentResolver
package com.abby.interceptor;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import com.abby.model.vo.LoginUser;