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.

	<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>

Step 2. Refer this handler in the form-login node of http namespace configuration.

 <form-login login-page='/login' default-target-url="/home"  authentication-failure-handler-ref="authenticationFailureHandler"/>

Step3. Capture the different URL extensions configured in step 1 in the login controller. (The example below uses Spring MVC)

    @RequestMapping(value = "/login/{error}", method = RequestMethod.GET)
   
    public final String displayLoginform(Model model,  @PathVariable final String error) {
        model.addAttribute("error", error);
    	return "login";
    }

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

Done !

Leave a Reply

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

*

* Copy This Password *

* Type Or Paste Password Here *

43,752 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>