UserDetailsS​​ervice被安全配置忽略

时间:2019-04-22 08:53:03

标签: spring-boot spring-security spring-webflux

我已尝试按照文档https://docs.spring.io/spring-security/site/docs/current/reference/html/jc-webflux.html#explicit-webflux-security-configuration

中所述为spring webFlux进行安全配置。

安全配置忽略userDetailsS​​erviceBean-我无法使用user:pass登录,但可以使用自动配置的凭据登录

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
    </parent>

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</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-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

我的pom.xml(片段):

@EnableWebFluxSecurity
@EnableWebSecurity
@Configuration
public class WebfluxSecurityConfig {

    @Bean
    public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
        http
        .authorizeExchange()
        .anyExchange().authenticated()
        .and()
        .httpBasic().and()
        .formLogin();
        return http.build();
    }


    @Bean
    public MapReactiveUserDetailsService userDetailsService() {
         UserDetails user = User.withDefaultPasswordEncoder()
                 .username("user")
                 .password("pass")
                 .roles("USER")
                 .build();
        return new MapReactiveUserDetailsService(user);
    }

}

我的安全配置:

 class ID {
  String title;
  String content;
  String timestamp;

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> ID = new Map<String, dynamic>();
    ID['title'] = this.title;
    ID['content'] = this.content;
    ID['timestamp'] = this.timestamp;
    return ID;
  }
}
  1. 为什么安全性配置会忽略userDetailsS​​ervice?
  2. spring-security文档是否存在错误?

1 个答案:

答案 0 :(得分:0)

  1. 删除@EnableWebSecurity批注。它用于Servlet应用程序,而不应用于WebFlux。

  2. 您还可以考虑在WebFlux配置中定义类型为UserDetailsRepositoryReactiveAuthenticationManager的bean。例如以下内容:

    @Bean
    public ReactiveAuthenticationManager authenticationManager(ReactiveUserDetailsService detailsService) {
         return new UserDetailsRepositoryReactiveAuthenticationManager(detailsService);
    }
    

在您的情况下,最可能是@EnableWebSecurity注释配置了InMemoryUserDetailsManager类型的Bean,它是ReactiveUserDetailsManager的非反应变量。

注意::如果您打算仅使用WebFlux,则可以从POM中删除以下内容:spring-boot-starter-tomcatspring-boot-starter-web