How to customize the authentication failure error to return a message in Body from the reply?

Asked

Viewed 170 times

0

When an authentication failure occurs in Spring Security, it returns an error in the response header. I would like to customize the error and return a message in the reply Body.

Below is the code used to validate Oauth2 with Spring Security Webflux with Opaque Token

@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class SecurityConfig {

    @Value("${spring.security.oauth2.resourceserver.opaque-token.introspection-uri}")
    private String introspectUri;
    @Value("${spring.security.oauth2.resourceserver.opaque-token.client-id}")
    private String clientId;
    @Value("${spring.security.oauth2.resourceserver.opaque-token.client-secret}")
    private String clientSecret;

    @Bean
    SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        http.csrf().disable()
                .formLogin().disable()
                .httpBasic().disable()
                .authorizeExchange()
                .pathMatchers(HttpMethod.OPTIONS).permitAll()
                .pathMatchers("/**").hasRole("read")
                .anyExchange().denyAll()
                .and()
                .oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::opaqueToken);
        return http.build();
    }

    @Bean
    public ReactiveOpaqueTokenIntrospector introspector() {
        return new JwtOpaqueTokenIntrospector(this.introspectUri, this.clientId, this.clientSecret);
    }
}

Current response:

inserir a descrição da imagem aqui

Response I wish to return

{
    "developerMessage": "Unauthorized - make sure the header parameter Authorization is valid",
    "userMessage": "You are not authorized to perform this operation",
    "errorCode": 30001,
    "moreInfo": ""
}
  • Welcome to the Stackoverflow in Portuguese. As the name suggests, the official language used here is Portuguese. So, could you please translate your question? If you prefer, you can also ask the same question on Stackoverflow website in English.

  • Welcome to Stackoverflow in Portuguese. As the name implies, the Official language used here is English. So, can you Please Translate your Question? If you prefer, you may also Ask this same Question in the English Stackoverflow site.

1 answer

0

The most "Spring" way to do this is to use a @RestControllerAdvice to intercept errors and change the error response to the format you want.

In the case of Spring, when it returns error 401, it will probably return the exception AccessDeniedException to signal this. So you can intercept it and exchange it for the answer you would like.

It would be something like that:

@Slf4j
@RestControllerAdvice
public class ErrorHandlerController {

    @ExceptionHandler(AccessDeniedException.class)
    public ResponseEntity<ApiErrorResponse> handleThrowable(AccessDeniedException ex, Locale locale) {
        log.error("Acesso não autorizado na API", ex);
        ApiErrorResponse error = new ApiErrorResponse("Unauthorized - make sure the header parameter Authorization is valid", "You are not authorized to perform this operation", 3001);
        return new ResponseEntity<>(error, HttpStatus.UNAUTHORIZED);
    }

}

The class ApiErrorResponse is the class with developerMessage, userMessage, errorCode and moreInfo.

  • with webflux I can’t get the exception this way, it throws no exceptions. I’m coming up with a solution here, then I’ll post as it turned out. Tks

  • Blz. There are some exceptions to Oauth that won’t work the way I put it up, maybe this is it. Check out my answer on Soen: https://stackoverflow.com/questions/45985310/customize-auth-error-from-spring-security-using-oauth2/55833524#55833524

Browser other questions tagged

You are not signed in. Login or sign up in order to post.