jwt权限验证工具类

jwt权限验证工具类

导入依赖

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.7.0</version>
</dependency>
<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.4.0</version>
</dependency>

创建自定义注解

package com.btf.annotation;

import java.lang.annotation.*;

/**
 * 用来标记需要权限验证请求的注解
 * @author maw
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface JwtAuth {}

配置类

package com.btf.config;

import com.btf.interceptor.JwtInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
 * @author maw
 */
@Configuration
public class WebConfigure implements WebMvcConfigurer {

    /**
     * 注册拦截器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //不拦截的请求路径
        List<String> excludePaths = new ArrayList<>();
        excludePaths.add("/doLogin");
//        excludePaths.add("/findAll");
        excludePaths.add("/logout");

        //性能记录
//        registry.addInterceptor(this.getPropertyInterceptor());
        //权限校验
        registry.addInterceptor(this.getJwtInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns(excludePaths);
    }

    /**
     * 权限拦截器的工厂方法
     *
     * @return
     */
    @Bean
    public HandlerInterceptor getJwtInterceptor() {
        return new JwtInterceptor();
    }

  

}

拦截器类(实现HandlerInterceptor接口)

package com.btf.interceptor;

import com.btf.annotation.JwtAuth;
import com.btf.utils.JwtUtils;
import org.springframework.stereotype.Component;
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;

/**
 * @author maw
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        } else {
            HandlerMethod hand = (HandlerMethod) handler;
            Method method = hand.getMethod();
            if (method.isAnnotationPresent(JwtAuth.class)) {
                String token = request.getHeader("Authorization");
                System.out.println("拿到的token = " + token);
                Boolean aBoolean = JwtUtils.isTokenValid(token);
                if (aBoolean) {
                    return true;
                } else {
                    throw new RuntimeException("token验证失败!");
                }
            } else {
                return true;
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
            throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }
}

jwt工具类校验令牌

package com.btf.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.sun.istack.internal.NotNull;

import java.util.Date;

/**
 * JWT校验工具
 *
 * @author maw
 */
public class JwtUtils {

    private static final long EXPIRE_TIME = 5 * 60 * 1000;
    private static final String SECRECT = "maw-secrect";

    /**
     * 获取token令牌
     *
     * @param uid
     * @return
     */
    public static String getAccessToken(String uid) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(SECRECT);
        return JWT.create()
                .withAudience(uid)
                .withExpiresAt(date)
                .sign(algorithm);
    }

    /**
     * 校验令牌的时效性和正确性
     *
     * @param token
     * @return
     */

    @NotNull
    public static Boolean isTokenValid(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRECT);
            JWTVerifier jwtVerifier = JWT.require(algorithm).build();
            DecodedJWT verify = jwtVerifier.verify(token);
            return true;
        } catch (JWTVerificationException ex) {
            throw new RuntimeException("令牌失效!");
        }
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值