iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot+Spring Security无法实现跨域的解决方案
  • 500
分享到

SpringBoot+Spring Security无法实现跨域的解决方案

2024-04-02 19:04:59 500人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

SpringBoot+spring Security无法实现跨域 未使用Security时跨域: import org.slf4j.Logger; import org.slf4

SpringBoot+spring Security无法实现跨域

未使用Security时跨域:


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.context.annotation.Configuration;
import org.springframework.fORMat.FormatterReGIStry;
import org.springframework.WEB.servlet.config.annotation.*;
@Configuration
@AutoConfigureBefore(SecurityConfig.class)
public class MymvcConfigurer implements WebMvcConfigurer {
    public void addCorsMappings(CorsRegistry registry){
        LOGGER.info("跨域已设置");
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("*")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
}

整合Security时发现只用上述方法前后端分离时仍存在跨域问题,

解决方法如下:


@Configuration
@AutoConfigureBefore(swagger2Configuration.class)
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(-1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(httpsecurity Http) throws Exception {
        http.formLogin()
                .loginProcessingUrl("/user/login")
                .loginPage("/singIn.html")
                .successhandler(moyuAuthenticationSuccessHandler)
                .failureHandler(moyuAuthenticationFailureHandler)
                .and()
                .apply(moyuSocialSecurityConfig)
                .and()
                .rememberMe()
                .tokenRepository(persistentTokenRepository())
                .tokenValiditySeconds(3600*24*7)
                .userDetailsService(userDetailsService)
                .and()
                .authorizeRequests()
                .antMatchers("/user/login","/login","/singIn.html","**","/**").permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .cors()
                .and()
                .csrf().disable();
    }
}

重点加入代码:


   .and()
   .cors()//新加入
   .and()
   .csrf().disable();

引用Spring Security 项目的跨域处理

最近项目采用了前后端分离的框架前端和后台接口没有部署到一个站点,出现了跨域问题,什么是跨域,这里就不再赘述,直接说解决办法。

Spring 解决跨域的方式有很多,个人采用了Crosfilter的方式

具体代码如下:


@Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new      UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }

配置完成后,测试调用,报错401,依然不行。网上查资料得知,跨域请求会进行两次。具体流程见下图:

这里写图片描述

每次跨域请求,真正请求到达后端之前,浏览器都会先发起一个preflight request,请求方式为OPTIONS 询问服务端是否接受该跨域请求,具体参数如下图:

这里写图片描述

但是该请求不能携带cookie和自己定义的header。

由于项目中引入了Spring security ,而我使用的token传递方式是在header中使用authorization 字段,这样依赖Spring Security拦截到 preflight request 发现它没有携带token,就会报错401,没有授权。

解决这个问题很简单,可以使用以下配置

让Spring security 不校验preflight request 。


 @Override
    public void configure(HttpSecurity http) throws Exception {
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry 
        = http.authorizeRequests();
        registry.requestMatchers(CorsUtils::isPreFlightRequest).permitAll();//让Spring security放行所有preflight request 
    }

再试就搞定了,但是后端直接配置支持跨域会导致两次请求。还使用另一种方式,使用Nginx 转发一下请求也可以。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: SpringBoot+Spring Security无法实现跨域的解决方案

本文链接: https://www.lsjlt.com/news/130672.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作