JWT token生成及验证(简易版)

1、 新增一个拦截器JwtInterceptor

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.shown.shownmp.domain.User;
import com.shown.shownmp.exception.BusinessException;
import com.shown.shownmp.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author shown
 * @date 2023/12/7 9:23
 */
@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
    public static final int ERROR_CODE_401 = 401;

    @Autowired
    private UserService userService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle method is called");
        String token = request.getHeader("Authorization");
        if (StrUtil.isBlank(token)){
            token = request.getParameter("token");
        }

        //执行认证
        if (StrUtil.isBlank(token)){
            throw new BusinessException(ERROR_CODE_401,"无token,请重新登录!");
        }

        //获取token中的userId
        String userId;
        User user;
        try {
            userId = JWT.decode(token).getAudience().get(0);
            user = userService.getById(Integer.parseInt(userId));
            // 获取 JWT 的过期时间
            Date expirationDate = JWT.decode(token).getExpiresAt();
            if (expirationDate != null && expirationDate.before(new Date())){
                throw new BusinessException(ERROR_CODE_401,"token已过期,请重新登录!");
            }
        } catch (Exception e) {
            String errMsg = "token验证失败,请重新登录";
            log.error(errMsg + ", token=" + token, e);
            throw new BusinessException(ERROR_CODE_401, errMsg);
        }

        if (user == null){
            throw new BusinessException(ERROR_CODE_401,"用户不存在,请重新登录!");
        }
        //用户密码加签验证 token,对应TokenUtils,java中的.sign(Algorithm.HMAC256(sign))
        // 以 password 作为 token 的密钥
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getUserPassword())).build();
            jwtVerifier.verify(token);
        } catch (JWTVerificationException  e) {
            throw new BusinessException(ERROR_CODE_401,"token验证失败,请重新登录!");
        }
        return true;

    }
}

2、新增一个TokenUtils

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shown.shownmp.domain.User;
import com.shown.shownmp.exception.BusinessException;
import com.shown.shownmp.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author shown
 * @date 2023/12/7 9:30
 */
@Component
@Slf4j
public class TokenUtils {

    private static UserService staticUserService;

    @Resource
    private UserService userService;

    @PostConstruct
    public void setUserService() {
        staticUserService = userService;
    }

    /**
     * 生成token
     *
     * @return
     */
    public static String getToken(String userId, String sign) {
        return JWT.create().withAudience(userId) // 将 user id 保存到 token 里面,作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2)) // 2小时后token过期
                .sign(Algorithm.HMAC256(sign)); // 以 password 作为 token 的密钥
    }

    /**
     * 获取当前登录的用户信息
     *
     * @return user对象
     * 
     */
    public static User getCurrentUser() {
        String token = null;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token = request.getHeader("Authorization");
            if (StrUtil.isBlank(token)) { 
                token = request.getParameter("token");
            }
            if (StrUtil.isBlank(token)) {
                log.error("获取当前登录的token失败, token: {}", token);
                return null;
            }
            //获取用户id
            String userId = String.valueOf(JWT.decode(token).getAudience().get(0));
            //检验token是否有效
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("token",token);
            User user = staticUserService.getOne(queryWrapper);
            if (user == null){
                log.error("token不存在!userid={}",userId);
                return null;
            }
            return user;
        } catch (Exception e) {
            log.error("获取当前登录的管理员信息失败, token={}", token,  e);
            return null;
        }
    }


}

3、配置文件(有部分注意点已打注释)

import com.shown.shownmp.interceptor.JwtInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author shown
 * @date 2023/12/7 9:20
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    JwtInterceptor jwtInterceptor;
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        // 指定controller统一的接口前缀
        configurer.addPathPrefix("", clazz -> clazz.isAnnotationPresent(RestController.class));
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //增加了全局api后就不需要在这儿加上api前缀会导致路径不匹配
//        registry.addInterceptor(jwtInterceptor).addPathPatterns("/api/**")
//                .excludePathPatterns("/api/user/login", "/api/user/register");
        registry.addInterceptor(jwtInterceptor).addPathPatterns("/**")
                .excludePathPatterns("/user/login", "/user/register");
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值