Check springsecurity, get request is normal, post request 403 error

The springboot version used in this article: 2.7.6

After introducing springsecurity, configure all requests to be accessible:

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    
    
        http.authorizeRequests().anyRequest().permitAll();
        return http.build();
    }
}

When sending a post request, the response is 403:

{
    
    
	"timestamp": "2023-08-03T06:56:00.277+00:00",
	"status": 403,
	"error": "Forbidden",
	"path": "/hi"
}

There was no relevant error message in the console, so I turned on debug and traced to see the specific error details:

debug: true
trace: true

The request was initiated again, and the relevant error information was printed on the console, which was intercepted by the CsrfFilter filter.

o.s.security.web.csrf.CsrfFilter         : Invalid CSRF token found for http://127.0.0.1:9001/hi
o.s.s.w.access.AccessDeniedHandlerImpl   : Responding with 403 status code
o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Writing [{
    
    timestamp=Thu Aug 03 14:56:00 CST 2023, status=403, error=Forbidden, path=/hi}]

According to the class path: ossecurity.web.csrf.CsrfFilter, check the CsrfFilter code. In order to prevent csrf attacks, CsrfFilter will verify the correctness of the csrftoken carried in the request. If it fails, it will respond with 403. Some key codes: So the get
Insert image description here
Insert image description here
request is normal, post A 403 error occurred with the request.

CSRF is a sleeping giant and needs protection. If you don’t use springsecurity csrftoken, just disable csrf:

http.authorizeRequests().anyRequest().permitAll().and().csrf().disable();

Guess you like

Origin blog.csdn.net/weixin_43275277/article/details/132083862