UserDetails getPassword returns null in spring security 3.1. How to get password of currently logged in user?

前端 未结 3 975
旧时难觅i
旧时难觅i 2020-12-10 03:46

I have implemented change password functionality using spring security but ((UserDetails) principal).getPassword()) is returning null for logged in user.

If I remem

相关标签:
3条回答
  • 2020-12-10 04:21

    Yes, this has changed in version 3.1. Credentials are cleared after a successfull authentication by default. You can set eraseCredentialsAfterAuthentication to false on the ProviderManager to prevent this. See details here: http://static.springsource.org/spring-security/site/docs/3.2.x/reference/core-services.html#core-services-erasing-credentials

    0 讨论(0)
  • 2020-12-10 04:21

    Since the password isn't retained in memory after the user has been authenticated (generally a good thing), you would need to explicitly reload it in order to use it. An alternative and more flexible strategy is to inject an instance of the AuthenticationManager and use that directly:

    String name = SecurityContextHolder.getContext().getAuthentication();
    
    try {
        authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(name, oldPassword));
        // Update password here with your dao
    } catch (AuthenticationException e) {
        // Old password was wrong
    }
    

    that way you don't need to worry about things like password-encoding strategies. Note that you shouldn't be storing passwords in plain text. They should be hashed using bcrypt or something similar.

    0 讨论(0)
  • 2020-12-10 04:34

    I used this block of code (erase-credentials="false") to fix this. I do not know if this is an elegant solution but it fixed my problem:

    <authentication-manager alias="authenticationManager" erase-credentials="false">
        <!-- authentication-provider user-service-ref="userService" -->
        <authentication-provider>
            <jdbc-user-service data-source-ref="dataSource" />
        </authentication-provider>
    </authentication-manager>
    
    0 讨论(0)
提交回复
热议问题