Java 定义基础拦截器

项目中拦截器用来处理特定的需要拦截的请求来进行一些特殊处理,如token验证,用户校验等等

一般需要以下两个类来实现一个基础拦截器的功能

AuthenticationInterceptor类

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
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;

/**
 * @Auther: 周先生
 * @Date: 2022/4/02 12:26
 * @Description:  用拦截器校验token
 */
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {

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

        if(!JwtUtil.verifyToken(token)){  //校验token
            throw new BadRequestException(HttpStatus.UNAUTHORIZED,"Token已过期或不存在");
        }

        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 {
    }
}

InterceptorConfig类
 

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @Auther: 周先生
 * @Date: 2022/4/02 12:26
 * @Description: 拦截器,拦截所有资源
 */
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authenticationInterceptor())
                .addPathPatterns("/**/h5/**");   //拦截路径
    }
    // 由于拦截器执行顺序的问题,必要要把第二个类加入容器,不然会报错,具体的解释我忘记了,旨在网上看到郭义熙,可以自行查阅
    @Bean
    public AuthenticationInterceptor authenticationInterceptor() {
        return new AuthenticationInterceptor();
    }
}

addPathPatterns("/**/h5/**") 用来拦截所有请求中带/h5/ 的请求并进行token验证

至于其他请求不做拦截处理

附上Jwt  Token验证工具类

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import lombok.extern.slf4j.Slf4j;

import java.util.Calendar;
import java.util.Date;

/**
 * @author 周先生
 * @version 1.0
 * @Description
 * @Classname JwtUtil
 * @company
 * @Date 2021/12/17 10:07
 */
@Slf4j
public class JwtUtil {
    private static final String SECRET_KEY = "6XAOBsoCtqN&yMjO3C#N%5MtsNQQmWIL";

   
    /**
     * 生成用户Token
     * @param username
     * @param minute
     * @return
     */
    public static String generateUser(String username, int minute){
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE, minute);
        Date expiresDate = nowTime.getTime();
        return JWT.create().withIssuedAt(new Date())
                .withExpiresAt(expiresDate)
                .withClaim("username", username)
                .sign(Algorithm.HMAC256(SECRET_KEY));
    }


    /**
     * 检验合法性
     * @param token
     */
    public static Boolean verifyToken(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET_KEY)).build();
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    public static String getUser(String token){
        if(!verifyToken(token)){
            return null;
        }
        Claim claim = JWT.decode(token).getClaim("username");
        if(claim == null){
            return null;
        }
        return claim.asString();
    }

    public static void main(String[] args) {
        log.info(generateUser("ce569b67cf942f625033287fefda287e", 14400));
        log.info(getUser("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MzIwMTk1NTUsImlhdCI6MTYzMTkzMzE1NSwidXNlcklkIjoiZDEyZTJlOGI0MDcyNGEwZjc3NmY5MGYyZTJjOTY0ODMifQ.1hMQrspnriRqTpRcRIgDLLPyyKCb29p6LCqsD9kIURG"));
    }
}

你可能感兴趣的:(java,spring)