Spring security 3 – How to display login errors ?

Heres how we display different error messages for the different cases of authentication failures like bad credentials, credentials expired etc.

Step 1. Configure an authentication failure handler in the application context.
[code language=”xml”]
<beans:bean id="authenticationFailureHandler"
class="org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler">
<beans:property name="exceptionMappings">
<beans:props>
<beans:prop key="org.springframework.security.authentication.BadCredentialsException">/login/badCredentials</beans:prop>
<beans:prop key="org.springframework.security.authentication.CredentialsExpiredException">/login/credentialsExpired</beans:prop>
<beans:prop key="org.springframework.security.authentication.LockedException">/login/accountLocked</beans:prop>
<beans:prop key="org.springframework.security.authentication.DisabledException">/login/accountDisabled</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
[/code]

Step 2. Refer this handler in the form-login node of http namespace configuration.
[code language=”xml”]
<form-login login-page=’/login’ default-target-url="/home" authentication-failure-handler-ref="authenticationFailureHandler"/>
[/code]

Step3. Capture the different URL extensions configured in step 1 in the login controller. (The example below uses Spring MVC)
[code language=”java”]
@RequestMapping(value = "/login/{error}", method = RequestMethod.GET)

public final String displayLoginform(Model model, @PathVariable final String error) {
model.addAttribute("error", error);
return "login";
}

[/code]

Step 4. Check the attribute error in the JSP and print appropriate message for each case.

Done !

Kj
Kj [/.] Sreekumar programs computers as a hobby and profession. Into programming from his school days, Sree uses Codemarvels to key in facts and fixes he finds interesting while working on different projects. Some of the articles here give away a few shades of his philosophical leanings too.

Leave a Comment

Your email address will not be published. Required fields are marked *