You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot Security配置:仅允许已认证用户发起POST请求

How to Allow POST Requests Only for Authenticated Users in Spring Boot Security

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.POST to 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:

  1. Send a POST request without authentication headers—you should receive a 401 Unauthorized response.
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 09:07:44