文章图片
第一步: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;
- 移动电源|专为笔记本设计、可上飞机,移速65W 26800mAh大容量移动电源试用
- Java|小米12Ultra意外曝光,火爆一时,却被一款剃须刀强力“压下”
- iOS|Java:Java与Scala — 哪个更好?
- 小米科技|2022年小米笔记本哪款好?618值得入手小米热销笔记本推荐及点评
- Java|紧急下架!亚马逊这类产品问题频出,卖家选品时一定要注意把控
- Java|黄章或离开手机领域,魅族发生了大事
- Python|Web前端:Python与Javascript在未来Web开发中的对比
- Java|Java:Java 和Go — 你应该知道的8个主要区别
- 中兴|这份Java面试八股文让329人成功进入大厂,堪称2022最强
- Java|618性价比游戏本推荐,最高优惠直降千元