首页 > 解决方案 > Spring 反应式安全性

问题描述

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

@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();
    }


}

Web身份验证管理器,

@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 管理器。但是,未经身份验证的调用仍然不会转到 WebAuthenticationManager。

当受保护的 URL 被命中时,它应该会转到 AuthenticationManager。例如,

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

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

在非反应式中,我们有 OncePerRequestFilter 并且正在那里处理身份验证。不确定,如何为反应式实现相同的。

标签: spring-bootspring-securityspring-reactive

解决方案


您禁用了所有身份验证机制,因此没有调用您的身份验证管理器。正如您所提到的,您可以通过过滤器实现身份验证流程。

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

    @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));
}

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


推荐阅读