Search code examples
javaspringoauthoauth-2.0spring-oauth2

Spring Oauth Get Current User


I'm developing a system with 3 smaller projects, which are as follows:

  • a client
  • a ressource server
  • a authentication server

The authentication server has a register and a login page. The resource server is secured by the authentication server.

From the client I want to access the resource via REST API. The client is calling the resource server via OAuth2RestTemplate from Spring to access the resource. I managed to access the resource, after I authenticated myself.

Now to the problem. At the client I need to know the current user to display the the username and enabling the user to change his profile.

I tried to access the principal of the user via spring security with

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

but it just returned null. So my question is: Is there a way to get the current logged in user with the OAuth2RestTemplate?

Edit:

So I decided to change the plan to implement a link in my authentication server, which returns the user information. The problem is, when I want to talk the authentication server via OAuth2RestTemplatethe authentication server just returns the login page. Everything works fine, when I call the page from browser or when I want to talk to the resource server via OAuth2RestTemplate.


Solution

  • Set a TokenEnhancer to your AuthorizationServerEndpointsConfigurer in Authorization server. You can add User information to the token as additional info map.

    Here is a sample implementation of a custom TokenEnhancer,

        public class CustomTokenEnhancer implements TokenEnhancer {
    
        @Override
        public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    
            final Map<String, Object> additionalInfo = new HashMap<String, Object>();
            UserDetails user = (UserDetails) authentication.getPrincipal();
    
            additionalInfo.put("<custom_user_info>", user.getUsername());
    
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
    
            return accessToken;
        }
    
    }
    

    In your Authorization server,

    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
            endpoints.tokenEnhancer(new CustomTokenEnhancer());
        }