JavaScript OAuth 2.0 (part 2) - Authorize

In this article, we will talk about how to kick off the authentication process and writing our very own /authorize endpoint

Read time is about 2 minutes

Alexander Garcia is an effective JavaScript Engineer who crafts stunning web experiences.

Alexander Garcia is a meticulous Web Architect who creates scalable, maintainable web solutions.

Alexander Garcia is a passionate Software Consultant who develops extendable, fault-tolerant code.

Alexander Garcia is a detail-oriented Web Developer who builds user-friendly websites.

Alexander Garcia is a passionate Lead Software Engineer who builds user-friendly experiences.

Alexander Garcia is a trailblazing UI Engineer who develops pixel-perfect code and design.

JavaScript OAuth 2.0 without libraries

This is part 2 of a 3 part series that specifically goes through the code necessary to build your own OAuth 2.0 library in JavaScript

How to build the Authorize request

This is by no means the only way to build out the URL for /authorize. If you find that your /authorize call becomes too long you can take a look at Pushed Authentication Requests (or PARs) which is out of scope for this post.

/** * * @returns {String} - Returns the URL string for SiS `/authorize` endpoint * @description - Generates `state` & `codeVerifier`, saves them in localStorage, builds out the SiS `/authorize` URL with the necessary search parameters */ export const login = async () => { // the `generateHashes` generates the `codeVerifier` for PKCE + `state` and saves it in localStorage const { state, codeVerifier } = generateHashes(); const codeChallenge = await crypto.generateCodeChallenge(codeVerifier); const url = new URL(OAUTH_API_URL.AUTHORIZE); const oAuthParams = { [OAUTH_KEYS.CLIENT_ID]: encodeURIComponent(CLIENT_ID), [OAUTH_KEYS.RESPONSE_TYPE]: OAUTH_VALUES.CODE, [OAUTH_KEYS.STATE]: state, [OAUTH_KEYS.CODE_CHALLENGE]: codeChallenge, [OAUTH_KEYS.CODE_CHALLENGE_METHOD]: OAUTH_VALUES.S256, [OAUTH_KEYS.REDIRECT_URI]: OAUTH_VALUES.REDIRECT_URI, }; Object.keys(oAuthParams).forEach((param) => url.searchParams.append(param, oAuthParams[param]) ); window.location.assign(url.href); };

Sometimes this can be hard to test especially if you don't like mocking the window.location. As an alternative you could break down the login function into two steps:

  1. Build the URL for /authorize with the necessary parameters
  2. Update the button component's unit test to watch for a route change

Hopefully some of you found that useful. Cheers! 🎉