5 Steps to Use OAuth in Your App
Tags: oauth, rails, react, spotify
Published: 2019-04-22 16:06:25

---
title: 5 Steps to Use OAuth in Your App
published: true
description: OAuth in Rails and ReactJS with Spotify's Public API
tags: OAuth, Rails, React, Spotify
---

[Stay hydrated out there](https://amzn.to/3S26cJa)

#What is OAuth?

![tinder oauth example](https://thepracticaldev.s3.amazonaws.com/i/zhpq7exsjpvl8ypm9j29.png)

OAuth allows developers to create ultra curated content for specific users. It essentially allows users to grant your application limited permission to access specific, allowed features from another application like Spotify, Facebook Instagram and more. So, developers can work with features and content a user has already curated for his or herself. Searchmicroservices said it, "allows an end user's account information to be used by third-party services, such as Facebook, without exposing the user's password."

You have seen this before. Dating app X would like to access your Instagram images. Music Streaming App Y would like to access your Facebook profile information. The list goes on.

What makes OAuth so interesting, in my opinion, is its ability to curate personalized content which is much more likely to be valuable to a user. Why? With OAuth, the user opts in to let our app integrate certain features of another app they're already using, which we can assume is already providing them with a great deal of value.

#Why Use OAuth?

Imagine an app that helps users create a collage of pictures with friends, and automatically sends those pictures to them on their birthday. Wouldn't it be great if within our app the user had instant access to lists of images with tagged friends without having to open another app? Wouldn't it be cool if they didn't have to leave our app, sort through their posted pictures, manually find those tagged pictures and somehow import them for every friend on every birthday? In this hypothetical example, OAuth would be the portal allowing us to access users' photos and tags (something they already probably care about quite a bit) so we can do all that for them.

#Using OAuth in Your App

In this example, [Jason Basuil](https://dev.to/jasonbasuil) and I connected to the Spotify public API to create MetroBeat, an app that gamifies playlist making by guessing the tempo (BPM) of songs served to them.
 
There are 3 main players in OAuth: **The User** (Stacy), **the Consumer** (MetroBeat), and the **Service Provider** (Spotify). 

###Step 1 -- Get a Client ID and Client Secret

![OAuth rails routes](https://thepracticaldev.s3.amazonaws.com/i/y96e5sie0c4lab4dc31h.png)

[Set up an account](https://developer.spotify.com/dashboard/) through Spotify Developer. The walkthrough is straightforward. They will give you a client ID and Client Secret. Make sure to never reveal these to anyone! You will need to include these in the initial request to Spotify in order to gain an access token and make requests (I'll explain in a sec). An initial request is made to Spotify with encoded versions of the Client ID and Secret. [More details on how you can encode info in Rails](https://medium.com/cedarcode/rails-5-2-credentials-9b3324851336).

###Step 2 --Verify the Consumer Identity to the Service Provider

We set up MetroBeat to redirect to `get '/login', to: "auth#spotify_request"` first thing. `#spotify_request` makes that initial request to Spotify with the Client ID and Secret, verifying it's us, we know each other, and suggesting we should get together for brunch sometime. This redirects Stacy to a prompt that asks if she's cool to allow MetroBeat to access her Spotify account.

![Rails Auth Controller](https://thepracticaldev.s3.amazonaws.com/i/9vodi6cakz1elg92jdw2.png)

This code makes a request to Spotify and contains a redirect to our `get '/user', to: "users#create"`. You'll also notice the body of this request specifies which permissions (scope) we need Stacy to agree to. You can add as many or as few as you need. Best practice requires we not to add any that aren't essential. When Stacy says it's all good, she gets created as a User and is assigned an access token.

###Step 3 -- Create the User and Assign Her an Access Token

Since we made that initial request, we'll get some params back in Spotify's response. We'll need to grab the `params[:code]` from that and include it in our request body, along with the client ID and Secret. We'll make a few more requests to Spotify for a Refresh token and an Access token.

The Consumer (MetroBeat) needs to remind the Service Provider (Spotify) that it's us every time we make a request to Stacy's Spotify info via the Spotify API. This is done by with an **access token**. 

![Refresh and Access Token](https://thepracticaldev.s3.amazonaws.com/i/c8ipdbvd56u8nxszjtqd.png)

When Stacy grants MetroBeat permission to access her Spotify account, we'll need to place this access token in every single request to a Spotify API endpoint.
These `auth_params` will get us back the access and refresh tokens we need to make those requests. The `user_params` contain profile info from Stacy's Spotify account that we can use to authenticate her and get her logged in (like her username and profile image. We can't see her password).

Then, we can create her as a User and make sure to associate those user and auth params to her in the database so we can use them later.

![rails create user](https://thepracticaldev.s3.amazonaws.com/i/fg3w9y6o62bvup4u731j.png)

Spotify's access tokens expire each hour, so we request a new one if Stacy's been playing for about 55 minutes.

###Step 4 -- Request User info from Service Provider API

Now we can make some requests and see the data come to life! We can create new playlists and add songs to them, see song analyses including song tempo, top tracks by country and so much more. 

In order to attach these requests to components and event listeners, we'll move to our ReactJS front end.

![React fetch user](https://thepracticaldev.s3.amazonaws.com/i/h8ymf7ukfhw2js8471bw.png)

![React fetch playlists](https://thepracticaldev.s3.amazonaws.com/i/dty9wiln0at37erlccag.png)

![React create playlist](https://thepracticaldev.s3.amazonaws.com/i/n56udsoxzahp1dfaueei.png)

######*users[1] was hard-coded in some areas initially, only for testing purposes*

We made other requests (to get song analysis info, for instance) but the sky's the limit. **You'll need to pay close attention to the Service Provider's request formatting. The headers and body for each request type will need to match their requirements**.

###Step 5 -- Implement Requests in React Components

All that's left to do now is determine when and where to display the info we get back from our requests. Make sure you keep [asynchronous programming](https://eloquentjavascript.net/11_async.html) in mind when planning your requests. You'll need that user info and access token back first before you can make other requests.

![react login button](https://thepracticaldev.s3.amazonaws.com/i/4kt6e4sgltbpyaupy4vp.png)

![react song card](https://thepracticaldev.s3.amazonaws.com/i/okst81sfav8w582yv43n.png)

#Conclusion

OAuth is a super interesting and secure technology that can help you create convenient, curated, tailored content that actually matters to users. The User, Consumer and Service Provider work closely through the entire process, passing access tokens and other vital info back and forth to verify your app and allow you to access a User's info through the Service Provider. Using Rails and React are a great way to make these requests and create a user experience all your own.

[Stay hydrated out there](https://amzn.to/3S26cJa)

But you know what else is nice... [A shiny new mechanical keyboard](https://amzn.to/48GVlcT). 
Click that if you're interested in a good one. 

Or click this for [another cool option](https://amzn.to/48lQTRe).

Or perhaps you have a good one and you want to [spruce it up a bit](https://amzn.to/3RMztpK) (you know I did).