Nov 11
Rerouting Spring Security 2 Login Page Through a Spring Controller
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.


February 3rd, 2009 at 2:14 pm
Couldn’t you also specify
access="ROLE_ANONYMOUS"for login.do? As I understand Spring Security, anonymous users are automatically put in this role.June 5th, 2009 at 8:22 am
Absolutely excelent post, you surely saved me some days. Thanks, good luck.