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

Spring Security过滤器拒绝匿名用户PUT/POST请求问题求助

Troubleshooting Custom Pre-Authentication Filter Issues with POST/DELETE Requests

Hey there, let's work through this problem step by step. I've tackled similar Spring Security pre-authentication filter headaches before, so here are the most likely root causes and optimal fixes to get your /method/do endpoint working for DELETE and POST requests:

1. Verify Filter Execution Order

Spring Security's filter chain order is critical—your custom myPreAuthenticationFilter needs to run before filters that might block the request (like CsrfFilter or other authentication filters). If it's running too late, the request could get rejected before your pre-auth logic even runs.

  • In your springSecurity-applicationContext.xml, set an explicit order property on your filter bean to ensure it runs early. For example, CsrfFilter has an order of 100, so setting your filter to order 90 will place it before:
    <bean id="myPreAuthenticationFilter" class="com.yourpackage.myPreAuthenticationFilter" order="90">
        <property name="authenticationManager" ref="authenticationManager"/>
        <!-- Other properties -->
    </bean>
    
  • Double-check your web.xml filter mapping includes all relevant dispatchers for POST/DELETE:
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher> <!-- Covers all HTTP methods by default, but explicit is safer -->
    </filter-mapping>
    

2. Ensure Your Filter Handles All HTTP Methods

Check your myPreAuthenticationFilter's doFilter method for any hardcoded checks that restrict it to GET requests. It's easy to accidentally add logic like:

if (request.getMethod().equalsIgnoreCase("GET")) {
    // Process authentication
}

If you have something like this, remove it or expand it to include POST and DELETE. The base AbstractPreAuthenticatedProcessingFilter doesn't restrict request methods by default, so the issue is likely in your custom code.

3. Fix CSRF Protection Conflicts

Spring Security enables CSRF protection by default, which blocks POST/DELETE requests that don't include a valid CSRF token. If your pre-authentication flow is for a stateless API (e.g., using API keys instead of sessions), you'll need to either:

  • Exclude your endpoint from CSRF checks:
    <security:http>
        <!-- Other security config -->
        <security:csrf>
            <security:ignored-requests>
                <security:request-matcher ref="apiRequestMatcher"/>
            </security:ignored-requests>
        </security:csrf>
    </security:http>
    
    <bean id="apiRequestMatcher" class="org.springframework.security.web.util.matcher.AntPathRequestMatcher">
        <constructor-arg value="/method/do"/>
        <constructor-arg value="POST"/>
        <constructor-arg value="DELETE"/>
    </bean>
    
  • Include CSRF tokens in your requests: If your client is a web app, make sure you're passing the CSRF token in the X-CSRF-TOKEN header or form parameter.

4. Resolve Authentication Exceptions Properly

If you're hitting exceptions in doFilter, make sure your filter is configured with an AuthenticationEntryPoint to handle failed authentication gracefully. Without this, Spring Security might return a generic 500 error instead of a meaningful 403/401.

Add this to your filter configuration:

<bean id="myPreAuthenticationFilter" class="com.yourpackage.myPreAuthenticationFilter">
    <property name="authenticationManager" ref="authenticationManager"/>
    <property name="authenticationEntryPoint" ref="forbiddenEntryPoint"/>
</bean>

<bean id="forbiddenEntryPoint" class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint"/>

Also, ensure any exceptions thrown in your filter are caught and handled by Spring Security's exception chain—avoid letting raw exceptions bubble up to the servlet container.

5. Fix Request Body/Parameter Retrieval for POST/DELETE

If your filter extracts authentication credentials from the request body (common for POST requests), you might run into issues where the input stream is read once and can't be accessed again by downstream filters. Use ContentCachingRequestWrapper to wrap the request so you can read the body multiple times:

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper((HttpServletRequest) request);
    
    // Extract credentials from wrappedRequest's content
    String requestBody = new String(wrappedRequest.getContentAsByteArray(), StandardCharsets.UTF_8);
    // Your authentication logic here
    
    chain.doFilter(wrappedRequest, response);
}

6. Validate Authentication Manager Configuration

Make sure your AuthenticationManager has a provider that supports PreAuthenticatedAuthenticationToken (the token type used by pre-auth filters). Add this to your security context:

<bean id="preAuthenticatedAuthProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
    <property name="preAuthenticatedUserDetailsService">
        <bean class="org.springframework.security.web.authentication.preauth.PreAuthenticatedGrantedAuthoritiesUserDetailsService"/>
    </property>
</bean>

<security:authentication-manager>
    <security:authentication-provider ref="preAuthenticatedAuthProvider"/>
</security:authentication-manager>

Without this provider, the authentication manager will reject the pre-auth token, leading to request failures.


Start with checking the filter order and CSRF configuration first—those are the most common culprits for POST/DELETE issues with pre-auth filters. If you still hit exceptions, capture the specific exception message and stack trace to narrow down the exact problem.

内容的提问来源于stack exchange,提问作者jpganz18

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:20:15