解决SpringSecurity跨域问题

解决SpringSecurity跨域问题

报错信息

在这里插入图片描述

Access to XMLHttpRequest at 'http://localhost:8081/test/login' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

跨域问题指的是当一个网页的脚本向不同的域名(或者端口、协议)的服务器请求资源时,会被浏览器拦截。这是因为浏览器出于安全考虑,禁止跨域请求,以防止恶意网站窃取用户信息或者进行其他攻击行为。

此次在开发过程中因前后端分离的原因,使用了SpringSecurity框架,以前的跨域问题解决方案是,如下:

@Configuration
public class WebAppConfigurer implements WebMvcConfigurer {
    /**
     * 处理跨域问题
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE","OPTIONS")
                .maxAge(3600);
    }
}

但是这次不知道咋的,就是不行了,还说提示说跨域问题。报错结果图下:
在这里插入图片描述
在网上查了一下资料。

方法一:排除安全自动配置SecurityAutoConfiguration.class

在启动类的添加@SpringBootApplication注解添加exclude = {SecurityAutoConfiguration.class}。
如下:

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
@MapperScan("com.javaandvue.mapper")
public class JavaVueDameApplication {
	public static void main(String[] args) {
		SpringApplication.run(JavaVueDameApplication.class, args);
	}
}

在这里插入图片描述
响应结果:
在这里插入图片描述

方法二:配置Spring Security

在原来的配置文件之外,再建立一个SecurityConfig 。具体代码与注释如下:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 该方法用于配置应用程序的安全策略。
     * 该代码用于启用跨域资源共享(CORS)功能。
     * CORS是一种机制,允许Web浏览器从一个域向另一个域发出跨域请求。
     * 调用 `http.cors()` 方法会在应用程序的HTTP响应中包含必要的CORS头,从而允许浏览器发出跨域请求。
     * @param http HttpSecurity对象,用于配置应用程序的安全规则
     * @throws Exception 配置过程中可能抛出的异常
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // ...
        http.cors();
    }
}

这样即便不排除SecurityAutoConfiguration.class,也能完成跨域问题的处理。
PS:如果不知道如何选择,就编写两个配置类。一起加上

拓展

配置启用跨域资源共享

    /**
     * 该代码用于启用跨域资源共享(CORS)功能。
     * CORS是一种机制,允许Web浏览器从一个域向另一个域发出跨域请求。
     * 调用 `http.cors()` 方法会在应用程序的HTTP响应中包含必要的CORS头,从而允许浏览器发出跨域请求。
     */
    /**
     * 该代码的作用是允许所有来源的请求,
     * 允许的方法包括GET、POST、OPTIONS、DELETE、PUT和PATCH,
     * 允许的头部包括authorization、content-type和x-auth-token。
     * 通过将该配置源注册到应用程序中,可以实现跨源资源共享。
     * @return
     */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        // 创建一个新的CorsConfiguration对象
        CorsConfiguration configuration = new CorsConfiguration();
        // 设置允许的来源,"*"表示允许所有来源
        configuration.setAllowedOrigins(Arrays.asList("*"));
        // 设置允许的HTTP方法
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS", "DELETE", "PUT", "PATCH"));
        // 设置允许的头部
        configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));
        // 创建一个新的UrlBasedCorsConfigurationSource对象
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 将CorsConfiguration对象注册到URL路径"/**",表示对所有路径生效
        source.registerCorsConfiguration("/**", configuration);
        // 返回配置好的CorsConfigurationSource对象
        return source;
    }
    ```
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security 并不直接解决跨域问题,而是通过集成 Spring MVC 提供的跨域解决方案来处理。 在 Spring MVC 中,可以通过添加 `@CrossOrigin` 注解来实现跨域访问。在 Spring Security 中,可以通过配置 `WebSecurityConfigurerAdapter` 来添加 `CorsConfigurationSource`,从而实现跨域访问。 具体实现方法如下: 1. 在配置类中添加 `CorsConfigurationSource`: ``` @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Arrays.asList("*")); configuration.setAllowedMethods(Arrays.asList("*")); configuration.setAllowedHeaders(Arrays.asList("*")); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } // ... } ``` 2. 将 `CorsFilter` 添加到 Spring Security 过滤器链中: ``` @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { // ... @Override protected void configure(HttpSecurity http) throws Exception { http // ... .cors() .and() // ... } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } } ``` 这样就可以通过 Spring Security 实现跨域访问了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值