我正在使用Spring 3.2.5。现在我正在使用哈希密码
MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
messageDigest.update(password.getBytes("UTF-8"));
byte[] digestBytes = messageDigest.digest();
我想使用 spring 提供的方法保护密码。我在网上搜索了大部分帖子,大部分帖子都很旧。所以任何例子都会很好。
org.springframework.security.crypto.password.StandardPasswordEncoder
类。这要麻烦得多,您不必担心盐和迭代 - 细节完全封装在编码器中。
<!-- password encoder -->
<beans:bean id="encoder" class="org.springframework.security.crypto.password.StandardPasswordEncoder" />
<!-- This is the authentication manager -->
<authentication-manager>
<authentication-provider user-service-ref="authService">
<password-encoder ref="encoder" />
</authentication-provider>
</authentication-manager>
访问此网站以了解更多信息。
使用具有 <password-encoder>
属性的密码编码器(如其他答案所示)是正确的。我还想补充一点,推荐使用的编码器是 BCryptPasswordEncoder,正如 Spring 文档在尝试使用旧的标准编码器时建议的那样:
If you are developing a new system, BCryptPasswordEncoder is a better choice both in terms of security and interoperability with other languages.
您还可以在此处阅读有关哈希的更多背景详细信息,其中BCrypt算法也是建议的算法之一。
你可以简单地使用弹簧安全性来做到这一点,在 spring-security.xml bean 中添加以下行:
使用 SHA-512,
<authentication-manager>
<authentication-provider user-service-ref="userDetailsService">
<password-encoder hash="sha-512" />
</authentication-provider>
</authentication-manager>
或使用 md5:
<authentication-manager>
<authentication-provider user-service-ref="userDetailsService">
<password-encoder hash="md5" />
</authentication-provider>
</authentication-manager>
关于用户详细信息服务:用户详细信息服务提供按用户名加载用户的方法。更多关于用户详细信息服务
如果你想通过任何其他属性(如电子邮件或手机号码)加载用户,那么你需要编写实现UserDetailsService
的自定义类,并在该类中编写你的实现。
有关自定义用户详细信息服务实现,请参阅此链接
我发现这是最简单的方法,因此这是我使用的方法:
<sec:authentication-manager alias="authenticationManager">
<sec:authentication-provider
user-service-ref="userDetailsService">
<sec:password-encoder hash="sha-256">
<sec:salt-source user-property="username" />
</sec:password-encoder>
</sec:authentication-provider>
</sec:authentication-manager>
这里的要点是,password-encoder
是在 XML 本身中定义的(如果需要,甚至可以在 salt 中定义),因此不需要额外的代码。这是"春天的方式"...