Spring Security AJAX登录

阅读更多
Spring Security版本:2.0.5

重写org.springframework.security.ui.webapp.AuthenticationProcessingFilter:
package com.cay.core.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.ui.webapp.AuthenticationProcessingFilter;
import org.springframework.security.util.RedirectUtils;

import com.cay.utils.RenderUtils;

public class AjaxableAuthenticationProcessingFilter extends
		AuthenticationProcessingFilter {	
	
	/**
     * If true, causes any redirection URLs to be calculated minus the protocol
     * and context path (defaults to false).
     */
    private boolean useRelativeContext = false;
	
    public void setUseRelativeContext(boolean useRelativeContext) {
        this.useRelativeContext = useRelativeContext;
    }
    
	protected void onSuccessfulAuthentication(HttpServletRequest request,
			HttpServletResponse response, Authentication authResult)
			throws IOException {
		super.onSuccessfulAuthentication(request, response, authResult);
		if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
			Map message = new HashMap();
			message.put("success", true);
			message.put("status", "1");
			RenderUtils.renderJSON(response, message);
		}
	}

	protected void onUnsuccessfulAuthentication(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException failed)
			throws IOException {
		super.onUnsuccessfulAuthentication(request, response, failed);
		if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
			Map message = new HashMap();
			message.put("success", true);
			message.put("status", "-1");
			message.put("message", failed.getMessage());
			RenderUtils.renderJSON(response, message);
		}
	}
	
	protected void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url)
            throws IOException {
		// ignore redirect when request via ajax
		if (!"XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
			RedirectUtils.sendRedirect(request, response, url, useRelativeContext);
		}
    }
}


applicationContext-security.xml如下:


	
	
		
			
		
					
			
		
		
		
		
		
		
		
        
        
        
        
        
	
	
	
		
	
	
	
		
		
		
		
	
	
	
	
	
		
	
  
	
		
	
	 




参考链接:
http://forum.springsource.org/showthread.php?56167-Overriding-AUTHENTICATION_PROCESSING_FILTER
http://forum.springsource.org/showthread.php?57373-How-to-replace-form-login
http://loianegroner.com/2010/02/integrating-spring-security-with-extjs-login-page/
http://stackoverflow.com/questions/4885893/how-to-differentiate-ajax-requests-from-normal-http-requests
http://androider.iteye.com/blog/588379

你可能感兴趣的:(Spring Security AJAX登录)