SpingBoot+SpringSecurity跨域访问,在请求头headers中加token后,跨域访问请求失败

和黑猫之家聊聊?


ajax跨域访问header带token

headers : {
        "token" : localStorage.getItem("tft_user_token")
    },123

在请求头上加入token后,跨域请求被拦截!SpingBoot+SpringSecurity跨域访问,在请求头headers中加token后,跨域访问请求失败 语言学习 第1张注释掉header后,跨域请求成功,但是我们的要求是要用token做验证,所以header的token不能注释,那怎么办呢?
SpingBoot+SpringSecurity跨域访问,在请求头headers中加token后,跨域访问请求失败 语言学习 第2张

不急,SpringSecurity有配置支持带token的跨域访问,解决方案:

//在 protected void configure(HttpSecurity http)配置中添加下面这行代码:
http.cors().configurationSource(CorsConfigurationSource());

//配置跨域访问资源
private CorsConfigurationSource CorsConfigurationSource() {
        CorsConfigurationSource source =   new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");	//同源配置,*表示任何请求都视为同源,若需指定ip和端口可以改为如“localhost:8080”,多个以“,”分隔;
        corsConfiguration.addAllowedHeader("*");//header,允许哪些header,本案中使用的是token,此处可将*替换为token;
        corsConfiguration.addAllowedMethod("*");	//允许的请求方法,PSOT、GET等
        ((UrlBasedCorsConfigurationSource) source).registerCorsConfiguration("/**",corsConfiguration); //配置允许跨域访问的url
        return source;
    }12345678910111213

经过上面配置后,带token的跨域访问完美解决
SpingBoot+SpringSecurity跨域访问,在请求头headers中加token后,跨域访问请求失败 语言学习 第3张SpingBoot+SpringSecurity跨域访问,在请求头headers中加token后,跨域访问请求失败 语言学习 第4张

文/黑猫之家

来黑猫之家看看呗

Copyright © 2021-2023 | 个人技术展示 |赣ICP备18005425号-1 | 赣公网安备36070202000869 |