Skip to main content

Client-side support

When developing a third party application which needs to participate in OAuth2 flows one has to write the code that will redirect users to OAuth2 AuthorizationCodeGrantService, interact with AccessTokenService in order to exchange code grants for access tokens as well as correctly build Authorization OAuth2 headers when accessing the end users' resources. JAX-RS makes it straightforward to support the redirection, while OAuthClientUtils class makes it possible to encapsulate most of the complexity away from the client application code.

For example, the following custom code can be used by the third-party application:

public class OAuthClientManager {
	
   private WebClient accessTokenService;
   private String authorizationServiceURI;
   private Consumer consumer;

   // inject properties, register the client application...

   public URI getAuthorizationServiceURI(ReservationRequest request,
      URI redirectUri,
      /* state */String reservationRequestKey) {
      String scope = OAuthConstants.UPDATE_CALENDAR_SCOPE + 
         request.getHour();
      return OAuthClientUtils.getAuthorizationURI(authorizationServiceURI, 
          consumer.getKey(),
          redirectUri.toString(),
          reservationRequestKey,
          scope);
      }

      public ClientAccessToken getAccessToken(AuthorizationCodeGrant 
         codeGrant) {
         try {
            return OAuthClientUtils.getAccessToken(accessTokenService, 
            consumer, codeGrant);
         } catch (OAuthServiceException ex) {
            return null;
         }
      }
	
      public String createAuthorizationHeader(ClientAccessToken token) {
         return OAuthClientUtils.createAuthorizationHeader(consumer, 
            token);
      }
}

The reason such a simple wrapper can be introduced is to minimize the exposure to OAuth2 of the main application code to the bare minimum, this is why in this example OAuthServiceExceptions are caught, presumably logged and null values are returned which will indicate to the main code that the request failed. Obviously, OAuthClientUtils can be used directly as well.

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 – please let us know!