Administrator
Administrator
Published on 2025-01-06 / 0 Visits
0
0

Springboot配置拦截器验证token

添加jwt依赖

   <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
   </dependency>

创建Jwt工具类

package org.taru.ems.common.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtUtil {
    //设置token过期时间
    @Value("${my.secretExpirationTime}")
    private long EXPIRATION_TIME;
    //你的密码,用于加密
    @Value("${my.privateSecret}")
    private String SECRET;

    /**
     * 生成token
     * @param username
     * @return
     */
    public  String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }

    /**
     * 解析token 返回用户名
     * @param token
     * @return
     */
    public  String getClaimsFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody().getSubject();
    }

    /**
     * 验证Token
     * @param token
     * @return
     */
    public  boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token);
            return true;
        } catch(Exception e) {
            return false;
        }
    }

}

生成token

jwtUtil.generateToken(authUserVo.getTelephone())

编写拦截器验证




import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.taru.ems.common.utils.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * token验证拦截器
 */
@Slf4j
@Component
public class TokenVerificationIntercepter implements HandlerInterceptor {
    @Autowired
    JwtUtil jwtUtil;
    @Value("${my.tokenKey}")
    String tokenKey;
    @Value("${my.enableTokenValid}")
    Boolean  isEnableValid;

   
    private final static String    OPTIONS="OPTIONS";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       log.info("正在请求接口:{},请求方法是:{}",request.getRequestURL(),request.getMethod());
       //token验证开关
        if(!isEnableValid){
            return true;
        }
        //如果是预检
        if(OPTIONS.equals(request.getMethod())){
            return true;
        }
        //从请求头中获取 token
        String token =request.getHeader(tokenKey);
        log.info("接口的Token是:{}",token);
        if(token!=null){
                //验证token的合法性
            boolean  isValid =jwtUtil.validateToken(token);
            if(isValid){
                log.info("接口Token合法");
                return true;
            }

        }
        log.info("接口Token不合法");
        //告诉前端 你没有令牌 通过http状态吗 401
        response.setStatus(401);
        response.setContentType("text/plain;charset=utf-8");
        response.getWriter().write("没有有效的token令牌,请重新登录");
        return false;
    }
}

配置拦截器


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
import org.taru.ems.common.intercepter.TokenVerificationIntercepter;

@Configuration
@EnableWebMvc
public class WebMvcConfig  implements WebMvcConfigurer {


  @Autowired
  TokenVerificationIntercepter tokenVerificationIntercepter;


  /**
     * 跨域
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").
                allowedOrigins("*").allowCredentials(false).
                allowedHeaders("*").allowedMethods("*").maxAge(3600);
    }


    /**
     * 添加token验证器 (“临时开放xxxx接口”)
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
       registry.addInterceptor(tokenVerificationIntercepter).addPathPatterns("/**")
                .excludePathPatterns("/auth/login","/auth/register","/static/**");


    }



}



Comment