Nov 11

Rerouting Spring Security 2 Login Page Through a Spring Controller

Tag: acegi, java, jsp, springpmularien @ 12:13 am

Interestingly, a month or so after I posted my 5 Minute Guide to Spring Security 2, a commonly asked question was asked on the Spring forums. I figured I’d address it here, because (once again in Spring/Acegi Security integration) the answer wasn’t really obvious.

Essentially, the question goes something like this:

The examples I can find using Spring Security show this “login.jsp” page. How can I pull Spring content into this page?

Typically, you might want to display data on the login page that’s provided by Spring service-layer beans, or tie into the i18n bundles you’ve configured, or tens of other possibilities.

Fortunately, this is possible with a few tweaks to your Spring configuration. In this post, I’ll assume you’ve started with the configuration I wrote up in the initial 5 Minute Guide to Spring Security.

First, as with any Spring action, you will need a controller to handle the Login page display (the form POST is handled by the Spring Security interceptor). A simple annotated controller might look like this:

/**
 * Simple mapping for login page.
 * 
 * @author Mularien
 */
@Controller
public class LoginController {
	private static Logger logger = Logger.getLogger(LoginController.class);
 
	@Autowired
	// stuff required to display header, footer, etc.
 
	@RequestMapping("/login.do")
	public void login() {
 
	}
 
	@RequestMapping("/accessDenied.do")
	public ModelAndView accessDenied() {
		return new ModelAndView("redirect:/index.do");
	}
}

Now, you can see where we’re going with this. We’ll need a corresponding “login.jsp” page in our views directory, so that the “login.do” mapping works. You’ll need to tweak your Spring Security configuration:

    <http auto-config="true" access-denied-page="/accessDenied.do">
        <intercept-url pattern="/login.do*" filters="none"/>  
        <intercept-url pattern="/app/*.do" access="ROLE_USER,ROLE_ADMIN"  />
        <intercept-url pattern="/admin/**/*.do" access="ROLE_ADMIN"  />
    	<form-login login-page="/login.do" authentication-failure-url="/login.do?login_error=1"
    	   default-target-url="/app/index.do"/>
    	<logout logout-success-url="/login.do"/>
    </http>

Note the references to “login.do” and “accessDenied.do” here - these are the mappings we set up in our login controller. Pay attention to the access rules we’ve assigned - the URL intercept for “/login.do*” has no authorization checks applied to it, this is important otherwise users won’t be able to access the login page!

Hope this helps someone! As always, your comments are appreciated.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="">