如何使用ReactiveUserDetailsS​​ervice通过springboot通过Rest API登录

时间:2018-10-11 06:31:34

标签: java spring-boot spring-security

我在springboot中使用反应式弹簧安全性,我的前端是用Angular 6构建的,如果我使用springboot默认登录表单,一切都可以正常工作。

我想使用rest api登录。

其他登录方式:

@PostMapping(path = "/login", consumes = MediaType.APPLICATION_JSON_VALUE)
public Mono<UserDetails> login(@RequestBody User user) {
    Mono<UserDetails> isLoggedIn = Mono.empty();
    try{
        isLoggedIn = this.userDetailsService.findByUsername(user.getUsername());
    }catch (RuntimeException e){
        return isLoggedIn;
    }

    return isLoggedIn;
}

我的SecurityConfig正在关注:

@Configuration
@EnableWebFluxSecurity 
public class SecurityConfig {

    @Bean
    SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    http.authorizeExchange().pathMatchers("/login","/signup","/api/users/login","/ui/**","/webjars/**").permitAll()
            .anyExchange().authenticated()
            .and()
            .httpBasic().disable()
            .formLogin().disable()
            .csrf().disable()
            .logout().disable();
    return http.build();
   }
}

我的ReactiveUserDetailService如下:

@Component
public class ServiceReactiveUserDetailsService implements ReactiveUserDetailsService {
     private UserRepo userRepo;

     public ServiceReactiveUserDetailsService(UserRepo userRepo) {
        this.userRepo = userRepo;
     }

     @Bean
     PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
     }

     @Override
     public Mono<UserDetails> findByUsername(String username) {
         return this.userRepo.findByUsername(username).map(CustomUser::new);
     }

    private class CustomUser extends User implements UserDetails {
        public CustomUser(User user) {
            super(user);
        }

       @Override
       public Collection<? extends GrantedAuthority> getAuthorities() {
          return AuthorityUtils.createAuthorityList("ROLE_USER");
       }

       @Override
       public boolean isAccountNonExpired() {
          return true;
       }

       @Override
       public boolean isAccountNonLocked() {
           return true;
       }

       @Override
       public boolean isCredentialsNonExpired() {
          return true;
       }

       @Override
       public boolean isEnabled() {
          return true;
       }
   }
}

我是春季世界的新人,将不胜感激

1 个答案:

答案 0 :(得分:0)

也许尝试使用formLogin.loginPage方法指向您的登录方法,而不是禁用formLogin。我认为问题出在您的安全配置中。

编辑: 这些基调可能会帮助您: https://dzone.com/articles/reactive-spring-security-for-webflux-rest-web-serv https://www.baeldung.com/spring-security-5-reactive