Authentication using Oauth 2.0

OAuth2 is an authentication framework used widely today for clients to access API endpoints. There are various flows available for authentication depending on the use case. Two popular flows commonly used are code-grant and client-credentials.

Code Grant is typically used when an application is requesting access to a resource on behalf of a user. In this instance the application redirects the user to an OAuth2 provider (such as Google or Facebook) and lets the user login with their OAuth login and password at the providers web site. The provider validates the login and redirects the user back to the application with an authorization code. The application can then exchange this code for an access token (along with its own client-id and secret that it obtained when it first registered with the OAuth2 providerthat it can then pass to the resource server to interact on behalf of the user. 

The resource server verifies that the access token is valid by checking its authenticity in possibly different ways. One of the popular ways is when the access token is a JWT (Json Web Token). In this case the application has to verify that the signature in the JWT is valid so no one tampered with it and that it has not expired. Verification of the signature could happen in multiple ways – the OAuth provider could produce a hash using the secret of the application or it could sign it using a private key who’s public keys are advertised in a well known location. In both cases the application regenerates the signature using either method and checks to make sure it matches the signature in the JWT. The application then extracts the principal (the user id if you like to think of it that way also called a “sub”) to identify who the user is and what their “scope” is (what they are allowed to do on the resource server).

Client Credentials is typically used when the application wants to access a resource not on behalf of a user but itself. A use case may be when an automated batch processes for example want to access data on the resource server. In this scenario the application sends its client-id and secret (that it obtained when it first registered with the OAuth2 provider) to obtain an access token. The provider validates this information and returns an access token back to the application which it then passes to the resource server with all its API calls. The resource server validates the token in the same manner described earlier and services (or denies) the request. 

The following diagram illustrates the Code-Grant workflow. If you leave out steps 1-3 it depicts Client-Credentials.

This is a great resource to understand OAuth in greater detail!

Leave a Comment