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 !

Sreekumar Kj
Sreekumar (KJ) has been a hobby programmer from school days. Codemarvels is his personal blog from the year 2010, where he writes about technology, philosophy, society and a bit about physics. He now runs a conversational AI company - DheeYantra - focusing his efforts to help businesses improve operational efficiency using digital employees powered by AI.