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<String, Object> message = new HashMap<String, Object>();
			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<String, Object> message = new HashMap<String, Object>();
			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如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd">
	
	<http entry-point-ref="authenticationProcessingFilterEntryPoint">
		
		<intercept-url pattern="/pages/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>	
		<intercept-url pattern="/css/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
		<intercept-url pattern="/images/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>			
		<intercept-url pattern="/new/commons/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>	
		<intercept-url pattern="/new/core/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
		<intercept-url pattern="/new/extjs/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
		<intercept-url pattern="/favicon.ico" access="ROLE_ANONYMOUS" />
		<intercept-url pattern="/**" access="ROLE_AUTHENTICATED" />
		
		<!-- 定制AuthenticationProcessingFilter不能使用form-login标签与auto-config="true" -->
		<!-- 同时必须使用logout、http-basic与anonymous标签 -->
        <logout logout-success-url="/pages/login.jsp" />
        <http-basic />
        <anonymous />
        
        <!--  
        <form-login login-page="/pages/login.jsp"
                    authentication-failure-url="/pages/login.jsp?error=true"
                    default-target-url="/index.do" />
		-->
	</http>
	
	<authentication-provider user-service-ref="userDetailsService">
		<password-encoder hash="md5" />
	</authentication-provider>
	
	<beans:bean id="authenticationProcessingFilter"
		class="com.cay.core.web.AjaxableAuthenticationProcessingFilter">
		<custom-filter position="AUTHENTICATION_PROCESSING_FILTER" />
		<beans:property name="defaultTargetUrl" value="/index.do" />
		<beans:property name="authenticationFailureUrl" value="/pages/login.jsp?error=true"/>
		<beans:property name="authenticationManager" ref="authenticationManager" />
	</beans:bean>
	
	<authentication-manager alias="authenticationManager"/>
	
	<beans:bean id="authenticationProcessingFilterEntryPoint"
		class="com.cay.core.web.handler.AjaxableAuthenticationProcessingFilterEntryPoint">
		<beans:property name="loginFormUrl" value="/pages/login.jsp" />
	</beans:bean>
  
	<beans:bean id="messageSource"
		class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
		<beans:property name="basename"
			value="classpath:com/cay/security/messages" />
	</beans:bean>
	<beans:bean id="localeResolver"
		class="org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver" /> 

</beans:beans>


参考链接:
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)