Announcement Announcement Module
Collapse
No announcement yet.
Spring Security 3 and Ajax type login Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Spring Security 3 and Ajax type login

    I'm new to Spring Security. However, in a fairly short time I've got it integrated with my project, compiling, and basically working. Now, my challenge.

    We have a web application that is one page, /index.jsp. Once that page loads, all other interaction is via Ajax calls. So the initial access to index.jsp has to allow anonymous access. When a user logins in, we submit an Ajax call e.g. myapp/users/action/login.action.

    So, what I want to do (I think based on my reading of the doc) is to create a custom UsernamePasswordAuthenticationFilter and have this intercept the Ajax login call. I've created the custom filter and have implemented the below applicationContext-security.xml file. In short, it never gets invoked. So I'm sure I don't have the config right. Or my approach to this problem could also be wrong.

    Anyway, all help appreciated. Thanks.
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    
    <!--
      - Sample namespace-based configuration
      -
      -->
    
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schem...-beans-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.0.xsd">
    
        <security:global-method-security secured-annotations="enabled">
        </security:global-method-security>
    
    	<security:http entry-point-ref="loginUrlAuthenticationEntryPoint" auto-config='false'>
    		<security:custom-filter position="FORM_LOGIN_FILTER" ref="tnFilter" />
    		<security:intercept-url pattern="/index2.jsp*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
    		<security:intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
    		<security:port-mappings>
    			<security:port-mapping http="8080" https="8443"/>
    		</security:port-mappings>
    	</security:http>
    	 
    	<security:authentication-manager alias="authenticationManager" >
    	<security:authentication-provider>
    		<security:jdbc-user-service data-source-ref="dataSource" 
    users-by-username-query="select user_name, password, enabled from site_users where user_name=?"
    authorities-by-username-query="select user_name,authority from site_users where user_name=?"/>
    	</security:authentication-provider>
    	</security:authentication-manager>
    	
    	<bean id="loginUrlAuthenticationEntryPoint"
    class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
     <property name="loginFormUrl" value="/index2.jsp" />
    </bean>
    
    <bean id="tnFilter"
    class="com.tattlenow.common.util.TNUsernamePasswordAuthenticationFilter" >
     <property name="authenticationManager" ref="authenticationManager" />
     <property name="authenticationFailureHandler" ref="failureHandler" />
     <property name="authenticationSuccessHandler" ref="successHandler" />
     <property name="filterProcessesUrl" value="/login.action*"/>
    </bean>
    
    <bean id="successHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
     <property name="defaultTargetUrl" value="/index2.jsp" />
    </bean>
    <bean id="failureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
     <property name="defaultFailureUrl" value="/index2.jsp" />
    </bean>
    
    </beans>
    Last edited by Luke Taylor; Mar 25th, 2010, 07:34 AM. Reason: Added code tags

  • #2
    What requests are sent from the browser and what is the corresponding debug output?

    Comment


    • #3
      The request from the browser is of the form:

      http://localhost:8080/myapp/users/action/login.action?

      with the user name and password passed as request parameters.

      This goes thru without being intercepted by the filter. e.g. without invoking by custom TNUsernamePasswordAuthenticationFilter.

      Comment


      • #4
        What is the corresponding debug log output?

        Comment


        • #5
          I'v got AJAX-style login working but I'm using ExtJs, I followed this:
          http://loianegroner.com/2010/02/inte...js-login-page/

          But I needed to change some stuff to make it working with Spring Security 3.0.

          I made some JSON handlers to return correct information, if you interested I can give you the code. But I'm not sure this would apply to your problem.

          Alois Cochard
          http://aloiscochard.blogspot.com
          http://www.twitter.com/aloiscochard

          Comment


          • #6
            What log output do you want exactly? Do you want to see the log ouput from the app starting up? Or post start-up?

            Comment


            • #7
              Actually, let me look at the posting by Alois Cochard. That looks very close to what I want to achieve. I will try that and update with my findings. Thanks.

              Comment


              • #8
                Originally posted by alois.cochard View Post
                I'v got AJAX-style login working but I'm using ExtJs, I followed this:
                http://loianegroner.com/2010/02/inte...js-login-page/

                But I needed to change some stuff to make it working with Spring Security 3.0.

                I made some JSON handlers to return correct information, if you interested I can give you the code. But I'm not sure this would apply to your problem.

                Alois Cochard
                http://aloiscochard.blogspot.com
                http://www.twitter.com/aloiscochard
                Thanks!
                I have downloaded your sample code.It works,but exception also been thrown.
                about Ajax login and Spring security:
                I think the main problem is that XHR is different from User-Agent(FireFox IE etc ).
                Spring Security works good with standard html form login(data sent by User-Agent) ,how to make it work with Ajax login?(data sent by XHR) we need to change something.(1) use standard form login even you are going to develop a Ajax App(2)Change some class in Spring Security.
                I change AbstractProcessingFilter's successfulAuthentication method like this :
                PHP Code:
                protected void successfulAuthentication(HttpServletRequest requestHttpServletResponse responseAuthentication authResultthrows IOExceptionServletException {
                        if (
                logger.isDebugEnabled()) {
                            
                logger.debug("Authentication success: " authResult.toString());
                        }
                        
                SecurityContextHolder.getContext().setAuthentication(authResult);
                        if (
                logger.isDebugEnabled()) {
                            
                logger.debug("Updated SecurityContextHolder to contain the following Authentication: '" authResult "'");
                        }
                        if (
                invalidateSessionOnSuccessfulAuthentication) {
                            
                SessionUtils.startNewSessionIfRequired(requestmigrateInvalidatedSessionAttributessessionRegistry);
                        }
                        
                String targetUrl determineTargetUrl(request);
                        if (
                logger.isDebugEnabled()) {
                            
                logger.debug("Redirecting to target URL from HTTP Session (or default): " targetUrl);
                        }
                        
                onSuccessfulAuthentication(requestresponseauthResult);
                        
                rememberMeServices.loginSuccess(requestresponseauthResult);
                        if (
                this.eventPublisher != null) {
                            
                eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResultthis.getClass()));
                        }
                        
                response.getWriter().print("{success:true, targetUrl : \'" determineTargetUrlrequest ) + "\'}");
                    } 
                let client code to redirect, do not use serverside redirect any more.

                -------------------------
                Sorry for My poor English

                Comment


                • #9
                  additional words:
                  If you try to send any data beforen response.sendRedirect();
                  you will get exception

                  Comment


                  • #10
                    Ok, I have this working as well. But I have one problem. I do not want to redirect after authentication. I just want to return to my client. This happens when there is an error. However, when successful, it insists on redirecting and so the response is a page. I just want to return my json object.

                    How do I prohibit the redirect?

                    Comment


                    • #11
                      Originally posted by javastick View Post
                      Ok, I have this working as well. But I have one problem. I do not want to redirect after authentication. I just want to return to my client. This happens when there is an error. However, when successful, it insists on redirecting and so the response is a page. I just want to return my json object.

                      How do I prohibit the redirect?
                      change AbstractProcessingFilter by removing redirect code
                      and add your code to send json then use it as the customer-filter "AuthencicationProcessingFilter" you also need to implement few abstract method of AbstractProcessingFilter .
                      I said client redirect not means you really need to do a real redirect in client code, you can do anything, load another module for example
                      give me your Email ,I can send a eclipse project if you need

                      Comment


                      • #12
                        Originally posted by CrazyGG View Post
                        change AbstractProcessingFilter by removing redirect code
                        and add your code to send json then use it as the customer-filter "AuthencicationProcessingFilter" you also need to implement few abstract method of AbstractProcessingFilter .
                        I said client redirect not means you really need to do a real redirect in client code, you can do anything, load another module for example
                        give me your Email ,I can send a eclipse project if you need
                        I implemented that exactly the same way, but I needed to create some more class because of the new structure of spring security 3.0 (not really difficult, but took time to understand spring security 3.0 changes).

                        Don't hesitate to ask for code too, I can post a sample project on my blog. But remember I made it for spring security 3.0.

                        Regards,

                        Alois Cochard
                        http://aloiscochard.blogspot.com
                        http://www.twitter.com/aloiscochard
                        Last edited by alois.cochard; Mar 29th, 2010, 08:11 AM.

                        Comment


                        • #13
                          Originally posted by alois.cochard View Post
                          I implemented that exactly the same way, but I needed to create some more class because of the new structure of spring security 3.0 (not really difficult, but took time to understand spring security 3.0 changes).

                          Don't hesitate to ask for code too, I can post a sample project on my blog. But remember I made it for spring security 3.0.

                          Regards,

                          Alois Cochard
                          http://aloiscochard.blogspot.com
                          http://www.twitter.com/aloiscochard
                          as a Chinese,I cant visit both of blogspot and twitter !!

                          Comment


                          • #14
                            I can compress and archive the content of my blog and send you by e-mail if wanted. Let me know using private message.

                            I heard of some software used to spoof ip-address and enable users from china to access blogspot, have you tried ?

                            See you,

                            Alois Cochard
                            http://aloiscochard.blogspot.com
                            http://www.twitter.com/aloiscochard

                            Comment


                            • #15
                              I think I basically want to archive something similar: An AJAX-JSON login which either returns 200 OK or 403 Forbidden. Following your Thread, I thunk I have to write my own filter, too? Or can I write a spring web-mvc method to handle authentication? (With @Requestmapping("/login")) ?

                              Cheers,

                              Jan

                              Comment

                              Working...
                              X