Skip to main content

How to get the user login name

When one writes a custom server application which needs to participate in OAuth2 flows, the major question which needs to be addressed is how one can access a user login name that was used during the end-user authorizing the third-party client. This username will help to uniquely identify the resources that the 3rd party client is now attempting to access. The following code shows one way of how this can be done:

@Path("/userResource")
public class ThirdPartyAccessService {

   @Context 
   private MessageContext mc;
	
   @GET
   public UserResource getUserResource() {
      OAuthContext oauth = mc.getContent(OAuthContext.class);
      if (oauth == null || oauth.getSubject() == null || 
         oauth.getSubject().getLogin() == null) {
	      throw new WebApplicationException(403);
	   }
	   String userName = oauth.getSubject().getLogin();
	   return findUserResource(userName)
   }

   private UserResource findUserResource(String userName) {
      // find and return UserResource
   }
}

The above shows a fragment of the JAX-RS service managing the access to user resources from authorized 3rd-party clients (see the Design Considerations section for more information).

The injected MessageContext provides an access to OAuthContext which has been set by OAuth2 filters described in the previous section. OAuthContext will act as a container of the information which can be useful to the custom application code which do not need to deal with the OAuth2 internals.

Did this page help you?

If you find any issues with this page or its content – a typo, a missing step, or a technical error – let us know how we can improve!