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

Dynamic state and `code_verifier`

3m:3s

The state variable is a defense against CSRF Attacks (Cross-Site Request Forgery attacks).

The idea is — if you use a random state value, it would be impossible for others to guess this state value, so it would be impossible for them to generate a sign-in link that works on your server.

The same is true for code_verifier. If you use a random code_verifier value, it would be impossible for others to guess this code_verifier value, so code_challenge will be secure on the identity provider’s end.

So you should always generate random state and code_verifier values (unless when you’re learning how they work).

These values can be saved in cookies.

Understanding Cookies

Cookies are small pieces of data that are stored in a browser. This data is sent to the server when the browser makes a request.

Here’s what you need to know:

  • Most cookies are created on the server.
  • Both frontend and server can read and set cookies, but the server has more options. For example, servers can set cookies that the frontend cannot read. These cookies are used to enhance security.

Storing state and code_verifier in cookies

First, you need to point users to a route in your server.

<a class="button" href="/auth/twitter">Login with Twitter</a>

Users will be directed to a route handler when they click on the login button.

In this route handler, we generate the sign-in link and redirect users to the identity provider with res.redirect.

app.get('/auth/twitter', async (req, res) => {
const baseURL = 'https://twitter.com/i/oauth2/authorize'
const params = {
/* ... */
}
const query = new URLSearchParams(params)
const link = baseURL + '?' + query.toString()
res.redirect(link)
})

From a user’s point of view, they won’t know they went to our server, because the next thing they see is the identity provider’s login page.

Before we redirect users to the identity provider, we can save the state and code_verifier values in cookies. We do this with res.cookie.

router.get('/auth/twitter', async (req, res) => {
// ...
res.cookie('state', state)
res.cookie('code_verifier', code_verifier)
res.redirect(link)
})

I recommend adding two more cookie attributes as you set the cookie.

  • httpOnly — ensures browsers cannot view this cookie, which ensures that the cookie value will not be stolen even if someone had access to your frontend JavaScript.
  • secure — ensures cookies are sent only in a HTTPS scheme, which ensures the cookies will not be intercepted in the middle of the request. (This attribute is not required if you already use HTTPS).
router.get('/auth/twitter', async (req, res) => {
// ...
res.cookie('state', state, {
httpOnly: true,
secure: true,
})
res.cookie('code_verifier', code_verifier, {
httpOnly: true,
secure: true,
})
res.redirect(link)
})

Getting state and code_verifier from cookies

When you receive a response from the callbackURL, you can check the cookies for state and code_verifier values.

router.get('/auth/twitter/callback', async (req, res) => {
const { state, code_verifier } = req.cookies
console.log(state)
console.log(code_verifier)
})

We want to check whether the state value stored in the cookie is the same as the state value returned from the identity provider. If both values are the same, we know we’re safe from CSRF attacks.

router.get('/auth/twitter/callback', async (req, res) => {
const { state, code_verifier } = req.cookies
const { state: returnedState, code } = req.query
if (state !== returnedState) return
})

From this point on, you can use code and code_verifier to exchange for an access token.

router.get('/auth/twitter/callback', async (req, res) => {
// ...
const response = await zlFetch.post('...', {
body: {
code,
code_verifier,
// Other values you need to get an access token
},
})
})

That’s it.