hekomobile
hekomobile

Reputation: 1388

How do I get the user when logs incorrectly with Spring Security?

I am using Spring security for interceptor to user wrong logged, but I can not find the way to do.

I specifically want to save the user logged in last, but I can't figure out how to achieve this.

Please help me.

Upvotes: 2

Views: 2456

Answers (1)

Japan Trivedi
Japan Trivedi

Reputation: 4483

Yes you can do that. You can define following tag in tag in your configuration xml file.

<security:form-login login-page="/sessionexpired" 
login-processing-url="/j_spring_security_check" 
default-target-url="/submitLogin" 
always-use-default-target="true" 
authentication-failure-handler-ref="customAuthenticationFailureHandler"/>

You can see the last parameter set authentication-failure-handler-ref its value is a refenrece to following bean defined in the same xml file.

<bean id="customAuthenticationFailureHandler" class="com.xxx.xxx.xxx.CustomFilter">
        <constructor-arg type="String" value="loginfailed"></constructor-arg>
        <constructor-arg type="org.hibernate.SessionFactory" ref="sessionFactory"></constructor-arg>        
</bean>

The class defined in this bean is your own class that will get the information about the failed login details.

public class CustomFilter extends SimpleUrlAuthenticationFailureHandler {

    private String defaultFailureUrl;      
    private SessionFactory sessionFactory;


    public CustomFilter(String defaultFailureUrl,SessionFactory sessionFactory) {
        super();
        this.defaultFailureUrl = defaultFailureUrl;
        this.sessionFactory = sessionFactory;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
            HttpServletResponse response, AuthenticationException exception)
            throws IOException, ServletException {
        // TODO Auto-generated method stub

        String userName = request.getParameter("j_username");;
        /*System.out.println("CustomFilter Begins");        
        System.out.println("CustomeFilter.username :: " + userName);
        System.out.println("getMessage :: " + exception.getMessage());
        System.out.println("exception :: " + exception.getClass().getSimpleName());
        System.out.println("RemoteAddr :: " + request.getRemoteAddr());        */
    }
}

When the Authentication will be failed then method onAuthenticationFailure of this class will be called and you can get the user details there to log in database or log file.

Hope this helps you. Cheers.

Upvotes: 3

Related Questions