Spring Security blocks POST requests despite SecurityConfig

后端 未结 3 1066
囚心锁ツ
囚心锁ツ 2021-02-12 15:27

I\'m developing a REST API based on Spring Boot (spring-boot-starter-web) where I use Spring Security (spring-security-core e spring-security-con

3条回答
  •  梦毁少年i
    2021-02-12 16:09

    There were 2 issues in SecurityConfiguration.java that made it misbehave.

    Although the 403 Forbidden error message didn't contain any message indication of why it was failing (see example below) it turns out it was due to having CSRF enabled. Disabling it allowed for POST and DELETE requests to be processed.

    {
        "timestamp": "2018-06-26T09:17:19.672+0000",
        "status": 403,
        "error": "Forbidden",
        "message": "Forbidden",
        "path": "/routeB"
    }
    

    Also the expression used in antMatched(HttpMethod, String) for RouteB was incorrect because /routeB/* expects it to have something after /. The correct configurtion is /routeB/** since more paths can be present (or not).


    The corrected SecurityConfiguration.java is

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().
            authorizeRequests().antMatchers(HttpMethod.GET, "/**").hasAnyRole("ADMIN", "USER")
                               .antMatchers(HttpMethod.POST, "/routeA/**").hasAnyRole("ADMIN", "USER")
                               .antMatchers(HttpMethod.POST, "/routeB/**").hasRole("ADMIN")
                               .antMatchers(HttpMethod.DELETE, "/routeB/**").hasRole("ADMIN").and().
            requestCache().requestCache(new NullRequestCache()).and().
            httpBasic().authenticationEntryPoint(authenticationEntryPoint).and().
            cors().and().
            csrf().disable();
    }
    

    Source: StackOverflow em Português

提交回复
热议问题