从spring-security 中检索当前用户的密码

我正在使用带有HTTP Basic Auth的spring-security来保护java webapp。 在我的webapp中,我需要获取当前用户的用户名和密码,以进一步针对其他服务进行身份validation。 我可以获取用户名,但不能获取密码。

我已尝试使用SecurityContextHolder.getContext().getAuthentication()来访问此处建议的信息如何从spring-security获取明文密码? 但密码返回null

我怎样才能获得密码?

谢谢。

这是我的applicationContext-security.xml

                                  

我已经弄清楚了。

我已将我的身份validation管理器配置更改为使用authentication-manager元素并在其中添加了属性:

    

然后我可以在我的控制器类中使用SecurityContextHolder.getContext().getAuthentication().getCredentials()来获取密码。

感谢Piotrek De的帮助

你使用记住我/运行/切换用户? 在这种情况下,密码为空(如您提到的线程中所述)。 此外,可能您必须使用基本表单身份validation,(发送请求到j_spring_security_check)

如果要在会话对象中设置当前用户的全部详细信息(包括密码),则可以从该会话对象获取密码。

更好的方法是实现’userDetailsS​​ervice’。 这样您就可以控制在进行身份validation时如何使用UserDetails。 我实现了基于表单的身份validation并编写了我自定义的用户服务,

 @Service("userService") public class UserServiceImpl extends GenericService implements UserDetailsService,UserService{ @Override @Transactional public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { // Declare a null Spring User UserDetails userDetails = null; // Search database for a user that matches the specified username // You can provide a custom DAO to access your persistence layer // Or use JDBC to access your database // DbUser is our custom domain user. This is not the same as Spring's User User dbUser=this.findUserByUserName(username); if (dbUser == null) { throw new UsernameNotFoundException("HiMVC Security:: Error in retrieving user(username=" + username + ")"); } userDetails = new org.springframework.security.core.userdetails.User( dbUser.getUserName(), dbUser.getPassword(),//here you can put a clear text password true, true, true, true, loadUserAuthorities(username)); return userDetails; }