Spring Boot Security配置:仅允许已认证用户发起POST请求
Great question! Let’s break down how to achieve this clearly, including clarifying what your current configuration already does and how to adjust it if you need more granular control.
First, What Your Current Configuration Already Does
Your existing code actually already meets your requirement! It enforces authentication for all requests (including POST) via HTTP Basic, and disables CSRF protection (which is necessary to prevent Spring Security from blocking POST requests by default in stateless setups):
@Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().authenticated() .and() .httpBasic(); http.csrf().disable(); }
With this setup, any unauthenticated POST request will be rejected with a 401 Unauthorized response, while authenticated users can send POST requests successfully.
If You Want More Granularity (Optional)
If you need to be more explicit (for example, if you have some public endpoints but want all POSTs to require authentication), you can modify the configuration to target POST requests specifically:
import org.springframework.http.HttpMethod; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() // Example: Allow public access to specific GET endpoints .requestMatchers(HttpMethod.GET, "/public/**").permitAll() // Require authentication for ALL POST requests .requestMatchers(HttpMethod.POST, "/**").authenticated() // Require authentication for all other requests .anyRequest().authenticated() .and() .httpBasic() .and() .csrf().disable(); }
Key Details:
- Use
HttpMethod.POSTto target only POST requests. - Replace
"/**"with specific paths (like"/api/v1/**") if you only want certain POST endpoints to be protected. - Disabling CSRF is safe here because you’re using HTTP Basic (a stateless authentication method). If you were using session-based auth (like form login), you’d want to keep CSRF enabled and handle it appropriately.
Testing the Setup
To confirm this works as expected:
- Send a POST request without authentication headers—you should receive a 401 Unauthorized response.
- Send the same POST request with valid HTTP Basic credentials—you should get a successful response (assuming your endpoint logic is correct).
内容的提问来源于stack exchange,提问作者Laurenz Kaml

