首页 > 解决方案 > Spring Webflux -Security:当jwt令牌过期或错误时如何让Spring返回401(未授权)异常

问题描述

下面是授权 JWT 令牌(Keyclock)的代码,但如果出现异常,服务器永远不会返回 401

@EnableWebFluxSecurity
public class SecurityConfig {

    @Bean
    public SecurityWebFilterChain securityWebFilterChain(final ServerHttpSecurity http) {
    // the matcher for all paths that need to be secured (require a logged-in user)



        http.authorizeExchange(exchanges -> exchanges.pathMatchers("/actuator/**").permitAll()
            .pathMatchers("/abcde/auth").permitAll()
            .pathMatchers("/abcde/auth/refresh").permitAll()
            .anyExchange().authenticated())
            .csrf().disable()
            .oauth2ResourceServer(oauth2ResourceServer ->
                    oauth2ResourceServer
                            .jwt(withDefaults())
            ).exceptionHandling(exception-> exception.authenticationEntryPoint((swe, e) -> Mono.fromRunnable(() -> 
                    {
                        swe.getResponse()
                           .setStatusCode(HttpStatus.UNAUTHORIZED);
                    }
                )
            )
        );
        return http.build();
}

另一个问题 :

这段代码会仅验证 JWT 令牌的到期还是其他验证?究竟发生了什么是我有兴趣知道的。

简而言之,此代码是否足以通过颁发者 URL 进行 keyclock JWT 验证?

标签: spring-bootspring-securitykeycloakspring-security-oauth2spring-webflux

解决方案


推荐阅读