文章图片
第一步: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//标记注解
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 {
- Java|虚拟现实+眼动追踪精选实战分享:认知“新”健康
- 小米科技|小米12s通过认证,7月份发布,小米12跌价800元
- Java|国家出手整治资本!人民日报三揭马云真面目,马云他到底干了啥?
- Java|当下屏幕最好的五款手机,和“周冬雨”说再见,数码博主都推荐
- Java|美媒:阿里、华为、中科院已经“突围”,芯片市场风向变了
- Java|美团这次硬气了!
- Java|百度的概念车,遭人嘲笑
- Java|花呗提前还款的“坏处”正式被确认,你有注意到吗?
- javascript|Web前端:什么是Node js? 什么是React? 有什么区别
- 电热水器|扁桶电热水器成时尚,该怎么选?通过这四款来找找异同