springboot简单集成jwt

springboot简单集成jwt

参考:https://blog.csdn.net/gjtao1130/article/details/111658060

大佬的源码是可以运行的,我写这个文章的目的是添加一些注释来辅助理解

源码

JwtInterceptor.Java

package com.xxh.jwt1.interceptor;

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;

import com.xxh.jwt1.annotation.LoginToken;
import com.xxh.jwt1.annotation.PassToken;
import com.xxh.jwt1.entity.User;
import com.xxh.jwt1.service.UserService;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @title: JwtInterceptor
 * @Author gjt
 * @Date: 2020-12-21
 * @Description:
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    // 拦截器,接收请求后,在执行请求前进行检测
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {

        System.out.println("object:"+object);
        System.out.println("object instanceof HandlerMethod:"+(object instanceof HandlerMethod));

        // 如果是请求方法(比如登录方法),那么object instanceof HandlerMethod的结果为true
        // 如果是请求资源(global.css),那么object instanceof HandlerMethod的结果为false,但是需要拦截器放行
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }

        // 这一步认为object是请求方法,强转
        HandlerMethod handlerMethod = (HandlerMethod) object;
        System.out.println("handlerMethod:"+handlerMethod);

        // 获取method对象
        Method method = handlerMethod.getMethod();

        System.out.println("method:" + method);

        //检查是否有 PassToken 注释,有则跳过认证,没有就继续验证
        if (method.isAnnotationPresent(PassToken.class)) {
            // 判断方法上是否有PassToken注解,有的话就获取,没有就为null
            PassToken passToken = method.getAnnotation(PassToken.class);

            System.out.println("method.getAnnotation:" + method.getAnnotation(PassToken.class));
            System.out.println("passToken.required():" + passToken.required());

            // 获取PassToken的required()的值,这是我们自定义的。默认为true,所以使preHandle返回true,通过验证
            if (passToken.required()) {
                return true;
            }

        }

        // 从 http 请求头中取出 token
        String token = httpServletRequest.getHeader("token");

        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(LoginToken.class)) {
            // 判断方法上是否有 LoginToken 注解,有的话就获取,没有就为null
            LoginToken loginToken = method.getAnnotation(LoginToken.class);

            // 获取LoginToken的required()的值,这是我们自定义的。默认为true
            if (loginToken.required()) {
                // 执行认证
                // token 已经在上面获取,如果没有就直接返回异常
                if (token == null) {
                    throw new RuntimeException("无token,请重新登录");
                }
                // 获取 token 中的 user id
                String userId;
                try {
                    userId = JWT.decode(token).getAudience().get(0);
                    System.out.println("JWT.decode(token).getAudience():"+JWT.decode(token).getAudience());
                    System.out.println("userId:"+userId);
                } catch (JWTDecodeException j) {
                    throw new RuntimeException("401");
                }

                User user = userService.getUser(userId);
                if (user == null) {
                    throw new RuntimeException("用户不存在,请重新登录");
                }

                // 验证 token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassWord())).build();
                System.out.println("jwtVerifier:"+jwtVerifier);
                System.out.println("jwtVerifier.verify(token):"+jwtVerifier.verify(token));

                try {
                    jwtVerifier.verify(token);
                } catch (JWTVerificationException e) {
                    throw new RuntimeException("401");
                }
                return true;
            }
        }

        // 如果没有 PassToken 或 LoginToken 的接口,如登录获取token方法,就会直接通过
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("hello welcome");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

我觉得集成jwt最难的就是理解JwtInterceptor的原理了。

JwtInterceptor实现HandlerInterceptor的preHandle方法,目的是为了springboot接收到请求前,先不执行controller的方法,由拦截器的逻辑来判断该条请求是否需要拦截。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

徐子元竟然被占了!!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值