Reputation: 591
I have two authentication providers. One checks against the database and the other is a pre-authenticated provider for SAML assertion.
User information and their respective roles are persisted in a DB. So when the user hits application with SAML, we insert a row in the database and assign a default role after which redirect the user to a registration page where we capture some user specific information.
With PreAuthenticatedProvider I am catching UserNotFoundException and the question is how do I redirect the user to registration page from my authenticate method?
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
try {
// custom code
} catch (UsernameNotFoundException e) {
// Redirect user to a view
}
}
Is there a better way of handling such cases?
EDIT: I am interested in handling AuthenticationExceptions coming from AuthenticationProviders particularly PreAuthenticationProviders.
Upvotes: 3
Views: 2274
Reputation: 6052
You can write your own Custom ExceptionTranslationFilter
and put it in the filter chain before the form processin filter to catch these exceptions and handle properly.
Something like this in the application-context.xml
<bean id="customExceptionFilter" class="com.company.module.security.filters.CustomExceptionTranslationFilter">
<constructor-arg ref="authenticationEntryPoint"/>
<constructor-arg ref="savedRequestCache"></constructor-arg>
<property name="accessDeniedHandler" ref="customAccessDeniedHandler"/>
</bean>
Your ExceptionTransalationFilter need to extend ExceptionTranslationFilter
and Override the doFilter
Method:
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
ServletException
{
try
{
super.doFilter(req, res, chain);
}
catch (Exception ex)
{
// Handle the exception here
logger.error("Exception - ", ex);
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (SecurityHelper.isAjaxRequest(request))
{
writeFailedAjaxResponse(response, ErrorCode.INTERNAL_ERROR);
return;
}
else
{
throw new ServletException(ex);
}
}
}
Look under 8.2 Here:
http://static.springsource.org/spring-security/site/docs/3.0.x/reference/core-web-filters.html
Upvotes: 1