springboot创建拦截器,导致跨域配置失效

一、创建拦截器

1、自定义拦截器

import com.jipaocampus.jipao_campus.utils.JwtUtils;
import com.jipaocampus.jipao_campus.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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

/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 前置处理
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("登录拦截");
        //获取用户token
        String token = request.getHeader("token");
        System.out.println("token-->"+token);
        //通过token解析出用户ID
        String userId = JwtUtils.getId(token);
        //获取缓存中token
        Object o = redisUtil.get(userId + "");
        if(o == null){
            //没有登录,重定向到login页面
            //没登录,要去登录
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            //返回false,拦截
            return false;
        }
        //续期半小时
        redisUtil.set(userId,token,1800);
        //返回true,放行
        return true;
    }
}

2、加载拦截器

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@ComponentScan
public class MyInterceptorConfig implements WebMvcConfigurer {

    @Autowired
    private LoginInterceptor loginInterceptor;


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        System.out.println("登录拦截配置");
        registry.addInterceptor(loginInterceptor)
                //添加拦截路径
                .addPathPatterns("/**")
                //添加不拦截路径
                .excludePathPatterns("/user/login");
    }
}

二、SpringBoot创建拦截器,跨域配置失效

1、原因:添加的自定义登录拦截器是在跨域拦截器之前执行的,导致跨域拦截器失效。跨域拦截器代码如下所示:

@Configuration
public class CrossOriginConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedHeaders("*")
                .allowedMethods("*")
                .allowCredentials(true)
                .allowedOriginPatterns("*")
//                .allowedOrigins("http://www.jipaoxiaoyuan.com:8086","http://jipaoxiaoyuan.com:8086","http://localhost:8888")
                .maxAge(3600);
    }
}

 2、解决方法:让跨域配置在登录拦截器之前执行。而Filter的执行顺序大于自定义拦截器,所以改为在Filter里实现跨域的配置。

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 跨域配置
 */
@Configuration
public class Filter {
    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOriginPattern("*");//*表示允许所有
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config); // CORS 配置对所有接口都有效
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值