春季反应式安全

时间:2020-04-13 21:52:36

标签: spring-boot spring-security spring-reactive

我正在尝试响应式安全性,并且未经身份验证的呼叫不会转到身份验证管理器。

@Configuration
@EnableWebFluxSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig{
    @Autowired
    private WebAuthenticationManager authenticationManager;

    @Autowired
    private ServerSecurityContextRepository securityContextRepository;

    private static final String[] AUTH_WHITELIST = {
            "/login/**",
            "/logout/**",
            "/authorize/**",
            "/favicon.ico",
    };

    @Bean
    public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) {
        return http.exceptionHandling().authenticationEntryPoint((swe, e) -> {
            return Mono.fromRunnable(() -> {
                swe.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            });
        }).accessDeniedHandler((swe, e) -> {
            return Mono.fromRunnable(() -> {
                swe.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
            });
        }).and().csrf().disable()
                .formLogin().disable()
                .httpBasic().disable()
                .authenticationManager(authenticationManager)
                .securityContextRepository(NoOpServerSecurityContextRepository.getInstance())
                .authorizeExchange().pathMatchers(HttpMethod.OPTIONS).permitAll()
                .pathMatchers(AUTH_WHITELIST).permitAll()
                .anyExchange().authenticated().and().build();
    }

    @Bean
    public PBKDF2Encoder passwordEncoder() {
        return new PBKDF2Encoder();
    }


}

WebAuthentication Manager,

@Component
public class WebAuthenticationManager implements ReactiveAuthenticationManager {

    @Autowired
    private JWTUtil jwtUtil;

    @Override
    public Mono<Authentication> authenticate(Authentication authentication) {
        String authToken = authentication.getCredentials().toString();

        String username;
        try {
            username = jwtUtil.getUsernameFromToken(authToken);
        } catch (Exception e) {
            username = null;
        }
        if (username != null && jwtUtil.validateToken(authToken)) {
            Claims claims = jwtUtil.getAllClaimsFromToken(authToken);
            List<String> rolesMap = claims.get("role", List.class);
            List<Role> roles = new ArrayList<>();
            for (String rolemap : rolesMap) {
                roles.add(Role.valueOf(rolemap));
            }
            UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
                username,
                null,
                roles.stream().map(authority -> new SimpleGrantedAuthority(authority.name())).collect(Collectors.toList())
            );
            return Mono.just(auth);
        } else {
            return Mono.empty();
        }
    }
}

在这里,我已经在Securityconfig中注册了WebAuthentication Manager。但是,未经身份验证的调用仍然不会转到WebAuthenticationManager。

当击中受保护的URL时,应转到AuthenticationManager。对于

http://localhost:8080/api/v1/user

不确定,为什么通话不会转到AuthManager。

在非反应式中,我们具有OncePerRequestFilter,并且那里的auth被照顾。不确定如何为反应式实现相同的功能。

1 个答案:

答案 0 :(得分:1)

您已禁用所有身份验证机制,因此无需调用身份验证管理器。如前所述,您可以通过过滤器实现身份验证流程。

身份验证过滤器的示例实现:

    @Bean
    public AuthenticationWebFilter webFilter() {
    AuthenticationWebFilter authenticationWebFilter = new AuthenticationWebFilter(authenticationManager);
    authenticationWebFilter.setServerAuthenticationConverter(tokenAuthenticationConverter());
    authenticationWebFilter.setRequiresAuthenticationMatcher(serverWebExchangeMatcher());
    authenticationWebFilter.setSecurityContextRepository(NoOpServerSecurityContextRepository.getInstance());
    return authenticationWebFilter;
}

然后将此过滤器添加到ServerHttpSecurity:http.addFilterBefore(webFilter(),SecurityWebFiltersOrder.HTTP_BASIC)

然后最后将调用您的身份验证管理器。


您必须提供一些其他东西才能使其正常工作。
匹配器,以检查是否将Authorization标头添加到请求中:

    @Bean
    public ServerWebExchangeMatcher serverWebExchangeMatcher() {
    return exchange -> {
        Mono<ServerHttpRequest> request = Mono.just(exchange).map(ServerWebExchange::getRequest);
        return request.map(ServerHttpRequest::getHeaders)
                .filter(h -> h.containsKey(HttpHeaders.AUTHORIZATION))
                .flatMap($ -> ServerWebExchangeMatcher.MatchResult.match())
                .switchIfEmpty(ServerWebExchangeMatcher.MatchResult.notMatch());
    };
}

令牌转换器负责从请求中获取令牌并准备基本的AbstractAuthenticationToken

    @Bean
    public ServerAuthenticationConverter tokenAuthenticationConverter() {
    return exchange -> Mono.justOrEmpty(exchange)
            .map(e -> getTokenFromRequest(e))
            .filter(token -> !StringUtils.isEmpty(token))
            .map(token -> getAuthentication(token));
}

我故意省略了getTokenFromRequestgetAuthentication的实现,因为有很多可用的示例。