This forum is now a read-only archive. All commenting, posting, registration services have been turned off. Those needing community support and/or wanting to ask questions should refer to the Tag/Forum map, and to http://spring.io/questions for a curated list of stackoverflow tags that Pivotal engineers, and the community, monitor.

Manually requesting authentication from application controller

Jan 30th, 2013, 10:33 AM

We have an application controller that serves various kinds of content, some public and some protected. Hence, we need to leave the endpoint unprotected, yet with the option to require authentication when needed, pseudo-like this:

Code:

public serverContent (request, response) {
if (hasInsufficientAuthentication()) {
// Option 1: Works, unless you capture exceptions for display (SimpleMappingExceptionResolver)
throw new InsufficientAuthenticationException("You need to be authenticated!");
// Option 2: Don't know how to best find these beans, and don't know if this is a good way:
ExceptionTranslationFilter etf = ...; // Where to find this?
AuthenticationEntryPoint aep = etf.getAuthenticationEntryPoint(); // Or some other way?
aep.commence (request, response, new InsufficientAuthenticationException("You need to be authenticated!"));
return;
}
...
}

The questions are like this:
- What is the best way to solve this requirement (One of the above? Something else?)
- If #2, how do I best access the required beans?

I would just wire the AuthenticationEntryPoint directly into the Controller. You can do this by manually creating the AuthenticationEntryPoint in your bean configuration (default implementation is LoginUrlAuthenticationEntryPoint). Then use the http@entry-point-ref attribute to get it to be wired into the ExceptionTranslationFilter. Then the same AuthenticationEntryPoint can be injected into your controller.

Alternatively (and recommended), I would simply throw an AccessDeniedException in your controller. Ensure that Spring MVC allows that exception to propegate and the ExceptionTranslationFilter will catch it and redirect the user to the log in page all on its own. It will also ensure the original page was saved to send the user after they authenticate.