Acquiring the Auth Code
Tags: javascript, firebase, spotify, webdev
Published: 2022-05-11 20:50:10

_I'm building this project with [NextJS](https://nextjs.org/) and [Google Firebase](https://firebase.google.com/docs/web/setup). If you're following along, follow these getting started guides first, as well as create a [Spotify Application](https://developer.spotify.com/dashboard/login)._

##What is OAuth anyway

> The OAuth 2.0 authorization framework enables a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party application to obtain access on its own behalf.

<u>_[-Internet Engineering Task Force](https://datatracker.ietf.org/doc/html/rfc6749)_</u>

First, let's go over the basics of the OAuth 2.0 flow because that's what took me the longest to understand.

There are many different approaches to OAuth called `Grant Types`. You can read more about Grant Types [here.](https://oauth.net/2/grant-types/) I chose the `Authorization Code` so users only have to grant access to their Spotify account once.

Think of it like a bartender trying to serve a patron a drink. Before the bartender serves them, they have to make sure they're old enough to have permission to serve them. They do that by checking the ID issued to the patron by a governing authority. The patron has to prove to the authorities that they are old enough to drink, then present that proof to a bartender to be served. Our User has to prove to Spotify that they are who they say they are and the `Auth Code` is proof of that. They then present that proof to our server so we can make API calls on their behalf.

If that doesn't make any sense, maybe this flow chart will.
![Graphic Explanation of Authorization Code OAuth grant](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s871i5qmu8dur66ypmfc.png)

As you can see, everything revolves around the `Auth Code`, a special string the user receives after logging into Spotify. We later use this `Auth Code` to verify with Spotify that the User has permitted us to access their account.

So our first step in getting this `Auth Code` is to ask the user to sign in. We do this by generating a special URL that redirects the user to Spotify's website to log in.

## Crafting the URL

When we prompt the user to log in with Spotify, we have to send them to a specific URL for them to do so. I'm building this project with React so I built a component that does specifically this.

```
import * as React from "react";
import { useRouter } from "next/router";
import { v4 as uuidv4 } from "uuid";
import * as queryString from "query-string";

const SpotifyLoginButton = () => {
  const router = useRouter();

  const spotifyQueryParams = {
    response_type: "code",
    client_id: process.env.NEXT_PUBLIC_SPOTIFY_CLIENT_ID,
    scope: "playlist-read-private playlist-modify-private user-read-email",
    redirect_uri: process.env.NEXT_PUBLIC_REDIRECT_URI,
    state: uuidv4(),
  };
  const spotifyOAuthRoute =
    "https://accounts.spotify.com/authorize?" +
    queryString.stringify(spotifyQueryParams);

  const handleClick = (e) => {
    e.preventDefault();
    router.push(spotifyOAuthRoute);
  };

  return <button onClick={handleClick}>Login with Spotify</button>;
};

export default SpotifyLoginButton;
```

Pay special attention to the `spotifyQueryParams`. These values are how we generate the special URL. You can learn more [here](https://developer.spotify.com/documentation/general/guides/authorization/code-flow/), but I'll go over what each value means.


- `response_type:` indicates we want an Auth Code returned to the user


- `client_id:` is the ID of our [Spotify Application](https://developer.spotify.com/dashboard/), this is required for Spotify to register our server before accessing their API

- `scope:` indicates the specific permissions we need the user to grant us, [read more](https://developer.spotify.com/documentation/general/guides/authorization/scopes/)

- `redirect_uri:` is the URL Spotify send the user back to with the Auth Code. This value must be set in the settings of your Spotify Application, I'm using local host now for development

- `state:` this helps prevent attacks like cross-site request forgery

After setting those values our User is ready to log in! I'm using [query-string](https://www.npmjs.com/package/query-string) to stringify the URL. Notice the URL starts with `https://accounts.spotify.com/authorize?`. The next part of the process happens on Spotify's servers, our site never sees the user's username or password. Our site only sees the `Auth Code` for now.

I used `useRouter()` to push the user to our login URL. I used a Button and function instead of an Anchor element because I wanted the user to know they're taking an action, not just following a link. Next, the user will see a screen like this,

![The Spotify login page prompting the user to grant us permissions on their account](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/toziv3jdpctg16ah8dmg.png)
 
After the User agrees to grant us permission, they'll be returned to the `redirect_uri` we specified with their Auth Code in the URL. Finally, we have the fabled Auth Code!

Now, what do we do with it? In my next post, I'll be detailing what we do with the `auth code` and the part it plays in our project.