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

Passing access tokens to the browser

3m:40s

It’s slightly harder to use local storage because you need to pass the token to the frontend, before you can save it to local storage.

There are three ways to pass the token:

  1. Use a query string
  2. Render HTML that contains some JS
  3. Use the server as a proxy

We’ll talk about each of these ways and which to choose.

Method 1: Using a query string

This method is straightforward — you pass the access token into a query parameter as you redirect the user to a logged-in page.

router.get('/auth/provider/callback', (req, res) => {
// ...
// Redirects to the frontend
res.redirect(`/logged-in?token=${access_token}`)
})

On this logged-in page, you can grab the access token (in the browser) with URLSearchParams.

// Frontend
if (location.pathname === '/logged-in') {
const searchParams = new URLSearchParams(location.search)
const token = searchParams.get('token')
}

The problem with this method is it exposes the access token in the URL — which is a security concern:

  • People may copy-paste this URL and giveaway their token by accident
  • Attackers may read the access token if they (somehow) get access to the browser’s history.
  • Servers may log URLs into a file. If an attacker (somehow) access this file, they can steal the access token.

Mitigating security concerns

We can mitigate the first and second concerns by overwriting the URL with a new one — one without the query string. We’ll use history.replaceState to do this because replaceState overwrites browser history.

// Frontend
if (location.pathname === '/logged-in') {
const searchParams = new URLSearchParams(location.search)
const token = searchParams.get('token')
// Strips token from the URL so others cannot view them, for security reasons.
history.replaceState('', '', location.pathname)
}

We can mitigate the third concern by deciding how we want the server to log URLs. Learning to do this is outside of the scope of this program.

Method 2: Rendering a HTML with some JavaScript

This method requires you to send HTML that contains some JavaScript. The JavaScript saves to token into local storage and immediately redirects the user to a logged-in page.

router.get('/auth/provider/callback', (req, res) => {
// ...
const html = `
<html>
<script>
localStorage.setItem('token', ${access_token})
location.href = '/logged-in'
</script>
</html>
`
// Redirects to the frontend
res.send(html)
})

This method is really simple, and it’s much more secure compared to method 1.

The only downside is you have to hardcode the redirect url in the server.

Method 3: Use the server as a proxy

This third method requires you to handle the callback_url from the browser

if (location.pathname === '/auth/provider/callback') {
// Handle callback
}

You have to obtain code from URLSearchParams and send it to the server with a Fetch request.

if (location.pathname === '/auth/provider/callback') {
const searchParams = new URLSearchParams(location.search)
const code = searchParams.get('code')
const response = zlFetch.post('/auth/provider/token', {
body: { code },
})
}

The backend will exchange the code value for an access token.

app.post('/auth/provider/token', async (req, res) => {
const { code } = req.body
// Get access token
const response = await zlFetch.post(
'https://provider.com/oauth/access_token',
{
body: {
client_id: clientID,
client_secret: clientSecret,
code,
},
}
)
})

When the identity provider returns the access token, you send it back to your frontend as a JSON value.

app.post('/auth/provider/token', async (req, res) => {
// ...
const response = zlFetch.post(/* ... */)
const token = response.body.access_token
res.json(token)
})

Your frontend then receives the token and saves it to local storage.

if (location.pathname === '/auth/provider/callback') {
// ...
const response = zlFetch.post('/auth/provider/token', {
body: { code },
})
const token = response.body.token
}

This method is secure because you’re not leaking any important credentials. But it’s unwieldy compared to the first two methods mentioned above.

It can get especially unwieldy if you need to include state and code_verifier values.

I don’t recommend method 3.

Summary

You need to pass an access token into the browser before the browser can save them into localStorage.

There are three ways to pass access tokens:

  1. Using a query string
  2. Sending HTML with some JavaScript
  3. Using the server as a proxy

I recommend the 1st method most of the time for ease of use because security concerns can be perfectly mitigated with good practices.

Only choose the 2nd method if you need to make sure the security is super-duper top-notch.