【问题标题】:CSRF disable doesn't work in Spring SecurityCSRF 禁用在 Spring Security 中不起作用
【发布时间】:2020-11-21 18:07:21
【问题描述】:

我目前正在使用 Spring Security 测试 REST API。因为这只是测试,所以我禁用了 CSRF。使用下面的代码,对 /users 的 Postman 获取请求可以完美运行,但来自 Postman 的任何其他类型的请求(例如 post、delete、put)都会返回 403 FORBIDDEN 错误。实在想不通。

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .httpBasic();
    }
}  

【问题讨论】:

  • 你的调试日志告诉你?
  • @ThomasAndolf 不,我没有收到任何消息
  • 你的 spring 安全调试日志会告诉你为什么你会被禁止返回,除非你是从 web 浏览器调用 a,然后检查 web 浏览器控制台 (F12) 你就会知道原因对于那里的禁止。使用 Spring 安全日志更新您的问题
  • @ThomasAndolf 我在哪里可以找到这些日志?我的控制台中没有显示任何内容。
  • 我不知道你是如何运行你的应用程序的,这取决于你是否在 eclipse、intellij、netbeans、命令行等中运行。如果你不知道如何查找/阅读日志,我建议您在尝试 Spring Security 之前先了解一下,以及如何调试您的应用程序。

标签: spring spring-boot spring-security csrf


【解决方案1】:

您是否有任何 cors 配置设置以允许“GET”以外的方法?

您可以创建一个CorsConfigurationSource bean,它应该允许访问这些类型的请求


@Configuration
public class CorsConfig {

    private static final String[] CORS_ALLOWED_HEADERS = new String[] {
        "*",
    };

    private static final String[] CORS_ALLOWED_METHODS = new String[] {
        "GET",
        "POST",
        "PUT",
        "OPTIONS"
    };

    private static final String CORS_API_PATTERN = "/api/**";

    private static final long CORS_MAX_AGE = 3600;

    @Value("${cors.allowed-origins}")
    private String[] corsAllowedOrigins;

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {

        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList(corsAllowedOrigins));
        configuration.setAllowedMethods(Arrays.asList(CORS_ALLOWED_METHODS));
        configuration.setAllowCredentials(true);
        configuration.setMaxAge(CORS_MAX_AGE);
        configuration.setAllowedHeaders(Arrays.asList(CORS_ALLOWED_HEADERS));

        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration(CORS_API_PATTERN, configuration);

        return source;

    }

【讨论】:

    猜你喜欢
    • 2018-12-12
    • 2022-12-15
    • 2020-05-09
    • 2016-06-30
    • 2014-03-12
    • 2014-04-26
    • 2015-09-27
    • 2021-05-06
    相关资源
    最近更新 更多