Spring Security Springboot 3 Webflux + Spring安全CSRF禁用不起作用

y1aodyip  于 2022-12-18  发布在  Spring
关注(0)|答案(1)|浏览(544)

今天我把我的Webflux REST API演示应用从springboot 2.7.x升级到了3.0.0版本。在测试中发现了SpringSecurity的POST调用,我得到了403 Forbidden和消息An expected CSRF token cannot be found。我仔细检查了我的安全配置,没有发现任何问题。

@Bean
    public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
        return http
            .csrf().disable()
            .authorizeExchange()
            .pathMatchers(HttpMethod.GET, "/actuator/**").permitAll()
            .pathMatchers(HttpMethod.POST, "/api/v1/users", "/api/v1/users/**").hasRole(ReactiveConstant.SECURITY_ROLE_ADMIN)     // Only admin can do POST
            .pathMatchers(HttpMethod.GET, "/api/v1/users", "/api/v1/users/**").hasAnyRole(ReactiveConstant.SECURITY_ROLE_USER, ReactiveConstant.SECURITY_ROLE_ADMIN)       // user can only do GET
            .anyExchange().authenticated()
            .and().formLogin()
            .and().httpBasic()
            .and().formLogin().disable()
            .build();
    }

这是在SpringBoot 2.7.5版本中工作的。我的build.gradle文件,

plugins {
    id 'org.springframework.boot' version '3.0.0'
    id 'io.spring.dependency-management' version '1.1.0'
    id 'java'
    id 'groovy'
}

group = 'io.c12.bala'
version = '0.2.1'
sourceCompatibility = JavaVersion.VERSION_17

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenLocal()
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-mongodb-reactive'
    implementation 'org.springframework.boot:spring-boot-starter-webflux'
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'org.springframework.boot:spring-boot-starter-validation'
    implementation 'org.springframework.boot:spring-boot-starter-security'

    // Springboot utils
    implementation 'io.projectreactor:reactor-tools'            // For Reactor debugging in IDE
    compileOnly 'org.projectlombok:lombok'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    annotationProcessor 'org.projectlombok:lombok'
    implementation 'org.modelmapper:modelmapper:3.1.0'
    implementation 'io.netty:netty-resolver-dns-native-macos:4.1.85.Final:osx-aarch_64'     // For macos netty DNS issue.
    implementation 'com.aventrix.jnanoid:jnanoid:2.0.0'

    // Springboot testing with Spock test framework
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.security:spring-security-test'

    // Spock test framework
    testImplementation 'org.spockframework:spock-core:2.3-groovy-4.0'
    testImplementation 'org.spockframework:spock-spring:2.3-groovy-4.0'

    // Reactor test framework
    testImplementation 'io.projectreactor:reactor-test'
}

test {
    useJUnitPlatform()
    maxParallelForks = Runtime.runtime.availableProcessors()
}

我在SpringSecurity文档中没有看到CSRF的任何更改。
我的POST调用,

curl --location --request POST 'http://localhost:8080/api/v1/users' \
--header 'Authorization: Basic am9objpIZWxsb1dvcmxkQDEyMw==' \
--header 'Content-Type: application/json' \
--data-raw '{
  "firstName": "John",
  "lastName": "Doe",
  "emailId": "John.doe@example.com",
  "userId": "j.doe"
}'

响应:403 Forbidden

An expected CSRF token cannot be found
xyhw6mcr

xyhw6mcr1#

今天我在将webflux应用程序迁移到Sping Boot 3.0.0时遇到了同样的症状,它在2.7.5中运行得很好。所以我在谷歌上搜索“禁用csrf不再工作”,发现了这个和一些其他的帖子...
但是,Spring security 6的注解变更导致了该问题:@EnableWebFluxSecurity在5. x版本中包含了“@Configuration”(我检查过了)--但显然不再包含,必须显式添加。
因此,在迁移之后没有找到完整的SecurityWebFilterChain bean...现在,工作代码如下所示:

@EnableWebFluxSecurity
@Configuration       // <- this annotation was missing but worked with Spring Security 5.x
public class AccountWebSecurityConfig { 

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http,
                                                        ReactiveAuthenticationManager authenticationManager,
                                                        ServerAccessDeniedHandler accessDeniedHandler,
                                                        ServerAuthenticationEntryPoint authenticationEntryPoint) {
    http.csrf().disable()
            .httpBasic(httpBasicSpec -> httpBasicSpec
                    .authenticationManager(authenticationManager)
                    // when moving next line to exceptionHandlingSpecs, get empty body 401 for authentication failures (e.g. Invalid Credentials)
                    .authenticationEntryPoint(authenticationEntryPoint)
            )
            .authorizeExchange()
    //...
}

由于FilterChain-snippet没有在类中显示注解,因此很有可能您还丢失了@Configuration..
在我的情况下,现在一切都像以前一样工作:-)

相关问题