How to get user's authorization credentials in code with spring security?

Alex picture Alex · May 23, 2015 · Viewed 8.7k times · Source

What I'm trying to do is to build CRUD REST service. It will maintain a database of users and theirs records. I'd like to allow users to get access only to their own records. I use Spring Security for authentication and store user's password hashed with Bcrypt. All I can understand right now that my spring-security.xml shuld like:

<security:http auto-config='true'>
    <security:intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
    <security:http-basic />
</security:http>

<security:authentication-manager>
    <security:authentication-provider>
    <authentication-provider>
        <password-encoder ref="encoder" />
        <jdbc-user-service data-source-ref="dataSource"
            users-by-username-query="select username,password, enabled from users where username=?"
            authorities-by-username-query="select username, role from user_roles where username =?" />
    </authentication-provider>
    </security:authentication-provider>
</security:authentication-manager>

But for farther work of the service I need to know exactly which user have been authorized. So how could I do that? And for related matter is there way to get around mainlining user's role in the database since there's no more roles planned.

Answer

holmis83 picture holmis83 · May 23, 2015

Simple.

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username = auth.getName();
Object credentials = auth.getCredentials();

To access the credentials, i.e. the password, you need to set erase-credentials to false:

<security:authentication-manager erase-credentials="false">
  ...
</security:authentication-manager>

Or if configured via annotations then:

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.eraseCredentials(false);
    /* configure user-service, password-encoder etc ... */
}