springboot 基于拦截器 配置token认证

亲测有效
1、配置token验证拦截器

package com.wst.data.interceptor.rfid;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

public class ParamInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String token = httpServletRequest.getHeader("token");
        //token验证
        if(!"8BC0BAE5859CDA31D212022721B3C00E".equals(token)){
            System.out.println("token验证失败");
            return false;
        }
        System.out.println("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 {
    
    }
    
}

2、注册拦截器

package com.wst.data.interceptor.rfid;

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

@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {

    public void addInterceptors(InterceptorRegistry registry) {
    	//此处配置拦截路径
        registry.addInterceptor(new ParamInterceptor()).addPathPatterns("/**");
    }
    
}

注:token是放在header中的额。

你可能感兴趣的:(java)