Page 1 of 2 12 LastLast
Results 1 to 10 of 17

Thread: Spring Security 3 and Ajax type login

  1. #1
    Join Date
    Nov 2009
    Posts
    16

    Default 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 at 06:34 AM. Reason: Added code tags

  2. #2
    Luke Taylor is offline Senior Member Acegi Security System TeamSpring Team
    Join Date
    Aug 2004
    Location
    Glasgow, Scotland
    Posts
    3,449

    Default

    What requests are sent from the browser and what is the corresponding debug output?
    Spring - by Pivotal
    twitter @tekul

  3. #3
    Join Date
    Nov 2009
    Posts
    16

    Default

    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.

  4. #4
    Luke Taylor is offline Senior Member Acegi Security System TeamSpring Team
    Join Date
    Aug 2004
    Location
    Glasgow, Scotland
    Posts
    3,449

    Default

    What is the corresponding debug log output?
    Spring - by Pivotal
    twitter @tekul

  5. #5

    Question

    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

  6. #6
    Join Date
    Nov 2009
    Posts
    16

    Default

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

  7. #7
    Join Date
    Nov 2009
    Posts
    16

    Default

    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.

  8. #8
    Join Date
    Mar 2010
    Posts
    7

    Default

    Quote 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

  9. #9
    Join Date
    Mar 2010
    Posts
    7

    Default

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

  10. #10
    Join Date
    Nov 2009
    Posts
    16

    Default

    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?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •