Spring Security 3 自定义过滤器后,不能控制同一用户的多次登录

最近在项目里面加入Spring Security做安全控制,参照网上的资料实现了用户、角色、权限从数据库中读取。最后出现一个问题:在将session交给Spring Security管理时,不能避免同一用户的多次登录。而我在之前在XML中定义用户和角色的时候,可以控制成功。请教一下大家是什么原因?

     以下是我的各个文件的代码片段:


     web.xml

Xml代码 复制代码
  1. <listener>  
  2.     <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>  
  3. </listener>  
  4. <!--  
  5.     项目中使用SpringSecurity的过滤器-->  
  6.   
  7. <filter>  
  8.     <filter-name>springSecurityFilterChain</filter-name>  
  9.     <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
  10. </filter>  
  11. <filter-mapping>  
  12.     <filter-name>springSecurityFilterChain</filter-name>  
  13.     <url-pattern>/*</url-pattern>  
  14. </filter-mapping>  

    applicationContext-Security.xml

 

Xml代码 复制代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:sec="http://www.springframework.org/schema/security"  
  5.     xsi:schemaLocation="     
  6.         http://www.springframework.org/schema/beans    
  7.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd     
  8.         http://www.springframework.org/schema/context    
  9.         http://www.springframework.org/schema/context/spring-context-3.0.xsd     
  10.         http://www.springframework.org/schema/security    
  11.         http://www.springframework.org/schema/security/spring-security-3.0.xsd">  
  12.     <sec:http auto-config="true">  
  13.         <!-- 登录页无须过滤 -->  
  14.         <sec:intercept-url pattern="/login.jsp" filters="none" />  
  15.         <!-- 资源的访问权限 已转为数据库存储 -->  
  16.         <!--   
  17.             <sec:intercept-url pattern="/secure/**" access="ROLE_ADMIN" />  
  18.             <sec:intercept-url pattern="/userManager/**" access="ROLE_ADMIN" />  
  19.         -->  
  20.         <sec:form-login login-page="/login.jsp"  
  21.             authentication-failure-url="/login.jsp?error=true"  
  22.             default-target-url="/login/LoginAction_loginSuccess.action"  
  23.             authentication-success-handler-ref="successHandler"  
  24.             authentication-failure-handler-ref="failureHandler"  
  25.             always-use-default-target="false" />  
  26.         <!--尝试访问没有权限的页面时跳转的页面 -->  
  27.         <sec:access-denied-handler error-page="/accessDenied.jsp" />  
  28.         <sec:http-basic />  
  29.         <!--注销用户-->  
  30.         <sec:logout invalidate-session="true"  
  31.             logout-success-url="/login/LoginAction_loginOut.action" logout-url="/j_spring_security_logout" />  
  32.         <sec:remember-me />  
  33.         <!-- 增加一个自定义的过滤器完成对URL资源的保护控制 。-->  
  34.         <sec:custom-filter before="FILTER_SECURITY_INTERCEPTOR"  
  35.             ref="resourceSecurityInterceptor" />  
  36.         <!-- 用户登录Session控制-->  
  37.         <sec:session-management invalid-session-url="/login.jsp"  
  38.             session-authentication-error-url="/login.jsp?error=true">  
  39.             <sec:concurrency-control max-sessions="1"  
  40.                 error-if-maximum-exceeded="true" expired-url="/login.jsp" />  
  41.         </sec:session-management>  
  42.     </sec:http>  
  43.     <!--认证成功-->  
  44.     <bean id="successHandler"  
  45.         class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">  
  46.         <property name="defaultTargetUrl" value="/login/LoginAction_loginSuccess.action" />  
  47.         <property name="alwaysUseDefaultTargetUrl" value="false" />  
  48.     </bean>  
  49.     <!-- 认证失败 -->  
  50.     <bean id="failureHandler"  
  51.         class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">  
  52.         <property name="defaultFailureUrl" value="/login/LoginAction_loginFailure.action" />  
  53.     </bean>  
  54.     <bean id="resourceSecurityInterceptor"  
  55.         class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">  
  56.         <!-- 认证管理器,实现用户认证的入口 -->  
  57.         <property name="authenticationManager" ref="authenticationManager" />  
  58.         <!-- 访问决策器,决定某个用户具有的角色,是否有足够的权限去访问某个资源 -->  
  59.         <property name="accessDecisionManager" ref="accessDecisionManager" />  
  60.         <!-- 资源源数据定义,即定义某一资源可以被哪些角色访问 -->  
  61.         <property name="securityMetadataSource"  
  62.             ref="secureResourceFilterInvocationDefinitionSource" />  
  63.         <!--<property name="observeOncePerRequest" value="false" />    -->  
  64.     </bean>  
  65.     <!-- 认证管理器 -->  
  66.     <sec:authentication-manager alias="authenticationManager">  
  67.         <!-- 认证管理器提供者  【user-service-ref】引用的服务组件,通过securityManager进行对用户信息的认证-->  
  68.         <sec:authentication-provider  
  69.             user-service-ref="userDetailsService">  
  70.             <!-- 密码采用md5加密方式加密 -->  
  71.             <sec:password-encoder base64="false" ref="passwordEncoder">  
  72.                 <!-- 用username做盐值加密,防止md5字典攻击 -->  
  73.                 <sec:salt-source user-property="username" />  
  74.             </sec:password-encoder>  
  75.         </sec:authentication-provider>  
  76.     </sec:authentication-manager>  
  77.     <!-- 访问决策器,决定某个用户具有的角色,是否有足够的权限去访问某个资源 -->  
  78.     <bean id="accessDecisionManager"  
  79.         class="org.springframework.security.access.vote.AffirmativeBased">  
  80.         <property name="allowIfAllAbstainDecisions" value="false" />  
  81.         <property name="decisionVoters">  
  82.             <list>  
  83.                 <bean class="org.springframework.security.access.vote.RoleVoter" />  
  84.                 <bean class="org.springframework.security.access.vote.AuthenticatedVoter" />  
  85.             </list>  
  86.         </property>  
  87.     </bean>  
  88.     <!-- 资源源数据定义,即定义某一资源可以被哪些角色访问 -->  
  89.     <bean id="secureResourceFilterInvocationDefinitionSource"  
  90.         class="com.sshframework.generic.security.filter.UserDefindInvocationSecurityMetadataSource">  
  91.         <!-- 实例化需要的参数 -->  
  92.         <constructor-arg>  
  93.             <ref bean="roleDAOImpl" />  
  94.         </constructor-arg>  
  95.         <constructor-arg>  
  96.             <ref bean="userDAOImpl" />  
  97.         </constructor-arg>  
  98.         <constructor-arg>  
  99.             <ref bean="resourceDAOImpl" />  
  100.         </constructor-arg>  
  101.         <!-- URL匹配器UrlMatcher需要的参数 -->  
  102.         <!--   
  103.             useAntPath 是否使用Apache Ant的匹配模式,即资源/userManager/**   
  104.             和/userManager/UserManager_list.action匹配   
  105.         -->  
  106.         <property name="useAntPath">  
  107.             <value>true</value>  
  108.         </property>  
  109.         <!--   
  110.             lowercaseComparisons 是否在比较URL前将URL都转化成小写,即资源/userManager/**   
  111.             和/UserManager/××匹配   
  112.         -->  
  113.         <property name="lowercaseComparisons">  
  114.             <value>true</value>  
  115.         </property>  
  116.     </bean>  
  117.   
  118.     <!-- 用户信息服务 -->  
  119.     <bean id="userDetailsService"  
  120.         class="com.sshframework.generic.security.service.UserDetailsServiceImpl">  
  121.         <property name="userDAO" ref="userDAOImpl" />  
  122.     </bean>  
  123.     <!-- 密码加密 -->  
  124.     <bean id="passwordEncoder"  
  125.         class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" />  
  126. </beans>  

 

    自定义的资源访问类

    UserDefindInvocationSecurityMetadataSource.java

 

Java代码 复制代码
  1. import java.util.ArrayList;   
  2. import java.util.Collection;   
  3. import java.util.HashMap;   
  4. import java.util.Iterator;   
  5. import java.util.List;   
  6. import java.util.Map;   
  7. import java.util.Set;   
  8.   
  9. import org.springframework.beans.factory.InitializingBean;   
  10. import org.springframework.security.access.ConfigAttribute;   
  11. import org.springframework.security.access.SecurityConfig;   
  12. import org.springframework.security.web.FilterInvocation;   
  13. import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;   
  14. import org.springframework.security.web.util.AntUrlPathMatcher;   
  15. import org.springframework.security.web.util.RegexUrlPathMatcher;   
  16. import org.springframework.security.web.util.UrlMatcher;   
  17.   
  18. import com.devtek.dao.IResourceDAO;   
  19. import com.devtek.dao.IRoleDAO;   
  20. import com.devtek.dao.IUserDAO;   
  21. import com.devtek.pojo.Resource;   
  22. import com.devtek.pojo.Role;   
  23. import com.devtek.pojo.RoleResource;   
  24. import com.sshframework.generic.util.LoggerHandle;   
  25.   
  26. /**  
  27.  * 此类在初始化时,应该取到所有资源及其对应角色的定义  
  28.  */  
  29. public class UserDefindInvocationSecurityMetadataSource implements  
  30.         FilterInvocationSecurityMetadataSource, InitializingBean {   
  31.   
  32.     private IUserDAO userDAO;   
  33.     private IRoleDAO roleDAO;   
  34.     private IResourceDAO resourceDAO;   
  35.   
  36.     private UrlMatcher urlMatcher;   
  37.     private boolean useAntPath = true;   
  38.     private boolean lowercaseComparisons = true;   
  39.   
  40.     private static Map<String, Collection<ConfigAttribute>> resourceMap = null;   
  41.   
  42.     public UserDefindInvocationSecurityMetadataSource(IUserDAO userDAO,   
  43.             IRoleDAO roleDAO, IResourceDAO resourceDAO) {   
  44.         super();   
  45.         this.userDAO = userDAO;   
  46.         this.roleDAO = roleDAO;   
  47.         this.resourceDAO = resourceDAO;   
  48.         loadResourceDefine();   
  49.     }   
  50.   
  51.     public void afterPropertiesSet() throws Exception {   
  52.         this.urlMatcher = new RegexUrlPathMatcher();   
  53.         if (useAntPath) {   
  54.             this.urlMatcher = new AntUrlPathMatcher();   
  55.         }   
  56.         if ("true".equals(lowercaseComparisons)) {   
  57.             if (!this.useAntPath) {   
  58.                 ((RegexUrlPathMatcher) this.urlMatcher)   
  59.                         .setRequiresLowerCaseUrl(true);   
  60.             }   
  61.         } else if ("false".equals(lowercaseComparisons)) {   
  62.             if (this.useAntPath) {   
  63.                 ((AntUrlPathMatcher) this.urlMatcher)   
  64.                         .setRequiresLowerCaseUrl(false);   
  65.             }   
  66.         }   
  67.     }   
  68.   
  69.     // 得到某个资源能访问的角色   
  70.     private void loadResourceDefine() {   
  71.         resourceMap = new HashMap<String, Collection<ConfigAttribute>>();   
  72.   
  73.         List<Resource> resourceList = this.resourceDAO.getAllResource();   
  74.         for (Resource resource : resourceList) {   
  75.             Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();   
  76.   
  77.             String resourceStr = resource.getValue();   
  78.   
  79.             Set<RoleResource> roleResourceSet = resource.getRoleResources();   
  80.             for (RoleResource roleResource : roleResourceSet) {   
  81.                 Role role = roleResource.getRole();   
  82.                 ConfigAttribute ca = new SecurityConfig(role.getRoleName());   
  83.                 atts.add(ca);   
  84.             }   
  85.             resourceMap.put(resourceStr, atts);   
  86.         }   
  87.   
  88.         LoggerHandle.log(this.getClass(), LoggerHandle.LOGGER_LEVEL_INFO,   
  89.                 "开始加载系统权限"null);   
  90.         StringBuffer strConfig = new StringBuffer();   
  91.         Iterator<String> ite = resourceMap.keySet().iterator();   
  92.         while (ite.hasNext()) {   
  93.             String resURL = ite.next();   
  94.             strConfig.append("{资源访问路径URL : [" + resURL + "]");   
  95.             strConfig.append(" , 所需要的角色权限 : ");   
  96.             Collection<ConfigAttribute> attss = resourceMap.get(resURL);   
  97.             for (ConfigAttribute cg : attss) {   
  98.                 strConfig.append("[" + cg.toString() + "]");   
  99.             }   
  100.             strConfig.append(" } ");   
  101.             LoggerHandle.log(this.getClass(), LoggerHandle.LOGGER_LEVEL_INFO,   
  102.                     strConfig.toString(), null);   
  103.             strConfig = new StringBuffer();   
  104.         }   
  105.         LoggerHandle.log(this.getClass(), LoggerHandle.LOGGER_LEVEL_INFO,   
  106.                 "加载系统权限完毕"null);   
  107.     }   
  108.   
  109.     public Collection<ConfigAttribute> getAttributes(Object filter)   
  110.             throws IllegalArgumentException {   
  111.         FilterInvocation filterInvocation = (FilterInvocation) filter;   
  112.         String requestURI = filterInvocation.getRequestUrl();   
  113.   
  114.         Iterator<String> ite = resourceMap.keySet().iterator();   
  115.         while (ite.hasNext()) {   
  116.             String resURL = ite.next();   
  117.   
  118.             // 比较资源定义中的URL和当前请求的URL   
  119.             // resURL 资源定义中的URL   
  120.             // requestURL 当前请求的URL   
  121.             if (urlMatcher.pathMatchesUrl(resURL, requestURI)) {   
  122.   
  123.                 Collection<ConfigAttribute> atts = resourceMap.get(resURL);   
  124.                 String colRole = "";   
  125.                 for (ConfigAttribute cg : atts) {   
  126.                     // System.out.println(cg.toString());   
  127.                     colRole = colRole + "," + cg.toString();   
  128.                 }   
  129.                 if (colRole.length() > 1) {   
  130.                     colRole = colRole.substring(1);   
  131.                 }   
  132.   
  133.                 LoggerHandle.log(this.getClass(),   
  134.                         LoggerHandle.LOGGER_LEVEL_INFO, "{用户请求资源URL :"  
  135.                                 + requestURI + " ,所需要的系统角色权限为:[" + colRole   
  136.                                 + "]}"null);   
  137.                 return atts;   
  138.             }   
  139.         }   
  140.   
  141.         return null;   
  142.     }   
  143.   
  144.     public boolean supports(Class<?> clazz) {   
  145.         return true;   
  146.     }   
  147.   
  148.     public Collection<ConfigAttribute> getAllConfigAttributes() {   
  149.         return new ArrayList<ConfigAttribute>();   
  150.     }   
  151.   
  152.     /**  
  153.      * @return the useAntPath  
  154.      */  
  155.     public boolean isUseAntPath() {   
  156.         return useAntPath;   
  157.     }   
  158.   
  159.     /**  
  160.      * @param useAntPath  
  161.      *            the useAntPath to set  
  162.      */  
  163.     public void setUseAntPath(boolean useAntPath) {   
  164.         this.useAntPath = useAntPath;   
  165.     }   
  166.   
  167.     /**  
  168.      * @return the lowercaseComparisons  
  169.      */  
  170.     public boolean isLowercaseComparisons() {   
  171.         return lowercaseComparisons;   
  172.     }   
  173.   
  174.     /**  
  175.      * @param lowercaseComparisons  
  176.      *            the lowercaseComparisons to set  
  177.      */  
  178.     public void setLowercaseComparisons(boolean lowercaseComparisons) {   
  179.         this.lowercaseComparisons = lowercaseComparisons;   
  180.     }   
  181. }  
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.AntUrlPathMatcher;
import org.springframework.security.web.util.RegexUrlPathMatcher;
import org.springframework.security.web.util.UrlMatcher;

import com.devtek.dao.IResourceDAO;
import com.devtek.dao.IRoleDAO;
import com.devtek.dao.IUserDAO;
import com.devtek.pojo.Resource;
import com.devtek.pojo.Role;
import com.devtek.pojo.RoleResource;
import com.sshframework.generic.util.LoggerHandle;

/**
 * 此类在初始化时,应该取到所有资源及其对应角色的定义
 */
public class UserDefindInvocationSecurityMetadataSource implements
		FilterInvocationSecurityMetadataSource, InitializingBean {

	private IUserDAO userDAO;
	private IRoleDAO roleDAO;
	private IResourceDAO resourceDAO;

	private UrlMatcher urlMatcher;
	private boolean useAntPath = true;
	private boolean lowercaseComparisons = true;

	private static Map<String, Collection<ConfigAttribute>> resourceMap = null;

	public UserDefindInvocationSecurityMetadataSource(IUserDAO userDAO,
			IRoleDAO roleDAO, IResourceDAO resourceDAO) {
		super();
		this.userDAO = userDAO;
		this.roleDAO = roleDAO;
		this.resourceDAO = resourceDAO;
		loadResourceDefine();
	}

	public void afterPropertiesSet() throws Exception {
		this.urlMatcher = new RegexUrlPathMatcher();
		if (useAntPath) {
			this.urlMatcher = new AntUrlPathMatcher();
		}
		if ("true".equals(lowercaseComparisons)) {
			if (!this.useAntPath) {
				((RegexUrlPathMatcher) this.urlMatcher)
						.setRequiresLowerCaseUrl(true);
			}
		} else if ("false".equals(lowercaseComparisons)) {
			if (this.useAntPath) {
				((AntUrlPathMatcher) this.urlMatcher)
						.setRequiresLowerCaseUrl(false);
			}
		}
	}

	// 得到某个资源能访问的角色
	private void loadResourceDefine() {
		resourceMap = new HashMap<String, Collection<ConfigAttribute>>();

		List<Resource> resourceList = this.resourceDAO.getAllResource();
		for (Resource resource : resourceList) {
			Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();

			String resourceStr = resource.getValue();

			Set<RoleResource> roleResourceSet = resource.getRoleResources();
			for (RoleResource roleResource : roleResourceSet) {
				Role role = roleResource.getRole();
				ConfigAttribute ca = new SecurityConfig(role.getRoleName());
				atts.add(ca);
			}
			resourceMap.put(resourceStr, atts);
		}

		LoggerHandle.log(this.getClass(), LoggerHandle.LOGGER_LEVEL_INFO,
				"开始加载系统权限", null);
		StringBuffer strConfig = new StringBuffer();
		Iterator<String> ite = resourceMap.keySet().iterator();
		while (ite.hasNext()) {
			String resURL = ite.next();
			strConfig.append("{资源访问路径URL : [" + resURL + "]");
			strConfig.append(" , 所需要的角色权限 : ");
			Collection<ConfigAttribute> attss = resourceMap.get(resURL);
			for (ConfigAttribute cg : attss) {
				strConfig.append("[" + cg.toString() + "]");
			}
			strConfig.append(" } ");
			LoggerHandle.log(this.getClass(), LoggerHandle.LOGGER_LEVEL_INFO,
					strConfig.toString(), null);
			strConfig = new StringBuffer();
		}
		LoggerHandle.log(this.getClass(), LoggerHandle.LOGGER_LEVEL_INFO,
				"加载系统权限完毕", null);
	}

	public Collection<ConfigAttribute> getAttributes(Object filter)
			throws IllegalArgumentException {
		FilterInvocation filterInvocation = (FilterInvocation) filter;
		String requestURI = filterInvocation.getRequestUrl();

		Iterator<String> ite = resourceMap.keySet().iterator();
		while (ite.hasNext()) {
			String resURL = ite.next();

			// 比较资源定义中的URL和当前请求的URL
			// resURL 资源定义中的URL
			// requestURL 当前请求的URL
			if (urlMatcher.pathMatchesUrl(resURL, requestURI)) {

				Collection<ConfigAttribute> atts = resourceMap.get(resURL);
				String colRole = "";
				for (ConfigAttribute cg : atts) {
					// System.out.println(cg.toString());
					colRole = colRole + "," + cg.toString();
				}
				if (colRole.length() > 1) {
					colRole = colRole.substring(1);
				}

				LoggerHandle.log(this.getClass(),
						LoggerHandle.LOGGER_LEVEL_INFO, "{用户请求资源URL :"
								+ requestURI + " ,所需要的系统角色权限为:[" + colRole
								+ "]}", null);
				return atts;
			}
		}

		return null;
	}

	public boolean supports(Class<?> clazz) {
		return true;
	}

	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return new ArrayList<ConfigAttribute>();
	}

	/**
	 * @return the useAntPath
	 */
	public boolean isUseAntPath() {
		return useAntPath;
	}

	/**
	 * @param useAntPath
	 *            the useAntPath to set
	 */
	public void setUseAntPath(boolean useAntPath) {
		this.useAntPath = useAntPath;
	}

	/**
	 * @return the lowercaseComparisons
	 */
	public boolean isLowercaseComparisons() {
		return lowercaseComparisons;
	}

	/**
	 * @param lowercaseComparisons
	 *            the lowercaseComparisons to set
	 */
	public void setLowercaseComparisons(boolean lowercaseComparisons) {
		this.lowercaseComparisons = lowercaseComparisons;
	}
}

 

   用户信息访问服务类

   UserDetailsServiceImpl.java

 

Java代码 复制代码
  1. import java.util.Collection;   
  2. import java.util.ArrayList;   
  3. import java.util.Set;   
  4.   
  5. import org.springframework.dao.DataAccessException;   
  6. import org.springframework.security.core.GrantedAuthority;   
  7. import org.springframework.security.core.authority.GrantedAuthorityImpl;   
  8. import org.springframework.security.core.userdetails.UserDetails;   
  9. import org.springframework.security.core.userdetails.UserDetailsService;   
  10. import org.springframework.security.core.userdetails.UsernameNotFoundException;   
  11.   
  12. import com.devtek.dao.IUserDAO;   
  13. import com.devtek.pojo.Role;   
  14. import com.devtek.pojo.User;   
  15. import com.devtek.pojo.UserRole;   
  16.   
  17. /**  
  18.  * 实现SpringSecurity的UserDetailsService接口,实现获取用户信息UserDetails.  
  19.  *   
  20.  */  
  21. public class UserDetailsServiceImpl implements UserDetailsService {   
  22.   
  23.     private IUserDAO userDAO;   
  24.   
  25.     public UserDetails loadUserByUsername(String userName)   
  26.             throws UsernameNotFoundException, DataAccessException {   
  27.   
  28.         User user = this.userDAO.getUserByUserName(userName);   
  29.   
  30.         return user;   
  31.     }   
  32.     public IUserDAO getUserDAO() {   
  33.         return userDAO;   
  34.     }   
  35.     public void setUserDAO(IUserDAO userDAO) {   
  36.         this.userDAO = userDAO;   
  37.     }   
  38.   
  39. }  
import java.util.Collection;
import java.util.ArrayList;
import java.util.Set;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.devtek.dao.IUserDAO;
import com.devtek.pojo.Role;
import com.devtek.pojo.User;
import com.devtek.pojo.UserRole;

/**
 * 实现SpringSecurity的UserDetailsService接口,实现获取用户信息UserDetails.
 * 
 */
public class UserDetailsServiceImpl implements UserDetailsService {

	private IUserDAO userDAO;

	public UserDetails loadUserByUsername(String userName)
			throws UsernameNotFoundException, DataAccessException {

		User user = this.userDAO.getUserByUserName(userName);

		return user;
	}
	public IUserDAO getUserDAO() {
		return userDAO;
	}
	public void setUserDAO(IUserDAO userDAO) {
		this.userDAO = userDAO;
	}

}

 

    用户信息类,实现了UserDetails 接口

    User.java

 

 

Java代码 复制代码
  1. import java.util.ArrayList;   
  2. import java.util.Collection;   
  3. import java.util.HashSet;   
  4. import java.util.Set;   
  5.   
  6. import org.springframework.security.core.GrantedAuthority;   
  7. import org.springframework.security.core.authority.GrantedAuthorityImpl;   
  8. import org.springframework.security.core.userdetails.UserDetails;   
  9.   
  10. public class User implements java.io.Serializable, UserDetails {   
  11.   
  12.     // Fields   
  13.     private String userId;   
  14.     private String userName;   
  15.     private String passWord;   
  16.     private String sex;   
  17.     private Integer status;   
  18.     private String descn;   
  19.     private Set userRoles = new HashSet(0);   
  20.   
  21.     // Constructors   
  22.   
  23.     public User() {   
  24.     }   
  25.     public User(String userId) {   
  26.         this.userId = userId;   
  27.     }   
  28.     public User(String userId, String userName, String passWord, String sex,   
  29.             Integer status, String descn, Set userRoles) {   
  30.         this.userId = userId;   
  31.         this.userName = userName;   
  32.         this.passWord = passWord;   
  33.         this.sex = sex;   
  34.         this.status = status;   
  35.         this.descn = descn;   
  36.         this.userRoles = userRoles;   
  37.     }   
  38.   
  39.     // Property accessors   
  40.     set() get()方法略.........   
  41.   
  42.     // 扩展UserDetails需要实现的方法---------------------------------------------------------//   
  43.     public Collection<GrantedAuthority> getAuthorities() {   
  44.         // TODO Auto-generated method stub   
  45.         Collection<GrantedAuthority> authCol = new ArrayList<GrantedAuthority>();   
  46.   
  47.         Set<UserRole> userRoleSet = this.getUserRoles();   
  48.         for (UserRole ur : userRoleSet) {   
  49.             Role role = ur.getRole();   
  50.             authCol.add(new GrantedAuthorityImpl(role.getRoleName()));   
  51.         }   
  52.         return authCol;   
  53.     }   
  54.   
  55.     public String getPassword() {   
  56.         return this.passWord;   
  57.     }   
  58.     public String getUsername() {   
  59.         return this.userName;   
  60.     }   
  61.     public boolean isAccountNonExpired() {   
  62.         return true;   
  63.     }   
  64.     public boolean isAccountNonLocked() {   
  65.         return true;   
  66.     }   
  67.     public boolean isCredentialsNonExpired() {   
  68.         return true;   
  69.     }   
  70.     public boolean isEnabled() {   
  71.         return true;   
  72.     }   
  73.     // 扩展UserDetails需要实现的方法---------------------------------------------------------//   
  74. }  
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;

public class User implements java.io.Serializable, UserDetails {

	// Fields
	private String userId;
	private String userName;
	private String passWord;
	private String sex;
	private Integer status;
	private String descn;
	private Set userRoles = new HashSet(0);

	// Constructors

	public User() {
	}
	public User(String userId) {
		this.userId = userId;
	}
	public User(String userId, String userName, String passWord, String sex,
			Integer status, String descn, Set userRoles) {
		this.userId = userId;
		this.userName = userName;
		this.passWord = passWord;
		this.sex = sex;
		this.status = status;
		this.descn = descn;
		this.userRoles = userRoles;
	}

	// Property accessors
	set() get()方法略.........

	// 扩展UserDetails需要实现的方法---------------------------------------------------------//
	public Collection<GrantedAuthority> getAuthorities() {
		// TODO Auto-generated method stub
		Collection<GrantedAuthority> authCol = new ArrayList<GrantedAuthority>();

		Set<UserRole> userRoleSet = this.getUserRoles();
		for (UserRole ur : userRoleSet) {
			Role role = ur.getRole();
			authCol.add(new GrantedAuthorityImpl(role.getRoleName()));
		}
		return authCol;
	}

	public String getPassword() {
		return this.passWord;
	}
	public String getUsername() {
		return this.userName;
	}
	public boolean isAccountNonExpired() {
		return true;
	}
	public boolean isAccountNonLocked() {
		return true;
	}
	public boolean isCredentialsNonExpired() {
		return true;
	}
	public boolean isEnabled() {
		return true;
	}
	// 扩展UserDetails需要实现的方法---------------------------------------------------------//
}

 

   其他pojo类省略(Role.java    UserRole.java    Resource.java    RoleResource.java)

 

  

    问题:现在能实现访问/userManager/UserManager_listUser.aciton 时跳转到login.jsp,输入用户名密码正常经/login/LoginAction_loginSuccess.action 再转到UserManager_listUser.aciton。但是多浏览器测试时,不能控制同一用户只允许登录一次。即代码中部门配置的session管理不起作用。困扰很久了。。。望各位指教!

    PS:我的环境 Struts2+Hibernate3+Spring3 ,Spring Security 是3.0.5版本。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值