我使用 Spring Security 来处理应用程序中的授权。在我的配置中,我有以下内容:
<security:authentication-manager>
<security:authentication-provider>
<security:password-encoder hash="md5"/>
<security:jdbc-user-service id="userService"
data-source-ref="dataSource"
users-by-username-query="select phone, password, true from users where phone=?"
authorities-by-username-query="select phone,'ROLE_USER' from users where phone=?" />
</security:authentication-provider>
</security:authentication-manager>
当我删除<security:password-encoder hash="md5"/>
时行并存储在数据库原始密码中,授权工作正常。但是当我尝试在数据库中存储哈希密码并使用此行时,授权失败。我做错了什么吗?
附注数据库中的密码哈希值 100% 正确。 202cb962ac59075b964b07152d234b70
对于 123
密码。
最佳答案
我可以建议您创建测试类并创建哈希。
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
public class Test {
public static void main(String[] args) {
Md5PasswordEncoder encoderMD5 = new Md5PasswordEncoder();
String securePass = encoderMD5.encodePassword("admin", null);
System.out.println(encoderMD5.isPasswordValid(securePass,"admin", null));
}
}
在xml中使用
<bean name="md5" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder"/>
<security:password-encoder ref="md5"/>
当然还要检查数据库中的哈希密码值
我推荐使用bcrypt
在 XML 中
<bean name="bcryptEncode" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
<constructor-arg value="12"></constructor-arg>
</bean>
<security:password-encoder ref="bcryptEncode"/>
您可以通过以下方式获取编码密码:
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
public class PrintBCryptString {
public static void main(String[] args) {
PasswordEncoder encoder = new BCryptPasswordEncoder(12);
System.out.println(encoder.matches("type here some string", encoder.encode("type here some string")));
System.out.println(encoder.encode("type here some string"));
}
}
也许会有用小explanation of bcrypt
关于java - Spring Security - 密码哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30151491/