Spring 引导安全性在最简单的情况下不起作用

Spring Boot security is not working in the simplest case

我有一个非常简单的 spring 启动应用程序来测试一些安全功能。但是我第一步就失败了,我也不太明白为什么。

我的应用程序是一个 WebFlux 应用程序,有 2 个用户和 2 个端点。具有 "ADMIN" 角色的用户可以访问其中一个端点,但对于另一个端点,用户只应经过身份验证。但我总是收到 HTTP 401(未经授权)响应。

这是我的 pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo-security</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo-security</name>
<description>Demo project for Spring Boot Security</description>

<properties>
    <java.version>11</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.projectreactor</groupId>
        <artifactId>reactor-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>


<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>11</source>
                <release>11</release>
            </configuration>
        </plugin>   
    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
    </repository>
</repositories>

</project>

这些是我的端点:

@Configuration
public class WebConfiguration {

    Mono<ServerResponse> message(ServerRequest request) {
        return ServerResponse.ok().body(Mono.just("Hello World!"), String.class);
    }

    Mono<ServerResponse> somethingElse(ServerRequest request) {
        return ServerResponse.ok().body(Mono.just("Hello Else!"), String.class);
    }

    @Bean
    RouterFunction<?> routes() {
        return RouterFunctions.route().GET("/message", this::message)
            .GET("/else", this::somethingElse)
            .build();
    }
}

最后是安全配置:

@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {

    @Bean
    ReactiveUserDetailsService userDetailsService() {
        UserDetails user1 = User.withDefaultPasswordEncoder()
            .username("notAdmin")
            .password("notAdmin")
            .roles("SYSTEM", "USER")
            .build();
        UserDetails user2 = User.withDefaultPasswordEncoder()
            .username("admin")
            .password("admin")
            .roles("ADMIN", "USER")
            .build();

        return new MapReactiveUserDetailsService(user1,user2);      
    }

    @Bean
    SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        return http.authorizeExchange()
            .pathMatchers("/message")
                .hasRole("ROLE_ADMIN")
            .anyExchange()
                .authenticated()
            .and()
            .build();
    }
}

这就是我调用服务的方式以及我得到的响应(请注意,两个端点的响应相同):

$ curl -v -uadmin:admin http://localhost:8080/else
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
* Server auth using Basic with user 'admin'
> GET /else HTTP/1.1
> Host: localhost:8080
> Authorization: Basic YWRtaW46YWRtaW4=
> User-Agent: curl/7.54.0
> Accept: */*
> 
< HTTP/1.1 401 Unauthorized
* Authentication problem. Ignoring this.
< WWW-Authenticate: Basic realm="Realm"
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Content-Type-Options: nosniff
< X-Frame-Options: DENY
< X-XSS-Protection: 1 ; mode=block
< Referrer-Policy: no-referrer
< content-length: 0
< 
* Connection #0 to host localhost left intact

我做错了什么?

更新:

在我点击提交按钮后,我发现了问题所在。缺少 .httpBasic()。这是正确的安全配置:

@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {

    @Bean
    ReactiveUserDetailsService userDetailsService() {
        UserDetails user1 = User.withDefaultPasswordEncoder()
            .username("notAdmin")
            .password("notAdmin")
            .roles("SYSTEM", "USER")
            .build();
        UserDetails user2 = User.withDefaultPasswordEncoder()
            .username("admin")
            .password("admin")
            .roles("ADMIN", "USER")
           .build();

        return new MapReactiveUserDetailsService(user1,user2);
    }

    @Bean
    SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        return http.authorizeExchange()
            .pathMatchers("/message")
                .hasRole("ADMIN")
            .anyExchange()
                .authenticated()
            .and()
            .httpBasic()
            .and()
            .build();
    }
}

抱歉,如果给您带来不便!