Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 543
Alex Avatar asked May 23 '15 11:05

Alex


People also ask

What is SecurityContextHolder getContext () getAuthentication ()?

The HttpServletRequest.getUserPrincipal() will return the result of SecurityContextHolder.getContext().getAuthentication() . This means it is an Authentication which is typically an instance of UsernamePasswordAuthenticationToken when using username and password based authentication.


1 Answers

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 ... */
}
like image 102
holmis83 Avatar answered Oct 11 '22 03:10

holmis83