Spring Security permitAll 的 POST 请求返回 403 错误

Spring Security Spring Boot About 1,373 words

现象

Spring Security在拦截器规则中放行了/api/testPOST接口,但请求时得到403状态码。

原始代码

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
                .securityMatcher("/api/**")
                .authorizeHttpRequests(authorizeHttpRequests -> {
                    authorizeHttpRequests.requestMatchers("/api/test").permitAll();
                    authorizeHttpRequests.anyRequest().authenticated();
                })
                .oauth2ResourceServer((oauth2) -> oauth2.jwt(Customizer.withDefaults()))
                .build();
    }

}

原因

Spring Security会拦截CSRF攻击,对于POST/PUT/DELETE请求会要求提供_crsf参数,否则会被禁止请求。

禁用 CSRF

CSRF发生在使用Session-Cookie模式下的攻击,对于使用Token/JWT等不借助于Cookie的请求可以直接禁用。

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
                .securityMatcher("/api/**")
                .csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests(authorizeHttpRequests -> {
                    authorizeHttpRequests.requestMatchers("/api/test").permitAll();
                    authorizeHttpRequests.anyRequest().authenticated();
                })
                .oauth2ResourceServer((oauth2) -> oauth2.jwt(Customizer.withDefaults()))
                .build();
    }
Views: 291 · Posted: 2024-04-29

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh