`
lilin530
  • 浏览: 88041 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Spring Security 3 证书登录

阅读更多

默认情况下ss3的<x509>标签只会取证书主题作为验证条件,如果想要自己指定证书的某一部分作为验证条件需要手动实现X509PrincipalExtractor接口:

Java代码 复制代码 收藏代码
  1. import org.springframework.security.web.authentication.preauth.x509.X509PrincipalExtractor;   
  2.   
  3. public class MyX509PrincipalExtractor implements X509PrincipalExtractor{   
  4.   
  5.     Logger logger = LoggerFactory.getLogger(this.getClass());   
  6.        
  7.     /**  
  8.      * 获取证书序列号  
  9.      * @param cert x509证书对象  
  10.      */  
  11.     @Override  
  12.     public Object extractPrincipal(X509Certificate cert) {   
  13.         String serialNumber = cert.getSerialNumber().toString(16);//取证书序列号作为判断条件   
  14.         return serialNumber;   
  15.     }   
  16.   
  17. }  
import org.springframework.security.web.authentication.preauth.x509.X509PrincipalExtractor;

public class MyX509PrincipalExtractor implements X509PrincipalExtractor{

	Logger logger = LoggerFactory.getLogger(this.getClass());
	
	/**
	 * 获取证书序列号
	 * @param cert x509证书对象
	 */
	@Override
	public Object extractPrincipal(X509Certificate cert) {
		String serialNumber = cert.getSerialNumber().toString(16);//取证书序列号作为判断条件
		return serialNumber;
	}

}

 实现用户描述接口:

Java代码 复制代码 收藏代码
  1. public class MyUserAuthority implements UserDetails{   
  2. ……   
  3. }  
public class MyUserAuthority implements UserDetails{
……
}

 

载入用户信息:

Java代码 复制代码 收藏代码
  1. import org.slf4j.Logger;   
  2. import org.slf4j.LoggerFactory;   
  3. import org.springframework.beans.factory.annotation.Autowired;   
  4. import org.springframework.security.core.Authentication;   
  5. import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;   
  6. import org.springframework.security.core.userdetails.UserDetails;   
  7. import org.springframework.security.core.userdetails.UsernameNotFoundException;   
  8.   
  9. /**  
  10.  *   
  11.  * Company: xxx公司 <br>  
  12.  *  
  13.  * Description:  用户信息载入服务  
  14.  *  
  15.  * <br>Copyright: Copyright (c) 2010 - 2015  
  16.  *  
  17.  * <br>Author: JLCON   
  18.  * <br>Created:2010-9-17  
  19.  *  
  20.  * <br>Modified:2010-9-17  
  21.  *  
  22.  * <br>version:V1.0  
  23.  */  
  24. public class MyUserDetailService implements AuthenticationUserDetailsService{   
  25.   
  26.     Logger logger = LoggerFactory.getLogger(this.getClass());   
  27.        
  28.   
  29.     //载入用户信息   
  30.     @Autowired  
  31.     private UserAuthorityInfo userinfo;   
  32.        
  33.   
  34.     /**  
  35.      * 用户信息载入  
  36.      * @param token 认证token  
  37.      */  
  38.     @Override  
  39.     public UserDetails loadUserDetails(Authentication token)   
  40.             throws UsernameNotFoundException {//这里得到的就是刚才返回的证书ID   
  41.         return userinfo.getUserDetails(token.getPrincipal().toString());   
  42.     }   
  43.   
  44. }  
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * 
 * Company: xxx公司 <br>
 *
 * Description:  用户信息载入服务
 *
 * <br>Copyright: Copyright (c) 2010 - 2015
 *
 * <br>Author: JLCON 
 * <br>Created:2010-9-17
 *
 * <br>Modified:2010-9-17
 *
 * <br>version:V1.0
 */
public class MyUserDetailService implements AuthenticationUserDetailsService{

	Logger logger = LoggerFactory.getLogger(this.getClass());
	

    //载入用户信息
	@Autowired
	private UserAuthorityInfo userinfo;
	

	/**
	 * 用户信息载入
	 * @param token 认证token
	 */
	@Override
	public UserDetails loadUserDetails(Authentication token)
			throws UsernameNotFoundException {//这里得到的就是刚才返回的证书ID
		return userinfo.getUserDetails(token.getPrincipal().toString());
	}

}

 通过URL获取该URL具有的访问属性:

Java代码 复制代码 收藏代码
  1. public class X509securityMetadataSource implements FilterInvocationSecurityMetadataSource{   
  2.   
  3. import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;   
  4. …………   
  5.   
  6.     @Override  
  7.     public Collection<ConfigAttribute> getAttributes(Object object)   
  8.             throws IllegalArgumentException {   
  9.         String url = ((FilterInvocation)object).getRequestUrl();   
  10.   
  11.         ………………   
  12.   
  13.         return list;   
  14.     }   
  15.   
  16.     @Override  
  17.     public boolean supports(Class<?> clazz) {   
  18.         return true;   
  19.     }   
  20.   
  21. }  
public class X509securityMetadataSource implements FilterInvocationSecurityMetadataSource{

import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
…………

	@Override
	public Collection<ConfigAttribute> getAttributes(Object object)
			throws IllegalArgumentException {
		String url = ((FilterInvocation)object).getRequestUrl();

		………………

		return list;
	}

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

}

 认证访问控制器:

Java代码 复制代码 收藏代码
  1. public class X509AccessDecisionManager implements AccessDecisionManager{   
  2.   
  3.     Logger logger = LoggerFactory.getLogger(this.getClass());   
  4.        
  5.     /**  
  6.      * 决定是否有权限访问资源  
  7.      * @param authentication 登录用户权限信息  
  8.      * @param object 访问的资源对象  
  9.      * @param configAttributes 资源对象具有的配置属性  
  10.      * @exception AccessDeniedException 访问被拒绝  
  11.      */  
  12.     @Override  
  13.     public void decide(Authentication authentication, Object object,   
  14.             Collection<ConfigAttribute> configAttributes)   
  15.             throws AccessDeniedException, InsufficientAuthenticationException {   
  16.         FilterInvocation filterInvocation = (FilterInvocation)object;   
  17.         for(ConfigAttribute configAttribute:configAttributes)   
  18.         {   
  19.             for(GrantedAuthority grantedAuthority:authentication.getAuthorities())   
  20.             {   
  21.                 if(configAttribute.getAttribute().equalsIgnoreCase(grantedAuthority.getAuthority()))   
  22.                 {   
  23.                     logger.debug("访问success! - {}",filterInvocation.getFullRequestUrl());   
  24.                     return;   
  25.                 }   
  26.             }   
  27.         }   
  28.         logger.debug("无权访问! - {}",filterInvocation.getFullRequestUrl());   
  29.   
  30.         throw new AccessDeniedException("无权限!");   
  31.     }   
  32.   
  33.     @Override  
  34.     public boolean supports(ConfigAttribute attribute) {   
  35.         return true;   
  36.     }   
  37.   
  38.     @Override  
  39.     public boolean supports(Class<?> clazz) {   
  40.         return true;   
  41.     }   
  42.   
  43. }  
public class X509AccessDecisionManager implements AccessDecisionManager{

	Logger logger = LoggerFactory.getLogger(this.getClass());
	
	/**
	 * 决定是否有权限访问资源
	 * @param authentication 登录用户权限信息
	 * @param object 访问的资源对象
	 * @param configAttributes 资源对象具有的配置属性
	 * @exception AccessDeniedException 访问被拒绝
	 */
	@Override
	public void decide(Authentication authentication, Object object,
			Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
		FilterInvocation filterInvocation = (FilterInvocation)object;
		for(ConfigAttribute configAttribute:configAttributes)
		{
			for(GrantedAuthority grantedAuthority:authentication.getAuthorities())
			{
				if(configAttribute.getAttribute().equalsIgnoreCase(grantedAuthority.getAuthority()))
				{
					logger.debug("访问success! - {}",filterInvocation.getFullRequestUrl());
					return;
				}
			}
		}
		logger.debug("无权访问! - {}",filterInvocation.getFullRequestUrl());

		throw new AccessDeniedException("无权限!");
	}

	@Override
	public boolean supports(ConfigAttribute attribute) {
		return true;
	}

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

}

  最后上配置:

Xml代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <b:beans xmlns:b="http://www.springframework.org/schema/beans"  
  3.     xmlns="http://www.springframework.org/schema/security"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
  6.     http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">  
  7.   
  8.     <http access-denied-page="/accessdenied.jsp">  
  9.         <custom-filter position="X509_FILTER" ref="x509Filter"/>  
  10.         <custom-filter ref="x509Intercepter" before="FILTER_SECURITY_INTERCEPTOR"/>  
  11.         <intercept-url pattern="/*" requires-channel="https"/>  
  12.         <port-mappings>  
  13.             <port-mapping http="8080" https="8443"/>  
  14.         </port-mappings>  
  15.         <form-login/>  
  16.     </http>  
  17.        
  18.     <b:bean id="preAuthenticatedProcessingFilterEntryPoint" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedProcessingFilterEntryPoint">  
  19.     </b:bean>  
  20.        
  21.     <b:bean id="x509Filter" class="org.springframework.security.web.authentication.preauth.x509.X509AuthenticationFilter">  
  22.         <b:property name="authenticationManager" ref="authenticationmanager"></b:property>  
  23.         <b:property name="principalExtractor">  
  24.             <b:bean class=".....MyX509PrincipalExtractor"></b:bean>  
  25.         </b:property>  
  26.     </b:bean>  
  27.        
  28.     <b:bean id="x509Intercepter" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">  
  29.         <b:property name="authenticationManager" ref="authenticationmanager"></b:property>  
  30.         <b:property name="securityMetadataSource" ref="x509securityMetadataSource"></b:property>  
  31.         <b:property name="accessDecisionManager" ref="x509AccessDecisionManager"></b:property>  
  32.     </b:bean>  
  33.        
  34.     <b:bean id="x509securityMetadataSource" class="....X509securityMetadataSource"></b:bean>  
  35.     <b:bean id="x509AccessDecisionManager" class="....X509AccessDecisionManager"></b:bean>  
  36.        
  37.     <authentication-manager alias="authenticationmanager" >  
  38.         <authentication-provider ref="x509provider">  
  39.         </authentication-provider>  
  40.     </authentication-manager>  
  41.        
  42.     <b:bean id="x509provider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">  
  43.         <b:property name="preAuthenticatedUserDetailsService" ref="UserDetailsService">  
  44.         </b:property>  
  45.         <b:property name="throwExceptionWhenTokenRejected" value="true"></b:property>  
  46.     </b:bean>  
  47.        
  48.     <b:bean id="loggerListener" class="org.springframework.security.authentication.event.LoggerListener"/>  
  49.        
  50.     <b:bean id="UserDetailsService" class="....MyUserDetailService"></b:bean>  
  51.        
  52.     <b:bean id="UserAuthorityInfo" class="....UserAuthorityInfoImp"></b:bean>  
  53.        
  54. </b:beans>  
<?xml version="1.0" encoding="UTF-8"?>
<b:beans xmlns:b="http://www.springframework.org/schema/beans"
    xmlns="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/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">

	<http access-denied-page="/accessdenied.jsp">
		<custom-filter position="X509_FILTER" ref="x509Filter"/>
		<custom-filter ref="x509Intercepter" before="FILTER_SECURITY_INTERCEPTOR"/>
		<intercept-url pattern="/*" requires-channel="https"/>
		<port-mappings>
			<port-mapping http="8080" https="8443"/>
		</port-mappings>
		<form-login/>
	</http>
	
	<b:bean id="preAuthenticatedProcessingFilterEntryPoint" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedProcessingFilterEntryPoint">
	</b:bean>
	
	<b:bean id="x509Filter" class="org.springframework.security.web.authentication.preauth.x509.X509AuthenticationFilter">
		<b:property name="authenticationManager" ref="authenticationmanager"></b:property>
		<b:property name="principalExtractor">
			<b:bean class=".....MyX509PrincipalExtractor"></b:bean>
		</b:property>
	</b:bean>
	
	<b:bean id="x509Intercepter" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
		<b:property name="authenticationManager" ref="authenticationmanager"></b:property>
		<b:property name="securityMetadataSource" ref="x509securityMetadataSource"></b:property>
		<b:property name="accessDecisionManager" ref="x509AccessDecisionManager"></b:property>
	</b:bean>
	
	<b:bean id="x509securityMetadataSource" class="....X509securityMetadataSource"></b:bean>
	<b:bean id="x509AccessDecisionManager" class="....X509AccessDecisionManager"></b:bean>
	
	<authentication-manager alias="authenticationmanager" >
		<authentication-provider ref="x509provider">
		</authentication-provider>
	</authentication-manager>
	
	<b:bean id="x509provider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
		<b:property name="preAuthenticatedUserDetailsService" ref="UserDetailsService">
		</b:property>
		<b:property name="throwExceptionWhenTokenRejected" value="true"></b:property>
	</b:bean>
	
	<b:bean id="loggerListener" class="org.springframework.security.authentication.event.LoggerListener"/>
	
	<b:bean id="UserDetailsService" class="....MyUserDetailService"></b:bean>
	
	<b:bean id="UserAuthorityInfo" class="....UserAuthorityInfoImp"></b:bean>
	
</b:beans>

 web.xml

Xml代码 复制代码 收藏代码
  1. 。。。。。   
  2. <filter>  
  3.         <filter-name>springSecurityFilterChain</filter-name>  
  4.         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
  5.     </filter>  
  6.   
  7.     <filter-mapping>  
  8.       <filter-name>springSecurityFilterChain</filter-name>  
  9.       <url-pattern>/manager/*</url-pattern>  
  10.     </filter-mapping>  
  11.   
  12. 。。。。。  
分享到:
评论
1 楼 wise_wei 2012-10-15  
收_藏_了,请问一下:
//载入用户信息 
    @Autowired 
    private UserAuthorityInfo userinfo;
这个 UserAuthorityInfo类是什么?

相关推荐

Global site tag (gtag.js) - Google Analytics