• 自定义拦截器与配置


    @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<String, String[]> 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");
        }
    }
  • 相关阅读:
    CodeBlocks "no such file or directory" 错误解决方案(创建类找不到头文件)
    WCF配置文件与文件下载之坎坷路
    使用Visual Studio 2010打造C语言编译器
    一个小程序引发的思考
    在C#使用文件监控对象FileSystemWatcher 实现数据同步
    C 语言 static、extern与指针函数介绍
    检测端口是否被占用
    C# ini文件读写类
    C学习笔记(2)--指针
    plsql auto 常用语法
  • 原文地址:https://www.cnblogs.com/person008/p/16087793.html
Copyright © 2020-2023  润新知