Spring3.x Security 简单应用

Security 配置文件:

<?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-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
	<!-- 不需要权限控制的资源 -->
	<http pattern="/favicon.ico" security="none" />
	......
	<!-- 404页面 -->
	<http pattern="/404.html" security="none" />
	<!-- 过滤器链 -->
	<http auto-config="true" access-decision-manager-ref="accessDecisionManager"
		disable-url-rewriting="true" request-matcher="ant">

		<intercept-url pattern="/**" access="IS_AUTHENTICATED_REMEMBERED" />

		<!-- 登录控制 -->
		<form-login login-page="/login/login.do"
			login-processing-url="/doLogin.do"
			authentication-success-handler-ref="loginSuccessHandler"
			authentication-failure-handler-ref="loginFailureHandler" />

		<!-- 退出链接 -->
		<logout logout-url="/logout.do" />

		<!-- 控制同时只能有一个相同的用户登录 -->
		<session-management invalid-session-url="/login/login.do">
			<concurrency-control max-sessions="1"
				error-if-maximum-exceeded="false" expired-url="/login/login.do" />
		</session-management>

		<!-- 记住我 -->
		<remember-me services-ref="rememberMeServices" key="rocks"
			use-secure-cookie="false" authentication-success-handler-ref="rememberMeSuccessHandler" />

		<!-- 自定义Filter -->
		<custom-filter ref="urlAuthenticationFilter" after="LAST" />

	</http>

	<!-- 自定义Filter实现 -->
	<beans:bean id="urlAuthenticationFilter" class="com.xxx.security.UrlAuthenticationFilter" />
	<!-- 登录成功处理 -->
	<beans:bean id="loginSuccessHandler" class="com.xxx.security.LoginSuccessHandler" />
	<!-- 登录失败处理 -->
	<beans:bean id="loginFailureHandler" class="com.xxx.security.LoginFailureHandler" />
	<!-- 通过记住我登录成功处理 -->
	<beans:bean id="rememberMeSuccessHandler" class="com.xxx.security.RememberMeSuccessHandler" />
	<!-- 密码加密方式 -->
	<beans:bean id="passwordEncoder"
		class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" />
	<!-- 权限控制 -->
	<authentication-manager alias="authenticationManager"
		erase-credentials="false">
		<authentication-provider user-service-ref="customerDetailsBiz">
			<password-encoder ref="passwordEncoder">
			</password-encoder>
		</authentication-provider>
	</authentication-manager>
	<!-- 记住我登录流程 -->
	<beans:bean id="rememberMeServices" class="com.xxx.customer.biz.CustomerRememberMeBiz">
		<beans:property name="userDetailsService" ref="customerDetailsBiz" />
		<beans:property name="key" value="rocks" />
	</beans:bean>
	<!-- Spring UserDetailsService接口实现类 主要是从数据库查找准备登录的用户 -->
	<beans:bean id="customerDetailsBiz" class="com.xxx.customer.biz.CustomerDetailsBiz" />
	<!-- 投票器 -->
	<beans:bean id="accessDecisionManager"
		class="org.springframework.security.access.vote.AffirmativeBased">
		<beans:property name="allowIfAllAbstainDecisions"
			value="false" />
		<beans:property name="decisionVoters">
			<beans:list>
				<beans:bean
					class="org.springframework.security.access.vote.AuthenticatedVoter" />
			</beans:list>
		</beans:property>
	</beans:bean>

</beans:beans>

 登录成功处理:

LoginSuccessHandler 

package com.xxx.security;

/**
 * 用户登录成功后处理
 * 
 * @author Theodore
 * 
 */
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
	private static final Log log = LogFactory.getLog(LoginSuccessHandler.class);

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication auth)
			throws IOException, ServletException {
		log.debug("...LoginSuccessHandler@onAuthenticationSuccess...");

		// 登录日志之类
		
	}

	/**
	 * 获取客户端IP
	 * 
	 * @param request
	 * @return
	 */
	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		log.debug("ip:::" + ip);
		return ip;
	}
}

 登录失败处理:

loginFailureHandler

package com.xxx.security;

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

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

/**
 * 登录失败逻辑处理
 * 
 * @author Theodore
 * 
 */
public class LoginFailureHandler implements AuthenticationFailureHandler {
	// private static final Log log =
	// LogFactory.getLog(LoginFailureHandler.class);

	@Override
	public void onAuthenticationFailure(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException exception)
			throws IOException, ServletException {

		//登录失败处理,例如向客户端输出失败信息

	}

}

 记住我:

RememberMeSuccessHandler

package com.xxx.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * 用户登录成功后处理
 * 
 * @author Theodore
 * 
 */
public class RememberMeSuccessHandler implements AuthenticationSuccessHandler {
	private static final Log log = LogFactory
			.getLog(RememberMeSuccessHandler.class);

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication auth)
			throws IOException, ServletException {
		log.debug("...RememberMeSuccessHandler@onAuthenticationSuccess...");

		// 登录日志
		
	}

	
	/**
	 * 获取客户端IP
	 * 
	 * @param request
	 * @return
	 */
	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}

 CustomerDetailsBiz

import java.util.List;


/**
 * 查找指定用户

 * @author Theodore
 * 
 */
public class CustomerDetailsBiz extends BaseBiz<Customer, CustomerDao>
		implements UserDetailsService {
	private static final Log log = LogFactory.getLog(CustomerDetailsBiz.class);

	@Resource
	private CustomerBiz xxxBiz;

	/**
	 * 
	 * <p>
	 * 根据后台用户名查找用户并加载用户的详细信息
	 * </p>
	 * 
	 * @param
	 * @return UserDetails
	 * @throws
	 */
	@Override
	public UserDetails loadUserByUsername(String userId)
			throws UsernameNotFoundException {

		Customer customer =  xxxBiz.getCustomer(userId);
		
		if (customer != null) {
			//如果该用户可以登录

		} else {
                        //如果没有找到该用户,需要创建一个空对象
			customer = new Customer();
		}

		return customer;
	}

}

 

你可能感兴趣的:(Security)