Getting started with oAuth2

The oAuth2 authorization framework is widely used by all big companies, such as Google, Facebook, Twitter, GitHub etc. It allows third party applications to get access to some scope of the service resources. You probably use it every day while clicking “Sign up with [some social media]”.
But how does it work? The official standard documentation RFC 6749 might be a bit difficult to read for beginners, so I will try to explain it in a more appealing way.

What is oAuth2 all about?

As we mentioned before oAuth2 is an authorization framework (sometimes called protocol). Authorization is about giving access to some secured resources and controlling the rights and privileges of this access.

Imagine you are working in a big office building and you have access to multiple rooms with your card or key. During your vacations you want your friend John to water the plants in one of your rooms. You have multiple possibilities to give him access to those plants in the office during your absence:

  • You can move all the plants manually to his place — not very convenient ❌
  • Give him your keys and your ID badge — not very secure. He can steal your keys, copy them or explore all the rooms you have access to, not only the one with the plants ❌
  • Provide some kind of controlled access to this specific room without giving him your keys ✅

The last option seems like a good idea! So imagine a scenario:
[P]atryk (me), [J]ohn, [R]eceptionist

J enters the office with the access card and waters the plants. 🌻 🎉
Pros of this approach:

  • J only has access to the P’s office and nothing more.
  • When the task is finished, P can take the permission back just by invalidating his access card and written permission.
  • Plants are alive.
  • Everyone is happy! 🕺🏿
Actually cactus doesn’t need so much watering, but it’s the best dancing plant GIF I found

So now let’s reference this real-life example to the oAuth2 Terminology.
You are the Resource owner and the office room you want to give access to is your Resource. You want to give this access to some specific person or service, which is called Client. After a successful authorization the office reception (Authorization Server) sends written permission (Authorization Grant) to the address specified before (redirect url). With this permission client comes back to the office reception (Authorization server) and exchanges the grant for the access card (Access Token). Having this token client can finally access the room (Resource) in the office building (Resource Server).

Authorization flow

Now let’s focus on how the things are implemented under the hood.

To receive the token, client needs to obtain authorization grant from the resource owner. There are four grant types defined by oAuth – each for different use cases:

  • Authorization code: for confidential clients like server-side apps
  • Implicit: for public clients such as web or mobile apps
  • Resource owner password credentials: for trusted clients such as internal or highly privileged apps
  • Client credentials: for third party apps (clients) to obtain access to some resources under its own control

For the purpose of this article we will discuss only the Authorization code grant type in details. (if you are interested in other types, please take a look at the official documentation linked above).

…so let’s take a look at the code flow scheme:

A. Authorization request

First of all, the third-party app which wants to obtain the access, gives the authorization link to the user (resource owner).

GET https://fakeapi.indoorway.com/v1/oauth/authorize
?response_type=code
&client_id=s6BhdRkqt3
&redirect_uri=https://superduperapp.com/clbk
&scope=buildings+contacts
&state=xyz

The url must be the address of oAuth provider (the service you want to obtain access to) and the URL has the following parameters:

  • response_type: the type of authorization grant. In this case code refers to the Authorization code grant type
  • client_id: The unique client identifier obtained during third-party client registration
  • redirect_uri: The URI to redirect the user to after performing the authorization
  • scope: List of predefined space-delimited access scope identifiers
  • state: A random string to verify the returning response

B. Confirmation

A special screen with the list of requested permissions, the requesting service name and some additional information should be shown for the user to confirm the grant.

C. Authorization response

After the successful confirmation the authorization service should redirect the user to the redirect_uri specified before with additional parameters (the authorization grant).

GET https://superduperapp.com/clbk
code=SplxlOBeZQQYbYS6WxSbIA
&state=xyz
  • code: Single-use authorization code generated by the server
  • state: A random string specified when the authorization request is made

D. Access token request

Now when the client already has the authorization grant, it can request for the access token. The request should look like this:

POST https://fakeapi.indoorway.com/v1/oauth/token
grant_type=authorization_code
&code=SplxlOBeZQQYbYS6WxSbIA
&redirect_uri=https://fancyclient.com/clbk
&client_id=s6BhdRkqt3
  • grant_type: Type of authorization grant
  • code: Authorization code received in the request before
  • redirect_uri: The same callback URL we passed in the authorization request
  • client_id: The unique client identifier obtained during third-party client registration

E. Access token response

After the successful code and client_id verification, a new access token is issued and returned to the client.

200 OK
{
"access_token":"2YotnFZFEjr1zCsicMWpAA",
"token_type":"bearer",
"expires_in":3600,
"refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA"
}
  • access_token: The token used for accessing protected resources
  • token_type: Type indicating how the token should be used. In this case barear type means that token should be passed in plain text in HTTP Authorization header
  • expires_in: How long the token is valid (in seconds)
  • refresh_token: Optional refresh token is used to obtain a new access token when the old one expires

F. Access to the resource

With the access token client can finally access the protected resources. We just need to add the Authorization header to the request like this:

GET https://fakeapi.indoorway.com/users/123/buildings/
Authorization
: Bearer 2YotnFZFEjr1zCsicMWpAA

Where the 2YotnFZFEjr1zCsicMWpAA value should be our access token obtained in the previous step. 🎉

Happy ending

As you can see, all this oAuth2 thing is not so hard. It is all about sending a few requests back and forth and remembering some random tokens 😁 .

After this short introduction you know enough to start implementing oAuth2 clients on your own. Is it Instagram photos stream you want to have access to? List of your users’ Tweets? Or maybe just “Sign Up with Facebook” button? The possibilities are endless!

That’s how “consuming an API” looks like (really)

To be continued….

In the next part of this tutorial we will take a closer look on how to implement an oAuth2 provider in Ruby on Rails, so stay tuned!

--

--