Essential CSS
JavaScript Roadmap
Learn JavaScript
Mastering Web Typography
Practical Astro
Understanding Async JS
Unorthodox Tailwind
API Masterclass
Build and Deploy
The Beginner Freelancer
Real World Node
Profile Billing Logout
Understanding Async JS
Lesson Plan
  1. Introduction
    1. What is Asynchronous JS?
    2. Callbacks are not automatically asynchronous
    3. What is an API?
    4. Evolution of HTTP APIs
    5. Ajax vs Asynchronous JavaScript
  2. Fundamental Concepts
    1. How to fetch resources
    2. Using XHR
    3. Using the Fetch API
    4. Using libraries
    5. Core JavaScript concepts
    6. Understanding Promises
    7. Understanding Async Functions
    8. Understanding the Event Loop
    9. Understanding JSON
    10. Async JS Best Practices
    11. Using Optimistic UI
  3. Understanding Rest API
    1. Diving into Rest APIs
    2. The Rest Architecture
    3. The Rest Structure
    4. Anatomy of a Request
    5. What's an endpoint
    6. Request methods
    7. Understanding request headers
    8. Understanding the request body
    9. Authentication
    10. Basic Authentication
    11. Bearer Authentication
    12. Authenticating with API keys and API Secrets
    13. Cross Origin Resource Sharing
    14. Anatomy of a response
    15. HTTP Statuses
    16. Response headers
    17. The response body
    18. Handling Errors
    19. Reading API documentations
    20. Understanding Curl
  4. Node Basics
    1. Why we are using Node
    2. Command Line Basics
    3. Installing Node
    4. Managing dependencies
    5. Using ES Modules in Node
    6. Using Node
    7. Restarting the server automatically
    8. Sending requests via Node
    9. Protecting API keys and secrets
  5. Building a server
    1. What's a server
    2. Building a simple server with Express
    3. Two kinds of servers
    4. API Server architecture
    5. Handling routes
    6. Understanding Middlewares
    7. Enabling CORS
    8. Receiving data
    9. Sending responses
    10. Handling errors in Express
    11. Using the server as a proxy
    12. Minimum viable server
  6. Open Authorization
    1. Open Authorisation (OAuth)
    2. Authenticating with Access Tokens
    3. Obtaining Access Tokens
    4. Public and Confidential Clients
    5. Authorisation Code Grant
    6. Understanding scope
    7. Proof Key for Code Exchange (PKCE)
    8. PKCE with Twitter
    9. Dynamic state and `code_verifier`
    10. Saving the access token in cookies
    11. Passing access tokens to the browser
    12. Saving the access token in local storage
    13. Refresh Token Grant
    14. Device Code Grant
    15. Client libraries vs REST
  7. Building Social Media Logins
    1. Introduction
    2. Starter Files
    3. Creating SSL certificates
    4. Login in with Github
    5. Github: Saving the token to local storage
    6. Github: Persisting the login status
    7. Login with Twitter
    8. Twitter: Saving the token to local storage
    9. Twitter: Persisting the login status
    10. Twitter: Refreshing the access token
    11. Login with Facebook
    12. Facebook: Saving the token to localStorage
    13. Facebook: Persisting the login status
    14. Facebook: Refreshing the access token
    15. Login with google
    16. Google: Saving the token to localStorage
    17. Google: Refreshing the access token

Authorisation Code Grant

6m:5s

You use authorisation code grant when you want to let users login with an identity provider like Github, Facebook, Twitter, Google, etc.

The process (or flow) looks like this:

  1. We create a “Sign in with XX” link for users
  2. Users click the link and sign in to the provider
  3. The provider redirects the users to a callback_url
  4. We generate an access token from the code value sent to the the callback_url
  5. We save the token for subsequent requests

You need the following to use the authorisation code grant:

  1. Create an app with the identity provider
  2. Have a server — this server is required for Step #4.

We’ll start this lesson by learning to create an app with the identity provider.

Creating an app with the provider

You need to tell an identity provider you want to use it for OAuth. You can do this by creating an “app” (which is an entry into their database) with the parameters needed for OAuth to work.

The instructions for creating the app depends on the provider you are using, so you have to look at the documentation for more details. For example, here are the instructions for Github and Twitter.

That said, the process for creating these apps are roughly the same. You need to:

  1. Sign up for a developer account with the provider
  2. Create an app in the provider’s website
  3. Set a name for your app
  4. Set a callback_url for your app

The name and callback url are important parameters.

  • Name — The name should be easily recognisable as users will see this name when they sign in.
  • Callback url — Users will be redirected to this url after they sign in. You’ll need this for the flow.

Using the authorisation code flow

We will go through the authorisation code flow with Github. Before you continue, please follow these instructions and create an app with Github.

The important parameters are the name and callback_url like I mentioned above. In this case, I set the name and callback url to the following:

  • Name: Learning AsyncJS
  • Callback url: https://localhost:3000/auth/github/callback
Settings for creating an app.

Note: We use localhost:3000 here because we want Github to redirect users to our local server. Make sure you set this to your app’s domain name for real-world usage.

The first step is to create a link users can use to sign in with Github. The instructions can be found here.

We can see two things here:

  1. The endpoint is https://github.com/login/oauth/authorize
  2. client_id is a required parameter.

You can find the client_id in the app you registered.

The sign-in url will be:

Terminal window
https://github.com/login/oauth/authorize?client_id=YOUR_CLIENT_ID

Note: Different providers require different parameters. Always check the documentations to ensure you’re sending the parameters they need!

You can get users to visit this link by sending them to a route. This route will redirect the user to the link we generated above.

<a href="/auth/github">Login with Github</a>
app.get('/auth/github/', (req, res) => {
res.redirect(
'https://github.com/login/oauth/authorize?client_id=YOUR_CLIENT_ID',
)
})

If you visit the link you created, you should see the following page.

Login with Github page

At this point, the user needs to click on the authorise button to sign-in with Github. If they do so, Github will redirect the user to the callback_url.

If the user cancels the sign-in request, the authorisation code flow will stop.

Step 3: Github redirects the user to our callback url

When Github redirects the user to the callback url, it provides us with a code query parameter. You can see the code parameter in your browser’s address bar.

This code value is a temporary verification for obtaining an access token. Each provider has a different expiration for this code value. Github’s code expires in 10 minutes. If the code value expires, you need get users to login to Github again.

Note: Most providers would return the code parameter. Check the documentations to be sure!

Step 4: Generating an access token from the callback url

We need to send a POST request to Github to request for an access token. The access token will be used for token authentication.

The instructions to do this with Github can be found here

There are three required parameters in this request:

  1. The client_id
  2. The client_secret
  3. code which we got from the above step

We already have the client_id from step 1.

For client_secret, you need to generate a one inside your app in Github. You should get a screen like this after generating the secret.

  • Make sure you copy this secret because you won’t see it again.
  • Also make sure you don’t show this secret to anyone. (I’m showing you because I deleted it already).

Getting code is straightforward. It can be found in req.query when we handle the callback_url route.

app.get('/auth/github/callback', (req, res) => {
const { code } = req.query
})

To get the access token, we send a POST request according to the instructions above. Make sure to include all three values in the body.

app.get('/auth/github/callback', async (req, res) => {
const code = req.query.code
// Send POST to get access token
const response = await zlFetch.post(
'https://github.com/login/oauth/access_token',
{
body: {
client_id: clientID,
client_secret: clientSecret,
code,
}
}
)
console.log(response.body)

If the request is successful, you should get an object with the access_token, scope, and token_type.

This access_token can be used for authentication.

Note: Github doesn’t require a grant_type parameter for this request, but some providers do. If they ask for it, you will most likely set grant_type to authorisation_code.

Step 5: Save the token for subsequent requests

The access_token can be used in the authorisation header for requests that require authentication.

Here’s is an example where we used the access token to get a list of repositories for the authenticated user.

// Using the access token
zlFetch.post('https://api.github.com/user/repos', {
auth: access_token,
})

You want to save this access_token so you can use it for subsequent requests without asking users to login again.

You can save it in two places:

  1. In the user’s browser
  2. In your database

You should save the token in the user’s browser if you let the user login to your app through the identity provider. Doing so allows you to authenticate the user silently upon each page request (which means they never have to sign in again). We’ll discuss how you save the token in the user’s browser in a later lesson.

You should save the token in the database if you only use it to help users access the API — you don’t need to let users login to your app through the identity provider. This keeps the token safe since the connection between servers and databases are secure.

Three legged auth

The Authorization Code Grant is also called a three-legged auth because it requires three participants:

  • The user
  • Your server
  • The identity provider’s server