有配置(applicationContext-security.xml):
<authentication-manager alias="authenticationManager">
<authentication-provider>
<password-encoder hash="sha"/>
<jdbc-user-service data-source-ref="dataSource"/>
</authentication-provider>
</authentication-manager>
从另一边有来 self 的 dataSource
的 SQL(它是 JdbcDaoImpl ):
...
public static final String DEF_USERS_BY_USERNAME_QUERY =
"select username,password,enabled " +
"from users " +
"where username = ?";
...
这段代码中现在有关于 sha
的字样,因此从标准 Spring Security users
表中选择的密码未编码。
也许,我应该在我的休眠映射配置中为 password
列提供一些 sha
属性:
<class name="model.UserDetails" table="users">
<id name="id">
<generator class="increment"/>
</id>
<property name="username" column="username"/>
<property name="password" column="password"/>
<property name="enabled" column="enabled"/>
<property name="mail" column="mail"/>
<property name="city" column="city"/>
<property name="confirmed" column="confirmed"/>
<property name="confirmationCode" column="confirmation_code"/>
<set name="authorities" cascade="all" inverse="true">
<key column="id" not-null="true"/>
<one-to-many class="model.Authority"/>
</set>
</class>
目前密码按原样保存到数据库中,但应该进行编码。
如何将applicationContext
配置和数据库查询的密码编码相同?
最佳答案
如果您自己选择哈希系统,而不是使用已经包含哈希密码的现有数据库构建应用程序,那么您应该确保您的哈希算法也使用盐。不要只使用普通摘要。
一个不错的选择是 bcrypt,我们现在通过 BCryptPasswordEncoder
(使用 jBCrypt 实现)在 Spring Security 3.1 中直接支持它。这会自动生成一个盐并将其与单个字符串中的哈希值连接起来。
一些数据库内置了对散列的支持(例如 Postgres )。否则,您需要在将密码传递给 JDBC 之前自己对密码进行哈希处理:
String password = "plaintextPassword";
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(password);
这就是您在创建用户时对密码进行编码所需要做的全部工作。
对于身份验证,您可以使用类似的东西:
<bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
<bean id="authProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="yourJdbcUserService" />
<property name="passwordEncoder" ref="encoder" />
</bean>
关于database - Spring 安全 :password encoding in DB and in applicationContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8521251/