如何在安全xml中配置BCryptPasswordEncoder

时间:2013-12-10 14:35:36

标签: java spring-security

我阅读了spring安全性的每个API和文档,但我无法找到如何在spring security bean xml中配置BCryptPasswordEncoder强度参数。

尝试做类似:BCryptPasswordEncoder(int strength);

的事情

我的security.xml:

<bean id="bCryptPasswordEncoder"
    class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />


<security:authentication-manager>
    <security:authentication-provider
        user-service-ref="userDetailsServiceImpl">
        <security:password-encoder ref="bCryptPasswordEncoder" />
    </security:authentication-provider>
</security:authentication-manager>  

1 个答案:

答案 0 :(得分:1)

为此,您将在BCryptPasswordEncoder上使用Spring's constructor dependency injection

<bean id="bCryptPasswordEncoder"
    class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
    <constructor-arg value="100"/>
</bean>

<security:authentication-manager>
    <security:authentication-provider
        user-service-ref="userDetailsServiceImpl">
        <security:password-encoder ref="bCryptPasswordEncoder" />
    </security:authentication-provider>
</security:authentication-manager>

从Spring 3.1开始,您可以更加简洁using the c-namespace。例如:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:c="http://www.springframework.org/schema/c"
    xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="bCryptPasswordEncoder"
          class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"
          c:strength="100"/>

    <security:authentication-manager>
        <security:authentication-provider
            user-service-ref="userDetailsServiceImpl">
            <security:password-encoder ref="bCryptPasswordEncoder" />
        </security:authentication-provider>
    </security:authentication-manager>

</beans>

你会注意到在这个例子中

  • 有一个新的xmlns:c声明
  • bCryptPasswordEncoder中c:之后的值对应于构造函数参数名称。或者,您可以使用c:_0指定索引。

有关c命名空间的更多详细信息,请参阅上一个链接。