在Webflux中实施自定义身份验证管理器时如何在未经授权的请求上响应自定义JSON正文

时间:2020-08-06 20:14:37

标签: spring-boot spring-security spring-webflux project-reactor spring-boot-2

我正在尝试实现自定义JWT令牌身份验证,同时我还在处理全局异常以针对每种异常类型自定义响应主体。一切正常,除了我想在收到未经授权的请求而不是401状态代码时返回自定义json响应。

下面是我对JwtServerAuthenticationConverter和JwtAuthenticationManager的实现。

@Component
public class JwtServerAuthenticationConverter implements ServerAuthenticationConverter {

    private static final String AUTH_HEADER_VALUE_PREFIX = "Bearer ";

    @Override
    public Mono<Authentication> convert(ServerWebExchange exchange) {

        return Mono.justOrEmpty(exchange)
                .flatMap(serverWebExchange -> Mono.justOrEmpty(
                        serverWebExchange
                                .getRequest()
                                .getHeaders()
                                .getFirst(HttpHeaders.AUTHORIZATION)
                        )
                )
                .filter(header -> !header.trim().isEmpty() && header.trim().startsWith(AUTH_HEADER_VALUE_PREFIX))
                .map(header -> header.substring(AUTH_HEADER_VALUE_PREFIX.length()))
                .map(token -> new UsernamePasswordAuthenticationToken(token, token))
                ;
    }
}
@Component
public class JwtAuthenticationManager implements ReactiveAuthenticationManager {

    private final JWTConfig jwtConfig;
    private final ObjectMapper objectMapper;

    public JwtAuthenticationManager(JWTConfig jwtConfig, ObjectMapper objectMapper) {
        this.jwtConfig = jwtConfig;
        this.objectMapper = objectMapper;
    }

    @Override
    public Mono<Authentication> authenticate(Authentication authentication) {

        return Mono.just(authentication)
                .map(auth -> JWTHelper.loadAllClaimsFromToken(auth.getCredentials().toString(), jwtConfig.getSecret()))
                .onErrorResume(throwable -> Mono.error(new JwtException("Unauthorized")))
                .map(claims -> objectMapper.convertValue(claims, JWTUserDetails.class))
                .map(jwtUserDetails ->
                        new UsernamePasswordAuthenticationToken(
                                jwtUserDetails,
                                authentication.getCredentials(),
                                jwtUserDetails.getGrantedAuthorities()
                        )
                )
                ;
    }
}

下面是我的全局异常处理,除了webflux从JwtServerAuthenticationConverter转换方法返回401的情况之外,它的工作都非常好。

@Configuration
@Order(-2)
public class ExceptionHandler implements WebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {

        exchange.getResponse().getHeaders().set("Content-Type", MediaType.APPLICATION_JSON_VALUE);

        return buildErrorResponse(ex)
                .flatMap(
                        r -> r.writeTo(exchange, new HandlerStrategiesResponseContext(HandlerStrategies.withDefaults()))
                );
    }

    private Mono<ServerResponse> buildErrorResponse(Throwable ex) {

        if (ex instanceof RequestEntityValidationException) {

            return ServerResponse.badRequest().contentType(MediaType.APPLICATION_JSON).body(
                    Mono.just(new ErrorResponse(ex.getMessage())),
                    ErrorResponse.class
            );

        } else if (ex instanceof ResponseStatusException) {
            ResponseStatusException exception = (ResponseStatusException) ex;

            if (exception.getStatus().value() == 404) {
                return ServerResponse.status(HttpStatus.NOT_FOUND).contentType(MediaType.APPLICATION_JSON).body(
                        Mono.just(new ErrorResponse("Resource not found - 404")),
                        ErrorResponse.class
                );
            } else if (exception.getStatus().value() == 400) {
                return ServerResponse.status(HttpStatus.BAD_REQUEST).contentType(MediaType.APPLICATION_JSON).body(
                        Mono.just(new ErrorResponse("Unable to parse request body - 400")),
                        ErrorResponse.class
                );
            }

        } else if (ex instanceof JwtException) {

            return ServerResponse.status(HttpStatus.UNAUTHORIZED).contentType(MediaType.APPLICATION_JSON).body(
                    Mono.just(new ErrorResponse(ex.getMessage())),
                    ErrorResponse.class
            );
        }

        ex.printStackTrace();
        return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON).body(
                Mono.just(new ErrorResponse("Internal server error - 500")),
                ErrorResponse.class
        );

    }
}

@RequiredArgsConstructor
class HandlerStrategiesResponseContext implements ServerResponse.Context {

    private final HandlerStrategies handlerStrategies;

    @Override
    public List<HttpMessageWriter<?>> messageWriters() {
        return this.handlerStrategies.messageWriters();
    }

    @Override
    public List<ViewResolver> viewResolvers() {
        return this.handlerStrategies.viewResolvers();
    }
}

@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {

    @Bean
    public SecurityWebFilterChain securityWebFilterChain(
            ServerHttpSecurity http,
            ReactiveAuthenticationManager jwtAuthenticationManager,
            ServerAuthenticationConverter jwtAuthenticationConverter
    ) {

        AuthenticationWebFilter authenticationWebFilter = new AuthenticationWebFilter(jwtAuthenticationManager);
        authenticationWebFilter.setServerAuthenticationConverter(jwtAuthenticationConverter);

        return http
                .authorizeExchange()
                .pathMatchers("/auth/login", "/auth/logout").permitAll()
                .anyExchange().authenticated()
                .and()
                .addFilterAt(authenticationWebFilter, SecurityWebFiltersOrder.AUTHENTICATION)
                .httpBasic()
                .disable()
                .csrf()
                .disable()
                .formLogin()
                .disable()
                .logout()
                .disable()
                .build();
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

所以当我在标题中用无效的JWT令牌击中它时。这是由我的ExceptioHandler类处理的,并且得到的输出低于正常的水平。 enter image description here

但是当我用空的jwt令牌击中它时,我明白了。

enter image description here

现在,在无效的JWT令牌的情况下,我想返回与我返回的相同的主体。但是问题是当提供空令牌时,它甚至不属于ExceptionHandler类的handle方法。那就是为什么它不像我在同一类中为JwtException所做的那样在我的控制之下。我该怎么办,请帮忙?

1 个答案:

答案 0 :(得分:0)

我自己整理一下。 webflux提供了ServerAuthenticationFailureHandler来处理该请求的自定义响应,但不幸的是ServerAuthenticationFailureHandler无法正常工作,这是一个已知问题,因此我创建了一条失败路由,并在其中创建了我的自定义响应,并设置了登录页面。

.formLogin()
.loginPage("/auth/failed")
.and()
.andRoute(path("/auth/failed").and(accept(MediaType.APPLICATION_JSON)), (serverRequest) ->
        ServerResponse
                .status(HttpStatus.UNAUTHORIZED)
                .body(
                        Mono.just(new ErrorResponse("Unauthorized")),
                        ErrorResponse.class
                )
);
相关问题