Tech

OAuth2 Explained for Dummies and How OAuth2 works?

I see a few major mistakes when developers start learning about How OAuth2 works. One of the biggest ones is not following...

· 11 min read >

I see a few major mistakes when developers start learning about How OAuth2 works. One of the biggest ones is not following the order in which information is written.

The second major mistake I see, honestly, is Not thinking about WHY we need OAUTH and What Problem it solves. They just jump on to hands-on implementation without reading the pre-requisite.

Yes, you can do this, but you will almost certainly regret it later.

as mentioned in my previous post Can you recommend a good OAuth tutorial?

Prerequisite and Expectation from Article:

Basic knowledge of web development along with Curiosity and Commitment to read through the article completely as each section is built on top of previous. It should take about 15 minutes to read the topic completely but this can be the last time you will be spending to learn about OAUTH2.0 if you pay attention. By the end of this guide, you will be able to explain clearly about OAUTH to your audience.

Your concern as a reader if this article is up to date and maintained or not. This article is revised and marked finished as of 12th Jan,2023.

The goal of this article is not to make you a proficient programmer to implement OAUTH2.0 in any language. There will be some code snippet present in article as reference material. we will have part#2 of this series where we will do the hands on implementation of OAuth so that you can focus on

what is the core goal of this article: understanding in detail how the OAuth2.0 framework works and what problems it solves.

Oauth problem

We will understand various concepts in this oauth2.0 simplified like oauth2 flow diagram, Oauth2 grant types. how oauth2 works, oauth2 vs jwt. When and how to determine which grant type to use.

If you follow along this series and read the article in sequence you will have a complete understanding of what the heck is OAUTH2.0 from inside out and hands on implementation.

WHAT IS THE PROBLEM IN THE ABOVE SITUATIONS ?

This image below is screen from near past where we have to enter twitter username and password to download a software.

AKA Dark age before OAUTH. yes you need to give your credentials.

There are various risks and debts involved when going this way.

before oauth 2.0 risk

•Apps store the user’s password (clear text passwords)

•Servers are required to support password authentication

•Overly-broad access granted

•Users can’t revoke access to an app except by changing their password

•Compromise of third party app can compromise all of the data including password

Let’s come back to present and find out if you might have already used OAUTH if you have phone or done basic browsing around internet. If you have come across any of these screen below you have already used OAUTH.

oauth screen

Stop Before we move on two critical concepts that must be clear in your head are authentication and authorization , if you have a slight doubt about any single bit of these two terms it is useless to keep reading about OAUTH Full stop. Read this fine post Written by me first and you will thanks me later.

Understanding Authentication VS Authorization from daily life routine ?

There is always a business case for everything that pops up on the IT screen these days . So why the heck we need OAUTH and what is the business related motivation for that.

why we need oauth ?
How to Avoid Bothering 86% of Your Users on Signups? well Let’s keep reading to find out.

Here is where oAuth comes into play. One of the most simple definition of Oauth is .

if this above technical jargon does not make sense don’t worry , in other words until this point you should be at least sure and clear about the business case and motivation why we need oauth. once we dig down and go into more detail things will start making sense.

To be very specific, in the OAuth ecosystem, we will have a client application that wants to gain access to a protected resource on behalf of a resource owner (usually an end user).

What is OAUTH 2.0 Ultimate goal ?

we will go in a greater granular detail and hands on implementation down the road but you should be clear that that we’ve got one goal in this whole journey: getting the client to access the protected resource for the resource owner.

In a Nutshell OAuth is about how to get a token and how to use a token.

The OAUTH specification describes five methods(aka Grants) for acquiring an access token. Here is the list below . we will go into details of each down the road.

  1. Authorization code grant
  2. Implicit grant
  3. Resource owner Password Grant
  4. Client credentials grant
  5. Refresh token grant

Have you come across any of the similar screen below ,where you have signed into an application using your Facebook or Google account or any social media login. This is made possible by using method authorization code grant listed above.

practical use of OAUTH on this screen.
practical use of OAUTH on this screen. specifically authorization code grant

Now we know the methods names for acquiring an access token. Let’s look into what parties or roles are involved in this interaction.

There are mainly 4 parties/roles involved in this workflow to achieve our goal as mentioned earlier “how to get a token and how to use a token.”

Each of these components is responsible for different parts of the OAuth framework, and they all work together to make the OAuth protocol work as mentioned in the illustration below. we should go into more details for each of them.

oauth roles

Now that you are aware of the roles involved in the OAUTH game . Let’s look into methods (aka. grants) in more details.

Each Method (Grant Type) describe the sequence of communication between OAuth actors and is intended to use in a certain scenarios.     

Can you recall the 5 types of methods for acquiring access token discussed earlier in our discussion ?

If not scroll up a little and revisit paragraph that discuss five methods(aka Grants) for acquiring an access token.

A general rule of thumb is that depending on if the client is capable of or not keeping a secret will dictate which grant(method) the client should use.

1- Authorization Code Method (aka Grant)


When all conditions below satisfy use this method.

1 – Client is acting on behalf of resource owner.
2 – Resource owner can interact with Web browser.
3 – The client is third party web app and application code is running on web server.

It is meant to be used on web servers – This is termed as Default work flow.


What is flow of information between OAUTH Roles using Authorization Code Grant ?

The Resource Owner authenticates to an Authorization Server who issues an Authorization code to the Client. The Client then uses the Authorization Server to exchange its Authorization code for an access token it can use to access the Resource Server on behalf of the Resource Owner. See the illustration below.

The below is the detailed step by step interaction , We have added a more practical based simplified view for convenience.

Now coming to hands on implementation . You can skip this in-depth detail listed below until we do some hands on implementation. I have still added it below for advanced users who want to take a in depth look but if you are just starting out it is recommended not to confuse yourself with too much detail at the moment

The client will redirect the user to the authorization server with the following parameters in the query string:

response_type with the value code
client_id with the client identifier
redirect_uri with the client redirect URI. This parameter is optional, but if not send the user will be redirected to a pre-registered redirect URI.
scope a space delimited list of scopes
state with a CSRF token. This parameter is optional but highly recommended. You should store the value of the CSRF token in the user’s session to be validated when they return.
All of these parameters will be validated by the authorization server.

The user will then be asked to login to the authorization server and approve the client.

If the user approves the client they will be redirected from the authorization server back to the client (specifically to the redirect URI) with the following parameters in the query string:

code with the authorization code
state with the state parameter sent in the original request. You should compare this value with the value stored in the user’s session to ensure the authorization code obtained is in response to requests made by this client rather than another client application.

The client will now send a POST request to the authorization server with the following parameters:

grant_type with the value of authorization_code
client_id with the client identifier
client_secret with the client secret
redirect_uri with the same redirect URI the user was redirect back to
code with the authorization code from the query string

The authorization server will respond with a JSON object containing the following properties:

token_type this will usually be the word “Bearer” (to indicate a bearer token)
expires_in with an integer representing the TTL of the access token (i.e. when the token will expire)
access_token the access token itself
refresh_token a refresh token that can be used to acquire a new access token when the original expires

2- Implicit Method (Grant)


When all conditions below satisfy use this method.

1 – Client is acting on behalf of resource owner.
2 – Resource owner can interact with Web browser.
3 – The client(application code) is completely running inside of a web browser such as single page application.not on web server. So hence there is no way to store client secret.

It is intended to be used for user-agent-based clients (e.g. single page web apps) that can’t keep a client secret because all of the application code and storage is easily accessible.

What is the flow of information between OAUTH Roles when we use Implicit Grant ?

This is a simplified Authorization Code flow that directly issues an access token without authenticating the client. The client request the token on behalf of user and authorization server redirect to login prompt the user authenticate and give consent and the authorization server provide the token . the client use the token to get access to protected resource.

In case of Implicit Grant instead of the authorization server returning an authorization code which is exchanged for an access token, the authorization server returns an access token.

oauth 2.0 Implicit grant flow simplified.

The client will redirect the user to the authorization server with the following parameters in the query string:

response_type with the value token
client_id with the client identifier
redirect_uri with the client redirect URI. This parameter is optional, but if not sent the user will be redirected to a pre-registered redirect URI.
scope a space delimited list of scopes
state with a CSRF token. This parameter is optional but highly recommended. You should store the value of the CSRF token in the user’s session to be validated when they return.
All of these parameters will be validated by the authorization server.

The user will then be asked to login to the authorization server and approve the client.

If the user approves the client they will be redirected back to the authorization server with the following parameters in the query string:

token_type with the value Bearer
expires_in with an integer representing the TTL of the access token
access_token a JWT signed with the authorization server’s private key
state with the state parameter sent in the original request. You should compare this value with the value stored in the user’s session to ensure the authorization code obtained is in response to requests made by this client rather than another client application.

3- Resource owner Password Grant

When using the resource owner password credentials grant, the user provides the credentials (user name and password) directly to the application. The application then uses the credentials to obtain an access token from the service. This is not a recommended method to use and is generally a bad idea.


When all conditions below satisfy use this method.

1- Client is acting on behalf of the resource owner.
2- Resource owner can not interact with the browser while using the client(application code).
3- user have a simple set of credentials like a password?

This is not a recommended method to use and is generally a bad idea.

What is the flow of information between OAUTH Roles when we use Resource owner Password Grant ?

The client will ask the user for their authorization credentials (usually a username and password) and then then it could be possible for the client to trade them for an access token directly that can then used to access the protected resource.
Resource owner Password Grant

Want to work more hands on listed below is step by step implementation of this grant in multiple frameworks where we send username and password and exchange it with the access token.

.NET Core 6 implementation of this Resource Owner Password Grant.

.NET Framework 4.7 token based authentication in web api step by step resource owner password grant

The client will ask the user for their authorization credentials (usually a username and password).

The client then sends a POST request with following body parameters to the authorization server:

grant_type with the value password
client_id with the the client’s ID
client_secret with the client’s secret
scope with a space-delimited list of requested scope permissions.
username with the user’s username
password with the user’s password
The authorization server will respond with a JSON object containing the following properties:

token_type with the value Bearer
expires_in with an integer representing the TTL of the access token
access_token a JWT signed with the authorization server’s private key
refresh_token an encrypted payload that can be used to refresh the access token when it expires.

4- Client Credential Grant

This flow is meant to be used for first class web applications(GMAIL client is owned by GOOGLE’s Owned Gmail emailing Service or Spotify mobile app is owned itself by Spotify Swedish organization itself) OR mobile applications.


When all conditions below satisfy use this method.

1- Client is NOT ACTING on behalf of the resource owner.
2- Client acting on its own behalf.

used for first class web and mobile apps.

From Practical aspect this flow suitable for machine-to-machine authentication. When using the client credentials grant workflow, only the client details are used for authentication and there is no resource owner.

Client Credential Grant

The client sends a POST request with following body parameters to the authorization server:

grant_type with the value client_credentials
client_id with the client’s ID
client_secret with the client’s secret
scope with a space-delimited list of requested scope permissions.
The authorization server will respond with a JSON object containing the following properties:

token_type with the value Bearer
expires_in with an integer representing the TTL of the access token
access_token a JWT signed with the authorization server’s private key

5- Refresh token grant

When a client needs to refresh its access tokens without bothering the resource owner again, it does this using another token: the refresh token. The OAuth token is the key mechanism that’s at the center of OAuth’s entire ecosystem, and without tokens there is arguably no OAuth. They’re created by the authorization server, used by the client, and validated by the protected resource.

They might expire on their own or be revoked by the resource owner (or an administrator) at the authorization server. A refresh token even allows a client to request a new access token to replace an invalidated one.

Implementation Details for Refresh Token Grant Flow

The client sends a POST request with following body parameters to the authorization server:

grant_type with the value refresh_token
refresh_token with the refresh token
client_id with the the client’s ID
client_secret with the client’s secret
scope with a space-delimited list of requested scope permissions. This is optional; if not sent the original scopes will be used, otherwise you can request a reduced set of scopes.
The authorization server will respond with a JSON object containing the following properties:

token_type with the value Bearer
expires_in with an integer representing the TTL of the access token
access_token the access token itself
refresh_token a refresh token that can be used to acquire a new access token when the original expires

Here is the general overview of scenarios and what grant type to use.

app type against the workflow

Security Considerations:

PKCE (RFC 7636) is an extension to the Authorization Code flow to prevent several attacks and to be able to securely perform the OAuth exchange from public clients.

Proof of key code Exchange- A technique to mitigate authorization code hijacking.

Now you should have a clear understanding of basics on OAUTH. You have good amount of knowledge to step on to hands on implementation .

NEXT RECOMMENDED HANDS ON IMPLEMENTATION

Oauth2 Refresh Token GRANT implementation STEP BY STEP Using .NET Core 6

Oauth2 Resource Owner Password Grant Flow Step by Step Using .Net Core 6

Oauth2 Resource Owner Passsword Grant Flow Step by Step Using ASP.NET Framework 4.7 Web api

With some of the Grants already implemented above . In Upcoming Part#2 and Part#3 of this post we will go over building OAuth Client for following scenarios also we are also going to explore OAUTH2.1 down the road.

—- Update Jan 2023 – As promised in 2022 you can see above some of the hands on implementation of some authorization grants.

Several Hands-on Ways to Use OAuth2.0.

  • – Reading/Retrieving the user’s contacts from Facebook on the client side
  • – Reading/Retrieving the user’s contacts from Facebook on the server side
  • – Reading/Retrieving User Profile on LinkedIn
  • – Reading/Retrieving a User Profile from Google.
  • – Managing to refresh tokens on the client side
  • – Revoking the Issued Token
  • Why do we need OpenID and how does it relates to OAUTH ?
  • – Authenticating Google User through OpenID Connect
  • – Using Microsoft and Google Identity Provider together
  • – Revoking issued tokens
  • Exploiting the OAUTH2.0 Vulnerabilities during implementation.
  • Updating to OAUTH2.1 from OAUTH2.0

Please do comment and share this article if you found it to be helpfull.

net core six article

ASP.NET CORE 6 JWT Authentication

Apollo11 in Tech
  ·   9 min read
  • “One of the biggest ones is not following the order in which information is written.”

    For clarity, you mean “not following the order in which data is exchanged among the client, authorization service, and resource service”, correct?

    • Hi Rob, thank you for reading my article the second and third part is still in draft mode as each article is extensive more than 7k words along with hands-on implementation I am hoping to post it in a month or so.

  • >