An AuthenticationServiceException
represents something that went wrong on the server side. As such, it shouldn't be handled by AuthenticationEntryPoint
s.
This means that likely is shouldn't be handled by ExceptionTranslationFilter
or any of the authentication filters.
However, because this class extends AuthenticationException
, it is required for each component to somehow opt-out of handing to its AuthenticationEntryPoint
.
One way to address this is to change AuthenticationServiceException
to no longer inherit from AuthenticationException
. Another way would be to add a new exception like AuthenticationServerErrorException
-- similar to spring-web
's HttpServerErrorException
-- that doesn't inherit from AuthenticationException
.
Comment From: rpvilao
EDIT: For now, I am using your solution from https://github.com/spring-projects/spring-security/issues/10818 by adding an ObjectPostProcessor.
Hi Josh! I bumped into this ticket after I upgraded spring-security-core to 5.7.6 where my authenticationEntryPoint functions are no longer picking up exceptions thrown by the oauth2 introspector (wrapped in an AuthenticationServiceException even though it still extends from AuthenticationException).
So now I am confused... is that already in place? If so, what's the best way to handle these exceptions? Even with a @RestControllerAdvice they are not handled.
If not... what's happening?
Thanks!
Comment From: amitbhoraniya
Hi @rpvilao @jzheaux - I am not sure what went wrong, atleast previously we were able to handle all exceptions with RestControllerAdvice
. But now if anything unexpected happens in AuthenticationService, then its not being handled using RestControllerAdvice
and throws response in different way. It doesn't allow us to modify error response in standard way.
Would you please help with same ?
Comment From: rpvilao
Hi @amitbhoraniya,
It was some time ago but I guess I just ended up implementing an object post processor:
.withObjectPostProcessor(object : ObjectPostProcessor<BearerTokenAuthenticationFilter> {
override fun <O : BearerTokenAuthenticationFilter> postProcess(o: O): O {
o.setAuthenticationFailureHandler { _: HttpServletRequest, httpServletResponse: HttpServletResponse, e: AuthenticationException ->
httpServletResponse.contentType = ContentType.APPLICATION_JSON.mimeType
httpServletResponse.status = HttpServletResponse.SC_UNAUTHORIZED
JsonUtils.objectMapper.writeValue(
httpServletResponse.outputStream,
OAuth2ErrorResponse.builder()
.withError("invalid_token")
.withErrorDescription(e.message)
.build()
)
}
return o
}
})
The example is in koltin, you can adapt to your needs.
Comment From: amitbhoraniya
@rpvilao - Yes, I did same and working for me. I am still wondering why RestControllerAdvice
is not able to handle such exceptions. Is it expected behavior or is it bug ??
Comment From: rpvilao
I don't know, maybe someone from spring security can answer that question.