我阅读了Spring Security的所有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>

最佳答案

为此,您可以在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-命名空间的更多详细信息,请参见上一个链接。

10-07 18:15