65.9K
CodeProject 正在变化。 阅读更多。
Home

Spring Security 6 中的 CORS

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0投票)

2024年9月2日

CPOL

2分钟阅读

viewsIcon

1618

跨域资源共享 (CORS) 是 Web 安全的一个重要方面,它控制如何从另一个域访问 Web 服务器上的资源。 在 Spring Security 6 中,配置 CORS 可确保您的应用程序与不同域中的资源安全地交互。

1. CORS 简介

1.1 什么是 CORS?

Image
CORS 代表跨域资源共享。 它是 Web 浏览器实现的一项安全功能,用于防止网站向不同的域发出未经授权的请求。 CORS 使用 HTTP 标头来指定允许哪些来源访问 Web 服务器上的资源。

1.2 为什么 CORS 很重要?

CORS 对于通过控制跨域请求来保护 Web 应用程序至关重要。 如果没有正确的 CORS 配置,您的应用程序可能会受到跨站请求伪造 (CSRF) 和跨站脚本 (XSS) 等安全威胁的攻击。 正确配置 CORS 有助于确保只有受信任的域才能访问您的资源。

2. 在 Spring Security 6 中配置 CORS

Spring Security 6 提供了一种使用 SecurityFilterChainCorsConfigurationSource 接口配置 CORS 的现代方法。 此设置提供了一种干净灵活的方式来管理 CORS 策略。

2.1 基本配置

首先,这是一个在 Spring Boot 应用程序中使用 Spring Security 6 配置 CORS 的基本示例
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.servlet.config.annotation.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.UrlBasedCorsConfigurationSource;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.cors(c -> c.configurationSource(corsConfigurationSource()))
            .csrf().disable()
            .authorizeRequests(authorizeRequests ->
                authorizeRequests.anyRequest().authenticated()
            );
        return http.build();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://example.com"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
在此示例中:
  • 我们将 CORS 配置为允许来自 http://example.com 的请求
  • 我们指定允许的 HTTP 方法和标头。
  • 我们启用凭据以允许 cookie 和身份验证标头。

2.2 高级配置

对于更复杂的需求,例如允许特定的标头和公开其他标头,您可以增强您的 CORS 配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.servlet.config.annotation.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.UrlBasedCorsConfigurationSource;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.cors(c -> c.configurationSource(corsConfigurationSource()))
            .csrf().disable()
            .authorizeRequests(authorizeRequests ->
                authorizeRequests.anyRequest().authenticated()
            );
        return http.build();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://example.com"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        configuration.setExposedHeaders(Arrays.asList("Authorization", "Content-Type"));

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
在此高级配置中
  • 我们添加了公开的标头,以允许 AuthorizationContent-Type 标头在响应中可见。
  • 此设置对于需要处理自定义标头或令牌的应用程序非常有用。

3. 测试您的 CORS 配置

设置 CORS 后,测试它是否按预期工作至关重要。 以下是您可以执行此操作的方法

3.1 使用 Postman

  • 打开 Postman 并创建一个新请求。
  • 将请求方法设置为 GET 并输入您的 API 端点。
  • Headers 选项卡下,添加一个新标头 Origin,其值为 http://example.com.
  • 发送请求并检查响应标头中的 Access-Control-Allow-Origin 标头。
示例结果
您应该看到如下所示的响应标头
Access-Control-Allow-Origin: http://example.com

3.2 使用浏览器开发者工具

  • 在浏览器中打开您的 Web 应用程序。
  • 打开浏览器的开发者工具(F12 或右键单击并选择“检查”)。
  • 转到 Network 选项卡并向您的 API 发出请求。
  • 检查响应标头以确保 Access-Control-Allow-Origin 存在且已正确设置。
示例结果
Network 选项卡下的 Headers 部分,您应该看到
Access-Control-Allow-Origin: http://example.com

4. 结论

在 Spring Security 6 中配置 CORS 是安全管理跨域请求的关键步骤。 通过使用 SecurityFilterChain 和 CorsConfigurationSource,您可以轻松设置和自定义 CORS 策略。 测试您的配置可确保您的设置按预期工作,并确保您的应用程序保持安全。
通过此设置,您可以确保您的 Spring Security 6 应用程序受到良好保护,并与受信任的域无缝交互。

阅读更多文章:Spring Security 6 中的 CORS

© . All rights reserved.