转自:http://zhuoyaopingzi.iteye.com/blog/1219364
以前在PA关注过用户登录授权的过程,看过JAAS的规范,看过WEBLOGIC的实现代码,看过Spring Security的源代码,这么久都忘了。。现在开始,把以前丢掉的技术日记能记得记下来,以后也开始写日记了~~:)
----
验证
使用opends作ldap数据库,(运行的脚本在该目录的ldap.ldif下)
上下文参数:
o=company.com.cn
cn=orcladmin
pwd: hhxxttxs
创建ou用的opends的图形工具创建,groups下面的条目用ldif导入创建的,ldif如下:
dn:cn=staffRole,ou=groups,o= company.com.cn objectClass:groupOfUniqueNames cn:staffRole uniquemember:uid=zhuoyueping790,ou=staff,ou=people,o= company.com.cn
dn:cn=clientRole,ou=groups,o= company.com.cn objectClass:groupOfUniqueNames cn:clientRole uniquemember:uid=chenshengli532,ou=client,ou=people,o= company.com.cn |
有staffRole角色的用户可以访问/staff.*资源;
有clientRole角色的用户可以访问/client.*资源
例子中所有密码均为:hhxxttxs
所有标有页数的地方为《敏捷Acegi、CAS——构建安全的java系统》的页码。
红色表示待解决的问题,蓝色表示有特别说明或者代码解释的语句。
该项目的全部文件(包括jar包,在该目录下的ss目录中)
斜体bena的名字表示即将要解释的调用的bean.
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Contacts Sample Application</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContextsecurity.xml</param-value> </context-param> <!-- /WEB-INF/applicationContext*.xml 加了*,报错listener--> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener《1》 </listener-class> </listener> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class> org.springframework.security.util.FilterToBeanProxy《2》 </filter-class> <init-param> <param-name>targetBean</param-name> <param-value>filterChainProxy</param-value> </init-param> </filter>
<filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
<filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/j_spring_security_check</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list>
</web-app> |
《1》:org.springframework.web.context.ContextLoaderListener
(该类在spring-web.jar包中,)
《2》:org.springframework.util.FilterToBeanProxy:如果配置了targetBean和targetClass,优先调用targetHean.推荐使用targetHean的方式。
通过调用FilterToBeanProxy的init()方法启动过滤器链工作。
(org.springframework.security.*的类都在spring-security-core.jar包中,)
public class FilterToBeanProxy implements Filter{ public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; String strategy = filterConfig.getInitParameter("init"); if ((strategy != null) && (strategy.toLowerCase().equals("lazy"))) { return; } doInit(); } } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(this.initialized)) { doInit(); } }
private synchronized void doInit() throws ServletException { //… String targetBean = this.filterConfig.getInitParameter("targetBean"); //关于lifecircle部分,先放在这里以后补充 String lifecycle = this.filterConfig.getInitParameter("lifecycle"); if ("servlet-container-managed".equals(lifecycle)) { this.servletContainerManaged = true; } ApplicationContext ctx = getContext(this.filterConfig); String beanName = null;
if ((targetBean != null) && (ctx.containsBean(targetBean))) { beanName = targetBean; } else { Class targetClass; if (targetBean != null) { throw new ServletException("targetBean '" + targetBean + "' not found in context"); } String targetClassString = this.filterConfig.getInitParameter("targetClass"); //… targetClass= Thread.currentThread().getContextClassLoader().loadClass(targetClassString); //.. this.initialized = true; //得到代理类,代理类必须是filter类,调用代理类的init() Object object = ctx.getBean(beanName); if (!(object instanceof Filter)) { throw new ServletException("Bean '" + beanName + "' does not implement javax.servlet.Filter"); } this.delegate = ((Filter)object); if (this.servletContainerManaged) {
//启动代理filter的init方法 this.delegate.init(this.filterConfig); } }
|
/WEB-INF/applicationContextsecurity.xml:
配置bean:filterChainProxy
<bean id="filterChainProxy" class="org.springframework.security.util.FilterChainProxy">《3》 <property name="filterInvocationDefinitionSource">《4》 <value> PATTERN_TYPE_APACHE_ANT /**=httpSessionContextIntegrationFilter,authenticationProcessingFilter,exceptionTranslationFilter,filterInvocationInterceptor </value> </property> </bean> |
《4》给该参数配置过滤器链。
《3》org.springframework.security.util.FilterChainProxy
/**表示要过该链的url为all
public class FilterChainProxy implements Filter, InitializingBean, ApplicationContextAware{ public void init(FilterConfig filterConfig) throws ServletException { Filter[] filters = obtainAllDefinedFilters(); for (int i = 0; i < filters.length; ++i) filters[i].init(filterConfig);//依次调用每个filter的过滤器链 } } } //destroy也相同,调用每个filter的destroy
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { FilterInvocation fi = new FilterInvocation(request, response, chain); List filters = getFilters(fi.getRequestUrl()); if ((filters == null) || (filters.size() == 0)) { chain.doFilter(request, response); return; } virtualFilterChain virtualFilterChain = new VirtualFilterChain(fi, filters, null); virtualFilterChain.doFilter(fi.getRequest(), fi.getResponse()); } } |
下面依次是过滤器链中的过滤器。
配置bean:httpSessionContextIntegrationFilter
集成过滤器,P49,如名字所示,将httpSession与securityContext中的认证信息同步。
<bean id="httpSessionContextIntegrationFilter" class="org.springframework.security.context.HttpSessionContextIntegrationFilter">《5》 <property name="allowSessionCreation" value="false" />《6》 </bean> |
《5》HttpSessionContextIntegrationFilter继承SpringSecurityFilter,SpringSecurityFilter实现了接口filter,在SpringSecurityFilter【附1】的doFilter方法中调用了doFilterHttp,子类在doFilterHttp中实现自己的逻辑,该过滤器应该放在所有过滤器之前。
《6》allowSessionCreation 是否创建HTTP session。
public class HttpSessionContextIntegrationFilter extends SpringSecurityFilter implements InitializingBean{ public void doFilterHttp(HttpServletRequest request, HttpServletResponse response, FilterChain chain){ public void doFilterHttp(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { //进入该过滤器器,从session中取认证相关信息,放在SecurityContext中。 SecurityContext contextBeforeChainExecution = readSecurityContextFromSession(httpSession); SecurityContextHolder.setContext(contextBeforeChainExecution); //继续执行过滤器链,因此,该过滤器应该放在所有过滤器之前! chain.doFilter(request, responseWrapper);
//… //在finally中执行,退出出这个过滤器(也是该过滤器链执行完后)前执行。 //在contextAfterChainExecution存最新的SecurityContext SecurityContext contextAfterChainExecution = SecurityContextHolder.getContext();
SecurityContextHolder.clearContext();//清除当前线程中的SecurityContext相关信息。 request.removeAttribute("__spring_security_session_integration_filter_applied"); //将contextAfterChainExecution 修改过的securitycontext放在HTTP session对象中 if (!(responseWrapper.isSessionUpdateDone())) { storeSecurityContextInSession(contextAfterChainExecution, request, httpSessionExistedAtStartOfRequest, contextHashBeforeChainExecution); } } }
|
配置bean:authenticationProcessingFilter
*认证处理过滤器。
<bean id="authenticationProcessingFilter" class="org.springframework.security.ui.webapp.AuthenticationProcessingFilter"> <property name="authenticationManager"> <ref bean="authenticationManager" /> </property> <property name="authenticationFailureUrl"> <value>/login.jsp?login_error=1</value> </property> <property name="defaultTargetUrl"> <value>/</value> </property> <property name="filterProcessesUrl"> <value>/j_spring_security_check</value> </property> </bean> <!—org.springframework.security.ui.webapp.AuthenticationProcessingFilter: 表示用表单认证的类; authenticationFailureUrl:认证失败跳转的url。 defaultTargetUrl:认证完成后,跳转回之前请求的页面,如果没有,到该url filterProcessesUrl:提交验证请求的form标签中action的地址 authenticationManager:处理得到的用户名和密码交给谁验证的问题 -->
<bean id="authenticationManager" class="org.springframework.security.providers.ProviderManager">p50 <property name="providers"> <list> <ref local="ldapAuthenticationProvider" /> </list> </property> </bean>
<!— providers:可以指定多个provider 的bean。 -->
<bean id="ldapAuthenticationProvider" class="org.springframework.security.providers.ldap.LdapAuthenticationProvider"> <constructor-arg ref="bindAuthenticator" /> <constructor-arg ref="defaultLdapAuthoritiesPopulator" /> </bean> <!— org.springframework.security.providers.ldap.LdapAuthenticationProvider: 指定该bean是去ldap认证。 <constructor-arg ref="bindAuthenticator" />:在ldap中哪里找用户 <constructor-arg ref="defaultLdapAuthoritiesPopulator" />:用什么来查,在哪里查角色 --> <!--采用绑定的方式认证 --> <bean id="bindAuthenticator" class="org.springframework.security.providers.ldap.authenticator.BindAuthenticator"> <constructor-arg ref="initialDirContextFactory" /> <property name="userDnPatterns"> <list> <value>uid={0},ou=users</value> </list> </property> <property name="userDetailsMapper" ref="ldapUserDetailsMapper"> </property> </bean> <!—initialDirContextFactory有错,主要原因是包的依赖关系有问题,待解决。 -->
<bean id="initialDirContextFactory" class="org.springframework.security.ldap.DefaultInitialDirContextFactory"> <constructor-arg value="ldap://localhost:389/o= company.com.cn" /> <property name="managerDn" value="cn=orcladmin,o= company.com.cn" /> <property name="managerPassword" value="hhxxttxs" /> <property name="useConnectionPool" value="true" /> <property name="authenticationType" value="simple" /> <property name="initialContextFactory" value="com.sun.jndi.ldap.LdapCtxFactory" /> </bean> <bean id="ldapUserDetailsMapper" class="org.springframework.security.userdetails.ldap.LdapUserDetailsMapper"> <property name="convertToUpperCase" value="true" /> <property name="passwordAttributeName" value="userPassword" /> <property name="roleAttributes">p236:将该参数的值作为role,如:ROLE_CN <list> <value>cn</value> </list> </property> <property name="rolePrefix" value="ROLE_" /> </bean> <!-- 采用密码比较的方式认证 --> <!-- <bean id="passwordComparisonAuthenticator" class="org.springframework.security.providers.ldap.authenticator.PasswordComparisonAuthenticator"> <constructor-arg ref="initialDirContextFactory" /> <property name="userDnPatterns"> <list> <value>uid={0},ou=users</value> </list> </property> <property name="passwordAttributeName" value="userPassword" /> </bean> -->
<!-- 采用密码比较的方式认证 --> <bean id="defaultLdapAuthoritiesPopulator" class="org.springframework.security.providers.ldap.populator.DefaultLdapAuthoritiesPopulator"> <constructor-arg ref="initialDirContextFactory" /> <constructor-arg value="ou=groups" /> <property name="groupSearchFilter" value="(uniquemember={0})" /> <property name="groupRoleAttribute" value="cn" /> <property name="convertToUpperCase" value="true" /> <property name="defaultRole" value="ROLE_DEFAULT" /> <property name="searchSubtree" value="true" /> <property name="rolePrefix" value="ROLE_" /> </bean>
|
配置bean:exceptionTranslationFilter
异常处理器:处理认证和授权过程中的异常
<bean id="exceptionTranslationFilter" class="org.springframework.security.ui.ExceptionTranslationFilter"> <property name="authenticationEntryPoint"> <ref local="authenticationProcessingFilterEntryPoint" /> </property> </bean> <!—exceptionTranslationFilter p173-->
<bean id="authenticationProcessingFilterEntryPoint" class="org.springframework.security.ui.webapp.AuthenticationProcessingFilterEntryPoint"> <property name="loginFormUrl"> <value>/login.jsp</value> </property> </bean> <!—AuthenticationProcessingFilterEntryPoint 继承自AuthenticationEntryPoint p17 AuthenticationEntryPoint 的commence(ServletRequest request, ServletResponse response, AuthenticationException authException) 构造验证入口。 -->
|
配置bean:filterInvocationInterceptor
过滤安全拦截器:处理认证和授权过程中的异常
<bean id="filterInvocationInterceptor" class="org.springframework.security.intercept.web.FilterSecurityInterceptor"> <property name="authenticationManager"> <ref local="authenticationManager" /> </property> <property name="accessDecisionManager"> <ref local="httpRequestAccessDecisionManager" /> </property> <property name="objectDefinitionSource"> <value> PATTERN_TYPE_APACHE_ANT /client/*=ROLE_CLIENTROLE /staff/*=ROLE_staffRole </value> </property> </bean>
<bean id="httpRequestAccessDecisionManager" class="org.springframework.security.vote.AffirmativeBased"> <property name="allowIfAllAbstainDecisions"> <value>false</value> </property> <property name="decisionVoters"> <list> <ref bean="roleVoter" /> </list> </property> </bean>
<bean id="roleVoter" class="org.springframework.security.vote.RoleVoter" /> |
附:一些类。
附1:
public abstract class SpringSecurityFilter implements Filter, Ordered { protected final Log logger; public SpringSecurityFilter() { this.logger = LogFactory.getLog(super.getClass()); } public final void init(FilterConfig filterConfig) throws ServletException { } public final void destroy() { } public final void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { throw new ServletException("Can only process HttpServletRequest"); } if (!(response instanceof HttpServletResponse)) { throw new ServletException("Can only process HttpServletResponse"); } doFilterHttp((HttpServletRequest)request, (HttpServletResponse)response, chain); } protected abstract void doFilterHttp(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse, FilterChain paramFilterChain) throws IOException, ServletException; public String toString() { return super.getClass() + "[ order=" + super.getOrder() + "; ]"; } public abstract int getOrder(); } |
/WEB-INF/applicationContextsecurity.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:jms="http://www.springframework.org/schema/jms" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 集成过滤器 --> <bean id="httpSessionContextIntegrationFilter" class="org.springframework.security.context.HttpSessionContextIntegrationFilter"> <property name="allowSessionCreation" value="false" /> </bean>
<!—下一个bean(initialDirContextFactory)有错,主要原因是包的依赖关系有问题,待解决。 -->
<bean id="initialDirContextFactory" class="org.springframework.security.ldap.DefaultInitialDirContextFactory"> <constructor-arg value="ldap://localhost:389/o= company.com.cn" /> <property name="managerDn" value="cn=orcladmin,o= company.com.cn" /> <property name="managerPassword" value="hhxxttxs" /> <property name="useConnectionPool" value="true" /> <property name="authenticationType" value="simple" /> <property name="initialContextFactory" value="com.sun.jndi.ldap.LdapCtxFactory" /> </bean>
<!--采用绑定的方式认证 --> <bean id="ldapUserDetailsMapper" class="org.springframework.security.userdetails.ldap.LdapUserDetailsMapper"> <property name="convertToUpperCase" value="true" /> <property name="passwordAttributeName" value="userPassword" /> <property name="roleAttributes"> <list> <value>cn</value> </list> </property> <property name="rolePrefix" value="ROLE_" /> </bean>
<bean id="bindAuthenticator" class="org.springframework.security.providers.ldap.authenticator.BindAuthenticator"> <constructor-arg ref="initialDirContextFactory" /> <property name="userDnPatterns"> <list> <value>uid={0},ou=users</value> </list> </property> <property name="userDetailsMapper" ref="ldapUserDetailsMapper"> </property> </bean>
<!-- 采用密码比较的方式认证 --> <!-- <bean id="passwordComparisonAuthenticator" class="org.springframework.security.providers.ldap.authenticator.PasswordComparisonAuthenticator"> <constructor-arg ref="initialDirContextFactory" /> <property name="userDnPatterns"> <list> <value>uid={0},ou=users</value> </list> </property> <property name="passwordAttributeName" value="userPassword" /> </bean> -->
<bean id="ldapAuthenticationProvider" class="org.springframework.security.providers.ldap.LdapAuthenticationProvider"> <constructor-arg ref="bindAuthenticator" /> <constructor-arg ref="defaultLdapAuthoritiesPopulator" /> </bean>
<bean id="authenticationManager" class="org.springframework.security.providers.ProviderManager"> <property name="providers"> <list> <ref local="ldapAuthenticationProvider" /> </list> </property> </bean>
<!-- 认证处理过滤器,用ldap provider来认证(绑定方式) --> <bean id="authenticationProcessingFilter" class="org.springframework.security.ui.webapp.AuthenticationProcessingFilter"> <property name="authenticationManager"> <ref bean="authenticationManager" /> </property> <property name="authenticationFailureUrl"> <value>/login.jsp?login_error=1</value> </property> <property name="defaultTargetUrl"> <value>/</value> </property> <property name="filterProcessesUrl"> <value>/j_spring_security_check</value> </property> </bean>
<!-- 授权 --> <!--验证失败后,comce方法--> <bean id="authenticationProcessingFilterEntryPoint" class="org.springframework.security.ui.webapp.AuthenticationProcessingFilterEntryPoint"> <property name="loginFormUrl"> <value>/login.jsp</value> </property> </bean>
<!-- exceptionTranslationFilter 认证和授权过程的异常处理 --> <bean id="exceptionTranslationFilter" class="org.springframework.security.ui.ExceptionTranslationFilter"> <property name="authenticationEntryPoint"> <ref local="authenticationProcessingFilterEntryPoint" /> </property> </bean>
<bean id="defaultLdapAuthoritiesPopulator" class="org.springframework.security.providers.ldap.populator.DefaultLdapAuthoritiesPopulator"> <constructor-arg ref="initialDirContextFactory" /> <constructor-arg value="ou=groups" /> <property name="groupSearchFilter" value="(uniquemember={0})" /> <property name="groupRoleAttribute" value="cn" /> <property name="convertToUpperCase" value="true" /> <property name="defaultRole" value="ROLE_DEFAULT" /> <property name="searchSubtree" value="true" /> <property name="rolePrefix" value="ROLE_" /> </bean>
<!-- 授权的策略 -->
<bean id="roleVoter" class="org.springframework.security.vote.RoleVoter" />
<bean id="httpRequestAccessDecisionManager" class="org.springframework.security.vote.AffirmativeBased"> <property name="allowIfAllAbstainDecisions"> <value>false</value> </property> <property name="decisionVoters"> <list> <ref bean="roleVoter" /> </list> </property> </bean>
<bean id="filterInvocationInterceptor" class="org.springframework.security.intercept.web.FilterSecurityInterceptor"> <property name="authenticationManager"> <ref local="authenticationManager" /> </property> <property name="accessDecisionManager"> <ref local="httpRequestAccessDecisionManager" /> </property> <property name="objectDefinitionSource"> <value> PATTERN_TYPE_APACHE_ANT /client/*=ROLE_CLIENTROLE /staff/*=ROLE_staffRole </value> </property> </bean>
<bean id="filterChainProxy" class="org.springframework.security.util.FilterChainProxy"> <property name="filterInvocationDefinitionSource"> <value> PATTERN_TYPE_APACHE_ANT /**=httpSessionContextIntegrationFilter,authenticationProcessingFilter,exceptionTranslationFilter,filterInvocationInterceptor </value> </property> </bean>
</beans> |