`
bookong
  • 浏览: 95376 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

浅谈Spring Security-Ldap认证配置

阅读更多
最近在项目中使用公司的LDAP做身份认证,积累了一些经验,与大家分享一下。

首选报告一下我们项目的概况,我们的项目是用java开发的,基于 spring 的web应用。主要相关软件或库的版本为:

java:1.6,maven:3.0.4,tomcat:7,spring framework:3.2.2.RELEASE,spring security:3.1.3.RELEASE

我的想法是这样的,当用户第一次登录系统时无需注册,只要输入LDAP绑定公司的域账户和密码就完成身份认证动作,然后会自动将用户信息(从LDAP中查询的用户中文名、邮箱等)插入数据库中,并且赋予用户一个默认的角色。然后加载用户所属角色的权限,通过 spring security 结合用户所有的权限对用户访问的资源进行控制。

首先,要在 pom.xml 中设置下面的 dependencies 来集成 LDAP 相关操作。

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-ldap</artifactId>
            <version>${springsecurity-version}</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>


在 web.xml 中做如下配置:

    <!-- Enables Spring Security -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class> 
            org.springframework.web.filter.DelegatingFilterProxy 
        </filter-class>
    </filter>

    <filter-mapping>
      <filter-name>springSecurityFilterChain</filter-name>
      <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    </filter-mapping>


DelegatingFilterProxy做的事情是代理Filter的方法,从application context里获得bean。 这让bean可以获得spring web application context的生命周期支持,使配置较为轻便。

下面我要配置 applicationContext-security.xml 文件,所有 spring security 相关的配置都应该写在这里。详细配置的意义可以参考 xml schema 文件:http://www.springframework.org/schema/security/spring-security-3.1.xsd

有些目录我们希望不限制访问的权限,比如 css、images、js等。

    <s:http pattern="/css/**" security="none"/>
    <s:http pattern="/images/**" security="none"/>
    <s:http pattern="/js/**" security="none"/>


上面的配置和以前的 <s:intercept-url pattern='/css/**' filters='none'/> 作用是一样的,但从 spring security 3 开始不再支持上面的写法——这是很多开源项目让人无语的地方——不在意兼容性。

其中 ** 代表可以跨越目录。

下面这一部分配置是对 http 的过滤:

<s:http 
        auto-config="true" 
        use-expressions="true" 
        entry-point-ref="accessDeniedHandler" >
    <s:intercept-url pattern="/service/**" access="hasAnyRole('USER')" />
    <s:intercept-url pattern="/home/**" access="hasAnyRole('USER')" />

    <s:access-denied-handler ref="accessDeniedHandler"/>
    <s:form-login 
        login-page="/login"
        default-target-url="/home" 
        authentication-failure-url="/login_fail" />
    <s:logout logout-success-url="/login" />
    <s:custom-filter ref="afterLoginFilter" after="FORM_LOGIN_FILTER" />
</s:http>


上面 <s:intercept-url …… /> 匹配过滤的路径。hasAnyRole 用于匹配一个使用GrantedAuthority 的角色列表(这里说的角色是 spring security 里的概念,不是我们定义的业务上的角色)。用户匹配其中的任何一个均可放行。

entry-point-ref 为用户第一次访问受保护的url时的处理程序。这个程序需要实现 AuthenticationEntryPoint 接口。我们可以在这里让没登录的用户跳转到登录页面去。

access-denied-handler是在拒绝用户访问(用户没有访问权限)的时候处理的程序。这个程序需要实现 AccessDeniedHandler 接口。我们可以在这里让用户跳转到 403 页面去。

form-login 这部分是登录控制

<s:custom-filter ref="afterLoginFilter" …… /> 这部分定义了一个 filter ,在 FORM_LOGIN_FILTER 之后。加这个的原因是这样的。我希望在登录后能将一些内容放在 session 中,但使用 LDAP 的 authentication provider 时无法在我自己实现的 authoritiesPopulator(这个后面会说到)中得到 session 。我觉得一种方法可能是用自己定义的 UserDetails 代替 spring security 中的实现,但由于时间关系没有太研究,如果哪位看官有经验可以一起讨论。另一种方法就是我现在这样,在登录后拦截一下,然后从 SecurityContextHolder.getContext().getAuthentication().getName() 中把用户输入的登录名拿出来,再到数据库捞出我想要的信息,放在了 session  里。

下面说说我们主要的内容 LDAP 进行身份认证部分:

首选我们指定 authentication-manager 为一个 LDAP 的 authentication provider。

    <bean id="ldapAuthProvider"
        class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider" >
        ……
    </bean>
        ……
    <s:authentication-manager>
        <s:authentication-provider ref="ldapAuthProvider">
        </s:authentication-provider>
    </s:authentication-manager>


这个 LdapAuthenticationProvider 有两个构造参数:

  • LdapAuthenticator authenticator:这是一个验证器,验证绑定策略
  • LdapAuthoritiesPopulator authoritiesPopulator:这个是在用户通过验证后,得到权限。这个眼熟吧?就是上面我说的在这里我没法得到 session 。


现在我们再看 ldapAuthProvider 的完整配置:

<bean id="ldapAuthProvider"
    class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider" >
    <constructor-arg>
        <bean id="authenticator"
            class="org.springframework.security.ldap.authentication.BindAuthenticator">
            <constructor-arg ref="contextSource" />
            <property name="userSearch">
                <bean
                    class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch">
                    <constructor-arg value="" />
                    <constructor-arg value="${security.ldap.searchFilter}" />
                    <constructor-arg ref="contextSource" />
                </bean>
            </property>
        </bean>
    </constructor-arg>
    <constructor-arg>
        <bean id="authoritiesPopulator"
            class="net.bookong.ldapsample.security.LdapAuthoritiesPopulatorImpl">
        </bean>
    </constructor-arg>
</bean>


在我们指定 authenticator 构造参数时,我们指定了一个 BindAuthenticator 对象,并将一个 contextSource 指定给了它,这个 contextSource 的定义如下:
    <bean id="contextSource"
        class="org.springframework.security.ldap.DefaultSpringSecurityContextSource" >
        <constructor-arg value="${security.ldap.providerUrl}" /> 
        <property name="userDn" value="${security.ldap.userDn}" />  
        <property name="password" value="${security.ldap.password}" />
    </bean>


这里定义了 LDAP 的一些属性。userDn 和 password 是一个域账户的用户名和密码,我们公司配置的 LDAP 必须要指定一个有特殊权限的用户来操作才可以。

${security.ldap.searchFilter} 是配置文件中配置的 LDAP 查询用户的过滤器内容,像我们公司的 LDAP服务器,登录是检查 mailNickname 来作为用户名的,所以我们在配置文件中如下配置:{0} 会替换成登录用户输入的用户名。

security.ldap.searchFilter=(mailNickname={0})


在我们指定 ldapAuthProvider 的第二个构造参数 authoritiesPopulator 时,我们配置的是自己实现的类 LdapAuthoritiesPopulatorImpl,这个类首选检查数据库里有没有记录,如果没有,就用LDAP里的信息初始化数据库。然后从数据库加载权限并添加到要作为函数返回值的Collection 中去。

这里需要注意的是,如果我们希望拿到 LDAP 里的信息,不需要自己再写程序连接 LDAP服务器,因为传入的参数 DirContextOperations userData 已经将能读到的 LDAP 信息都带过来了。比如你想要用户的中文姓名,那么可以这样:

userData.getAttributes().get("displayName").get().toString()

当然,上面说的 displayName 是我们公司 LDAP 里记录中文姓名的属性。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics