DEV Community

Michelle Marcelline for Cotter

Posted on • Originally published at blog.cotter.app on

What on Earth Is OAuth? ASuper Simple Intro to OAuth 2.0, Access Tokens, and How to Implement It in Your Site

Get a quick intro on what OAuth 2.0 is and how signing in with OAuth 2.0 works – explained in simple terms using Google Sign In as an example.

What On Earth Is OAuth? A Super Simple Intro to OAuth 2.0, Access Tokens, and How to Implement it in your Site

We're excited to tell you that Cotter now generates access tokens and refresh tokens on authentication. Let's first go over the concepts of OAuth 2.0 and the tokens before we jump in on how to use it.

Overview

  1. What is OAuth 2.0
  2. OAuth 2.0 in Action
  3. OAuth Tokens: Short-lived access tokens and long-lived refresh tokens
  4. How to Implement OAuth 2.0 for your site

What is OAuth 2.0?

OAuth 2.0 is an authorization framework that defines how a third-party application can obtain access to a service securely without requiring security details (username, password, etc.) from the user. A common example of OAuth 2.0 is when you use "Sign in with Google" to log in to other websites.

OAuth 2.0 in Action

In general, the OAuth 2.0 flow looks like this:

What On Earth Is OAuth? A Super Simple Intro to OAuth 2.0, Access Tokens, and How to Implement it in your Site
OAuth 2.0 Flow with Google Sign In

Let's use "Sign in with Google" as an example.

Albert is a Google Calendar user and he's trying to use Calendly.com to help manage his calendar. We'll go over the terms in the next example.

  • (1) Calendly.com wants to access Albert's Google Calendar. Calendly.com redirects Albert to sign in to his Google account where he grants Calendar permission for Calendly.com. (2) Google returns an Authorization Grant and redirects Albert to Calendly.com. (3) Calendly.com gives the Authorization Grant to Google and (4) receives an Access Token. (5) Calendly.com can now use this Access Token to (6) access Albert's Google Calendar, but not his Google Drive or other resources.

Here, Calendly.com is the client, Albert is the Resource Owner, Google Account is the Authorization Server, and Google Calendar is the Resource Server.

Let's try to understand the terms in a simpler example.

Let's use an example of Alberta who stays in a hotel and wants to allow her babysitter, Candy, to access her room.

  1. Alberta agrees that Candy shall access her room and asks Candy to get her own room key from the receptionist. Alberta gives Candy a copy of her ID and a note saying "access during daytime only".
  2. Candy goes to the receptionist with a copy of Alberta's ID and the note. The receptionist verifies the ID and gives Candy a special room key that can only be used during daytime. Candy goes back to the room and uses her key to access the room.

What On Earth Is OAuth? A Super Simple Intro to OAuth 2.0, Access Tokens, and How to Implement it in your Site

  • Candy is the Client (just like Calendly.com) who wants to access Alberta's data. Alberta here is granting limited access to the Client. The Authorization Grant is Alberta's ID copy and her note.
  • The receptionist is the Authorization Server, they can generate a room key for Candy to access the room. This room key is the equivalent of an Access Token, it can be used to get resources.
  • The room lock is the Resource Server, it holds the resource that Candy wants: the room.

There are several different flows that OAuth 2.0 offers, this example is following the Authorization Code flow. We'll talk about the different flows in a different post :)

OAuth Tokens

As mentioned above, at the end of the flow, the client receives an Access Token. Generally, these Access Tokens are short-lived; so, what happens when it expires?

Short-lived access tokens and long-lived refresh tokens

At step 4, the Authorization Server can generate 2 tokens, an access token and a refresh token. The access token is short-lived, it should only last from several hours to a couple of weeks.

When the access token expires, the application can use the refresh token to obtain a new access token. This prevents having to ask the user to re-authenticate.

Access Token

Alright, now that we understand how things work, let's start thinking about how to generate access tokens. With a short-lived access token, we can use a JWT Token to make a self-encoded access token.

What On Earth Is OAuth? A Super Simple Intro to OAuth 2.0, Access Tokens, and How to Implement it in your Site
How a JWT Token Looks Like

JSON Web Tokens (JWT) is a signed JSON object. This means you can trust the data contained in the JSON object by verifying the signature. For authorizing a user, you can include the user's ID and email in the JWT.

When you give the JWT Access Token to the Resource Server (your backend API server), your server can validate the JWT Token without needing to access the database to check if it's valid.

All your server needs to do is to validate that the JWT Token is valid using a library, see the user ID of the user making the request from the token, and trust that this user ID is already authenticated.

Refresh Token

What On Earth Is OAuth? A Super Simple Intro to OAuth 2.0, Access Tokens, and How to Implement it in your Site
Renewing Access Token using a Refresh Token

A refresh token is a special token that is used to obtain a new Access Token. Since this is long-lived, refresh tokens are generally opaque strings stored in the database. Storing refresh tokens in the database allows you to revoke them by deleting it from the database.

Because there is no way to expire an Access Token, we should make the access token short-lived. Revoking the refresh token prevents malicious parties from refreshing an expired Access Token. This means that if your Access Token expires in 1 hour, then an attacker who obtained your Access Token can only access your API for 1 hour before it expires.

How to Implement OAuth 2.0 for your site

This sounds like a lot, but you can implement OAuth 2.0 and authorizes API requests using access tokens by using Cotter in just a few minutes.

Your website as the Client, Cotter as the Authorization Server

With the OAuth flow above, here's how it looks like:

  • Your website is the Client
  • Your user is the Resource Owner
  • Cotter is the Authorization Server
  • Your backend server is the Resource Server

Logging-in and Generating Access Tokens

We have several 5-minutes quickstarts for authenticating users and generating access tokens:

What On Earth Is OAuth? A Super Simple Intro to OAuth 2.0, Access Tokens, and How to Implement it in your Site

For this guide, we'll use React as an example. We'll build a login form with email magic link and get an access token at the end of the flow.

Import Cotter:

yarn add cotter
Enter fullscreen mode Exit fullscreen mode

Initialize and show an email login form:

import React, { useEffect } from "react";
import Cotter from "cotter"; // 1️⃣ Import Cotter

function App() {
  useEffect(() => {
    // 2️⃣ Initialize and show the form
    var cotter = new Cotter(API_KEY_ID); // 👈 Specify your API KEY ID here
    cotter
      .signInWithLink() // use Magic link
      .showEmailForm() // show email login form
      .then(resp => console.log(resp))
      .catch(err => console.log(err));
  }, []);

  return (
    // 3️⃣ Put a <div> with id "cotter-form-container"
    // that will contain the form
    <div id="cotter-form-container" style={{ width: 300, height: 300 }} />
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode
App.js

You can get your API_KEY_ID from the dashboard by creating a free account.

That's it. Check your console logs for an access token.

The function above covers steps 1-4 in the OAuth 2.0 flow. The response from showEmailForm() returns an access token. As described above, you should then use this access token to access a resource in your backend server.

For example, you can include this access token to your endpoint /api/private-resource and you'll check if the access token is valid before continuing with the request.

What's Next?

Now that you know how to get access tokens, here's a few more things to wrap up your login flow.


Questions & Feedback

If you need help or have any feedback, ping us on Cotter's Slack Channel! We're here to help.

Ready to use Cotter?

If you enjoyed this tutorial and want to integrate Cotter into your website or app, you can create a free account and check out our documentation.

Top comments (0)