Spring MVC中豁免认证的控制器方法如何禁用CSRF检查?
Alright, let's tackle this CSRF issue for your webhook endpoint. Since webhooks are typically triggered by external services that don't have access to your app's CSRF tokens, we need to explicitly exclude this specific path from Spring Security's CSRF protection. Here's how you can do it based on your configuration style:
1. Java Configuration (Modern Approach - Spring Security 5.7+)
If you're using Spring Security 5.7 or later, the WebSecurityConfigurerAdapter is deprecated, so we'll use the recommended SecurityFilterChain bean:
@Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http // Configure authorization rules (you already have the permitAll for webhook) .authorizeHttpRequests(auth -> auth .requestMatchers("/web_hook").permitAll() .anyRequest().authenticated() ) // Exclude the webhook path from CSRF checks .csrf(csrf -> csrf .ignoringRequestMatchers("/web_hook") ); return http.build(); } }
2. Java Configuration (Legacy - Using WebSecurityConfigurerAdapter)
If you're still using the older WebSecurityConfigurerAdapter approach:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/web_hook").permitAll() // Your existing auth exemption .anyRequest().authenticated() .and() // Disable CSRF for the webhook endpoint .csrf() .ignoringAntMatchers("/web_hook"); } }
3. XML Configuration
If your project uses XML-based Spring Security configuration:
<security:http> <!-- Existing authorization rule to allow unauthenticated access to webhook --> <security:intercept-url pattern="/web_hook" access="permitAll"/> <security:intercept-url pattern="/**" access="authenticated"/> <!-- Exclude webhook from CSRF protection --> <security:csrf> <security:ignored-request-matcher ref="webHookRequestMatcher"/> </security:csrf> </security:http> <!-- Define the matcher for your webhook path --> <bean id="webHookRequestMatcher" class="org.springframework.security.web.util.matcher.AntPathRequestMatcher"> <constructor-arg value="/web_hook"/> </bean>
Why This Works
Spring Security's CSRF protection is designed to prevent cross-site request forgery attacks, which rely on authenticated users unknowingly sending requests to your app. Since webhooks are initiated by external services (not authenticated users in your app), they can't provide the required CSRF token. Excluding the /web_hook path from CSRF checks ensures these external requests are accepted while keeping CSRF protection enabled for all other endpoints.
内容的提问来源于stack exchange,提问作者Gandalf

