自定义拦截器与配置


@Slf4j
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Resource
    private RedisCache redisCache;

    /**
     * 请求处理之前调用
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws IOException {
        log.info("请求地址:【{}】", httpServletRequest.getServletPath());
        Map parameterMap = httpServletRequest.getParameterMap();
        String join = MapUtil.join(parameterMap, ",", "=");
        log.info("请求参数:【{}】",join);
        //获取请求头的token
        String token = httpServletRequest.getHeader("Authorization");
        //响应
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        //认证
        if (StringUtils.isEmpty(token)) {
            log.info("token为空");
            httpServletResponse.getWriter().write(JSON.toJSONString(AjaxResult.error("登录过期!","")));
            return false;
        }
        JWT jwt = JWTUtil.parseToken(token);
        Object userId = jwt.getPayload("userId");
        if (userId == null){
            log.info("token携带内容为空");
            httpServletResponse.getWriter().write(JSON.toJSONString(AjaxResult.error("登录过期!","")));
            return false;
        }
        String key = "APP_TOKEN_" + userId;
        if (!redisCache.hasKey(key)) {
            log.info("token过期");
            httpServletResponse.getWriter().write(JSON.toJSONString(AjaxResult.error("登录过期!","")));
            return false;
        }
        String token1 = redisCache.getCacheObject(key);
        if (!StringUtils.equals(token1,token)){
            log.info("token被篡改");
            httpServletResponse.getWriter().write(JSON.toJSONString(AjaxResult.error("登录过期!","")));
            return false;
        }
        return true;
    }

    /**
     * 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    /**
     * 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

}

配置:

package com.zhhs.framework.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.zhhs.project.yazq.auth.AuthenticationInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.zhhs.common.constant.Constants;
import com.zhhs.framework.interceptor.RepeatSubmitInterceptor;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * 通用配置
 *
 */
@Configuration
public class ResourcesConfig implements WebMvcConfigurer {
    /**
     * 首页地址
     */
    @Value("${shiro.user.indexUrl}")
    private String indexUrl;

    @Autowired
    private RepeatSubmitInterceptor repeatSubmitInterceptor;

    @Autowired
    private AuthenticationInterceptor authenticationInterceptor;

    /**
     * 默认首页的设置,当输入域名是可以自动跳转到默认指定的网页
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:" + indexUrl);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /** 本地文件上传路径 */
        registry.addResourceHandler(Constants.RESOURCE_PREFIX + "/**").addResourceLocations("file:" + SystemConfig.getProfile() + "/");
    }

    /**
     * 自定义拦截规则
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**");
        //H5接口拦截
        registry.addInterceptor(authenticationInterceptor).addPathPatterns("/mini-app/**").excludePathPatterns("/mini-app/login");
    }
}