What on Earth Is OAuth? ASuper Simple Intro to OAuth 2.0, Access Tokens, and How to Implement It in Your Site
Tags: security, javascript, webdev, oauth
Published: 2020-07-14 17:24:51

---
title: What on Earth Is OAuth? ASuper Simple Intro to OAuth 2.0, Access Tokens, and How to Implement It in Your Site
published: true
date: 2020-07-14 17:00:00 UTC
tags: security, javascript, webdev, oauth
canonical_url: https://blog.cotter.app/what-on-earth-is-oauth-super-simple-intro-to-oauth-20-access-tokens-and-how-to-implement-it-in-your-site/
series: OAuth 2.0, JWT Tokens, and How to Store Them Securely
---
*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](https://blog.cotter.app/content/images/2020/07/Cover-1.png)

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](#what-is-oauth-20)
2. [OAuth 2.0 in Action](#oauth-20-in-action)
3. [OAuth Tokens](#oauth-tokens): Short-lived access tokens and long-lived refresh tokens
4. [How to Implement OAuth 2.0 for your site](#how-to-implement-oauth-20-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](https://blog.cotter.app/content/images/2020/07/image-5.png)<figcaption>OAuth 2.0 Flow with Google Sign In</figcaption>

### 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](https://blog.cotter.app/content/images/2020/07/image-10.png)

- 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](https://blog.cotter.app/content/images/2020/07/image-6.png)<figcaption>How a JWT Token Looks Like</figcaption>

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](https://blog.cotter.app/content/images/2020/07/image-9.png)<figcaption>Renewing Access Token using a Refresh Token</figcaption>

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:

- **Web:** [HTML](https://docs.cotter.app/quickstart-guides/html-magic-link-with-email-and-phone) **,** [React](https://docs.cotter.app/quickstart-guides/react-magic-link-with-email-and-phone), [Angular](https://dev.to/cotter/angular-send-email-sms-and-whatsapp-verification-code-to-new-users-worldwide-1n1i-temp-slug-1500123) (also check out our [Gatsby](https://dev.to/cotter/stop-spending-days-to-code-your-login-page-add-cotter-s-magic-link-to-your-gatsby-app-under-5-minutes-mgl) and [Next.js](https://dev.to/cotter/passwordless-login-with-email-and-json-web-token-jwt-authentication-using-next-js-4b8f-temp-slug-7505363) tutorials).
- **Mobile:** [React Native](https://docs.cotter.app/sdk-reference/react-native/react-native-sdk-verify-email-phone), [Flutter](https://docs.cotter.app/sdk-reference/flutter/sign-in-with-email-phone-number), [iOS](https://docs.cotter.app/sdk-reference/ios/ios-sdk-verify-email-phone), [Android](https://docs.cotter.app/sdk-reference/android/android-sdk-1)

![What On Earth Is OAuth? A Super Simple Intro to OAuth 2.0, Access Tokens, and How to Implement it in your Site](https://blog.cotter.app/content/images/2020/07/image-7.png)

**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:

```bash
yarn add cotter
```

### Initialize and show an email login form:

```javascript
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;
```
<figcaption>App.js</figcaption>

You can get your `API_KEY_ID` from [the dashboard](https://dev.cotter.app) 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](https://docs.cotter.app/getting-access-token/verifying-jwt-tokens) 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.

- [OAuth Tokens from Cotter](https://docs.cotter.app/getting-access-token/handling-authentication-with-cotter): What tokens do you get, and how do they look like.
- [How to verify the access token and allow requests to private endpoints](https://dev.to/cotter/passwordless-login-with-email-and-json-web-token-jwt-authentication-using-next-js-4b8f-temp-slug-7505363).
- How to store it securely in the front end. We'll cover this next week, stay tuned!

* * *

### Questions & Feedback

If you need help or have any feedback, ping us on [Cotter's Slack Channel](https://join.slack.com/t/askcotter/shared_invite/zt-dxzf311g-5Mp3~odZNB2DwYaxIJ1dJA)! 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](https://dev.cotter.app/) and [check out our documentation](https://docs.cotter.app/).