У меня есть очень простое приложение для весенней загрузки, чтобы проверить некоторые функции безопасности.Но на первом этапе я потерпел неудачу, и я не совсем понимаю, почему.
Мое приложение является приложением 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();
}
}
И, наконец,config security:
@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
Чтоя делаю не так?