Reactive Spring 5安全性,自定义用户服务无阻塞

时间:2017-10-19 03:28:46

标签: spring spring-security

我有以下Spring 5安全配置:

@Configuration
@EnableWebFluxSecurity
class SecurityConfiguration(private val us: UserService) : UserDetailsRepository {

    override fun findByUsername(username: String?): Mono<UserDetails> {
        if (username != null) {
            val user = us.byUsername(username).block()
            val grantedAuthorities = user.roles!!
                    .map{SimpleGrantedAuthority(it)}

            var userDetails: UserDetails = org.springframework.security.core.userdetails.User(user.username,
                    user.password, user.enabled, user.accountNonExpired, user.credentialsNonExpired,user.accountNonLocked,
                    grantedAuthorities)

            return userDetails.toMono()
        }
        throw UsernameNotFoundException("Username is null")
    }
}

我正在使用自定义用户服务,并将此User映射到Spring Security UserDetails对象。要获取User对象,我需要使用block()语句。有没有办法让这段代码无阻塞?

1 个答案:

答案 0 :(得分:0)

这是一个java实现

@Override
public Mono<UserDetails> findByUsername(String username) {
    return userRepository.findByUsername(username).map(new Function<User, UserDetails>() {
        @Override
        public UserDetails apply(User user) {
            List<GrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
                    true, true, true, true, authorities);
        }
    });
}