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

PKCE with Twitter

5m:31s

We’re going to perform a PKCE flow with Twitter.

Before we begin, please follow the instructions here to create a Twitter App. Twitter will ask you for a bunch of information. Just write you’re learning to use the API every box. You’ll get immediate access once you complete the form.

Creating a Twitter App

When you’re in the developer portal, create a “Project”. Then, create an “App” in the project.

Go back to the dashboard when you’re done with the process and you should get a screen like this:

I named both my project and app ‘Learning Async JS’.

Click on your app and you should be able to setup Authentication settings. Click on Set up, then turn on OAuth 2.0.

User authentication settings
Turning on OAuth 2.0

We’ll add http://127.0.01:3000/auth/twitter/callback as the callback URL. 127.0.0.1 is synonymous with localhost. We use 127.0.0.1 because Twitter mentioned not to use localhost.

When you’re done, you should see a page with your client_id and client_secret. Save these values somewhere.

You’ve created the app and you’re now ready to perform a PKCE flow.

PKCE Flow with Twitter

The information needed from Twitter for the PKCE flow can be found in two links — this and this.

Note: Twitter’s documentations are harder to read compared to Github’s documentation. Take your time if you’re reading through the above links.

First, we need to create the sign-in link. Twitter gave an example that looks like this:

This link looks complicated. If you pay attention to the structure, you’ll discover there are a few key points:

  1. The endpoint is https://twitter.com/i/oauth2/authorize
  2. It requires a scope parameter
  3. It requires the following parameters:

There are many parameters here so let’s take things slow.

The Scope Parameter

Twitter requires a scope parameter for the sign-in link. You can see a list of scopes here.

We’ll set scope to tweet.read for now.

const params = {
scope: 'tweet.read',
}

Other Parameters

We have to add six more parameters to the sign-in link. The first three are the easy ones:

  • response_type — we set this to code
  • client_id — we can get this from the App
  • redirect_uri — we need to provide same value we used for the callback url.
const params = {
scope: 'tweet.read',
response_type: 'code',
client_id: 'CLIENT_ID',
redirect_uri: 'https://localhost:3000/auth/twitter/callback',
}

The next three require a bit more explanation:

  • state — this is a random string used to prevent Cross-site request forgery (CSRF) attacks. You need to provide the same state values in Step 1 and 4.
  • code_challange and code_challenge_method — we talked about these in the previous lesson. We need to use the same code_verifier values in Step 1 (to generate code_challenge and in Step 4 (to send to the API).

We’ll discuss how to use the same state and code_verifier values in Steps 1 and 4 in the next lesson. For now, we’ll use the following hardcoded values:

  • State: 12345
  • Code verifier: challenge
  • Code challenge: LdAL134CIs7YgmZUganB2fkHMJ0W4F7QB6HqY5KEd6k
  • Code challenge method: S256
const params = {
// ...
state: '12345',
code_challenge: 'LdAL134CIs7YgmZUganB2fkHMJ0W4F7QB6HqY5KEd6k',
code_challenge_method: 'S256',
}

Combining everything

We can combine the endpoint and params to generate the sign-in link:

const baseURL = 'https://twitter.com/i/oauth2/authorize'
const params = {
/* ... */
}
const query = new URLSearchParams(params)
const link = baseURL + '?' + query.toString()
console.log(link)

You should get a link like this. (Please replace CLIENT_ID with your client id)

Terminal window
https://twitter.com/i/oauth2/authorize?response_type=code&client_id=CLIENT_ID&redirect_uri=https%3A%2F%2Flocalhost%2Fauth%2Ftwitter%2Fcallback&state=12345&code_challenge=LdAL134CIs7YgmZUganB2fkHMJ0W4F7QB6HqY5KEd6k&code_challenge_method=S256&scope=tweet.read

You can get your users to visit this link by sending them to a route, then redirecting the user from that route.

<a href="/auth/twitter">Login to Twitter</a>
app.get('/auth/twitter/', (req, res) => {
// ...
res.redirect(link)
})

Step 2: User signs in to Twitter

If you click the link you should see this page.

Simply authorise the app to move on to the next step.

Step 3: Twitter redirects the users to the callback url

Twitter sends along two parameters — state and code when it redirects the user back to the callback url. We can get these values through req.query.

Terminal window
router.get('/auth/twitter/callback', async (req, res) => {
const { state, code } = req.query
console.log(state)
console.log(code)
})

We need to check if the returned state value matches the same one we created.

  • If the values are the same, it means the request originated from us and we can proceed.
  • If the values are not the same, the request originated elsewhere and we should not proceed.
app.get('/auth/twitter/callback', async (req, res) => {
const { state, code } = req.query
if (state !== '12345') return
})

Step 4: Using code to request for an access token

Twitter requires us to do a few things here:

  1. We need to send a POST request to https://api.twitter.com/2/oauth2/token
  2. We need to perform Basic Authentication with client_id as the username and client_secret as the password.
  3. We need to set Content-Type to application/x-www-form-urlencoded
  4. We need to pass in five parameters — code, grant_type, client_id and redirect_uri, and code_verifier.

Here’s how we get the values we need:

  • client_id — you should already have this
  • client_secret — get from the App in Twitter
  • redirect_uri — you should already have this
  • grant_type — set this to authorization_code
  • code — get this from the query parameter sent to the callback url
  • code_verifier — set this to challenge since we hardcoded the code_challenge earlier.

Here’s the request we need to send.

app.get('/auth/twitter/callback', async (req, res) => {
// ...
const response = await zlFetch.post(
'https://api.twitter.com/2/oauth2/token',
{
auth: {
username: 'CLIENT_ID',
password: 'CLIENT_SECRET',
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: {
client_id: 'CLIENT_ID',
redirect_uri: 'https://localhost/auth/twitter/callback',
grant_type: 'authorization_code',
code: code,
code_verifier: 'challenge',
},
},
)
console.log(response.body)
})

You should get a response like this:

Step 5: Save the token for subsequent requests

Again, you can save the access token in the browser or the database. We’ll talk about this in detail in a later lesson.

Notice Twitter returns an expires_in value together with the access token. This value tells us when the token expires. It should be saved together with the access token so we know whether it has expired.

We’ll talk about saving the expries_in value as we talk about saving the token.