Spring Security的filter配置及说明

以前在PA关注过用户登录授权的过程,看过JAAS的规范,看过WEBLOGIC的实现代码,看过Spring Security的源代码,这么久都忘了。。现在开始,把以前丢掉的技术日记能记得记下来,以后也开始写日记了~~:)

 

----

 

验证

使用 opendsldap 数据库,(运行的脚本在该目录的 ldap.ldif 下)

上下文参数:

http://localhost:389

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: 如果配置了targetBeantargetClass, 优先调用targetHean. 推荐使用targetHean 的方式。

通过调用FilterToBeanProxyinit ()方法启动过滤器链工作。

( 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) {

 

// 启动代理 filterinit 方法

     this.delegate.init(this.filterConfig);

     }

  }

 

 

/WEB-INF/applicationContextsecurity.xml

配置 beanfilterChainProxy

<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 》给该参数配置过滤器链。

3org.springframework.security.util.FilterChainProxy

/** 表示要过该链的urlall

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 也相同,调用每个 filterdestroy

 

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());

}

}

 

下面依次是过滤器链中的过滤器。

 

配置 beanhttpSessionContextIntegrationFilter

集成过滤器 P49, 如名字所示,将httpSessionsecurityContext 中的认证信息同步。

       <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);

     }

}

}

 

 

 

配置 beanauthenticationProcessingFilter

* 认证处理过滤器 。

       <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>

 

 

 

配置 beanexceptionTranslationFilter

异常处理器:处理认证和授权过程中的异常

       <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) 构造验证入口。

-->

 

 

 

配置 beanfilterInvocationInterceptor

过滤安全拦截器:处理认证和授权过程中的异常

 

       <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>

 

 

    <! 下一个beaninitialDirContextFactory )有错,主要原因是包的依赖关系有问题,待解决。 -->

       

    <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>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值