欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot简单的token验证

程序员文章站 2022-07-14 09:16:59
...

启动类添加组件扫描注解

@SpringBootApplication
// 扫描组件
@ServletComponentScan
public class WarningForecastApplication {

    public static void main(String[] args) {
        SpringApplication.run(WarningForecastApplication.class, args);
    }
}

定义token拦截器

package com.aliyun.warningforecast.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * Created with IntelliJ IDEA.
 *
 * @author: wb-zcx696752
 * @description:
 * @data: 2021/3/1 9:55 PM
 */

@Slf4j
public class TokenVerificationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        log.info("访问前拦截请求,从请求头中获取token ---> " + token);
        if (StringUtils.isEmpty(token)) {
            log.info("token为空,请携带正确的token");
            return false;
        }
        if (token.equals("123")) {
            log.info("token验证成功");
            return true;
        }
        return false;
    }

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

    }
}

注册token拦截器

package com.aliyun.warningforecast.config;

import com.aliyun.warningforecast.interceptor.TokenVerificationInterceptor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

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

@Configuration
@ConfigurationProperties(prefix = "interceptor.config.path")
public class InterceptorConfig extends WebMvcConfigurationSupport {

    private List<String> special = new ArrayList<>();

    public List<String> getSpecial() {
        return special;
    }

    public void setSpecial(List<String> special) {
        this.special = special;
    }

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {

        InterceptorRegistration interceptor = registry.addInterceptor(new TokenVerificationInterceptor());

        interceptor.addPathPatterns(special);
    }
}

配置文件配置

# 拦截器配置路径
interceptor.config.path.special=/api/v0.1/**
相关标签: springboot