Spotify API Authentication with Spring Boot and React

Bret Gibson
7 min readNov 10, 2020

--

Warning! This is a long one, buckle in!

For my latest project, I decided to tackle something I had always wanted to try: an app utilizing the Spotify API. The first major hurdle of doing this is using the API to handle user authentication. After registering my project with Spotify (which you can do here), I went directly to the authentication page of the Spotify API docs (which are GREAT by the way, might be a good idea to check them out before going through this post).

After reading the instructions in the docs and looking through the example code they had, I found that the whole authorization process still wasn’t quite sticking. Also, they use Node in their example and I was having trouble mapping some things to my own Java/React app.

So, I took to Google and Youtube to see if I could find people that also had issues so I could read about their solutions and use it to figure things out. To my surprise, it was really hard to find information that really matched what I needed!

This blog will be me sharing what took me a lot of searching different sources to figure out to hopefully save you some time!

Also, the main aspect of this project is to help me learn the Spring Boot Java framework (I have always used Ruby on Rails in the past). The way I have things set up are probably not the proper or best way to do them and there is a good chance they change sometime in the future. HOWEVER, currently, the set up I will go through below works well enough for me to get what I need to start working on my front end, so I am rolling with it. Also, hopefully it will help you to better wrap your head around the process so you can adapt it to your needs.

MUST READ:

I will be !HEAVILY! using a Spotify API Java library that is a Java wrapper for Spotify API functions. It is required if you want to use code from my examples in your own learning.

Using this library helped me out greatly, and the github for the library even has authorization examples that I used to help me get things up and running.

Spotify Java Web API Github

1.

Go to your app on the Spotify developer dashboard and click “edit settings”.

2.

In the settings menu, find “Redirect URIs” and enter the URI that you want Spotify to redirect to after a user authenticates through the Spotify authentication page. This should be directed to your BACKEND and the end point can be whatever you want, but you will eventually need to map to this endpoint in your backend.

For my app, I have Spotify redirecting to: “http:localhost:8080/api/get-user-code/”.

3.

Alright, let’s get to the code. First, to give you an idea as to how things work, I’ll show you how I’m testing things out. I have a simple web page that just has a button on it that when clicked, should prompt the user to login in with Spotify.

4.

Now to the backend. In my Spring Boot backend, I created a controller called AuthController to handle all the Spotify API auth stuff.

I took a lot of direction for these parts from the auth examples on the Spotify API Java library’s github. Here is the first bit of set up:

So, I have a “redirectURI” for the Spotify redirect URI (It HAS TO MATCH what was entered into the settings from your Spotify developer dashboard in step 2 above) and a “code” for the user access code which will eventually ask Spotify for a user access token. The “SpotifyHttpManager” part comes from the library.

Then, I am setting up a SpotifyApi object (supplied by the library) so that it contains the required fields for sending requests to the Spotify API, my Client ID (hidden in an enum I created), Client Secret (hidden in an enum I created), and the Redirect URI (which we defined already). We will also be able to use this object in the future when we need to make further adjustments to the data related to the API or when we eventually request user stats.

Next, I have this spotifyLogin method that has a GetMapping to the route “/api/login”. Also, using @ResponseBody will ensure that what the method returns is returned in the response body. We are again taking advantage of the library and using its AuthorizationCodeUriRequest class to generate a URI that will prompt the user to authorize their account.

The scope is the level of access the user will need to authorize for us to be able to retrieve certain data on their behalf (you can find out what kinds of access are need for certain API requests in the API docs). The show_dialog(true) part just means that when the user visits the supplied link, they are directed to a web page from Spotify telling them that our app is requesting access.

Finally, I am returning the URI created by the AuthorizationCodeUriRequest creator so that it is sent in the response body (thanks to @ResponseBody) for my front end to receive more easily.

5.

Now, in the front end, I have a method called “getSpotifyUserLogin” that sends a fetch request to the “/api/login” route that we just created above, and uses window.location.replace, taking in the Spotify API authorization URI that should have been returned in the response body of the fetch request to redirect the user to the Spotify API authorization page.

Now, when the button is clicked, the user is redirected to this page:

6.

Now, back to the backend, as we are not quite done with our authentication yet!

When the user clicks the “Agree” button above, Spotify redirects to your predefined redirect URI AND adds a special code inside the redirect URI as a parameter (EX: “http://yourredirect/?code=xxxxxxxx”). I need to use this code to then ask Spotify for a user access token which so that Spotify knows the user has authenticated when making API calls.

So, since my redirect URI is “http://localhost:8080/api/get-user-code/”, I created a getSpotifyUserCode method with a GetMapping to match the redirect URI. In this method I take in a @RequestParam to get the xxxxxxx part of “http://localhost:8080/api/get-user-code/?code=xxxxxxxx” which is the Spotify user code, and an HttpServletResponse so that I can eventually redirect back to our frontend app.

Since I get back the Spotify API user code from the @RequestParam, the first thing I do is set the “code” variable I created in Step 4 to what I get back from that request param.

I then use the AuthorizationCodeRequest class from the Java library to create an authorization code using the “code” variable we just set.

Then, I use that AuthorizationCodeRequest to create AuthorizationCodeCredentials (again a class from the Java library). With these code credentials, I am able to get a Spotify API user access token (authroizationCodeCredentials.getAccessToken())and set the access token in the spotifyApi object so that it is attached to all subsequent requests I make using the spotifyApi object.

Note: A further step can be taken here to refresh tokens, however I am not going to go into that here.

Lastly, I use response.sendRedirect() to redirect to my front end application at the “/top-artists” route.

7. Last Step! Now that I have the user access token, we can finally start to request user specific data from the Spotify API! Let’s get the authorized user’s top artists.

In my backend, I created an endpoint for “http:localhost:8080/api/user-top-artists”. Using the GetUsersTopArtistsRequest class from the Java library, I send a Spotify API request for the user’s top artists adding, a time range, limit of artists, and an offset to the request. This GetUsersTopArtists class is simply builds a URI to the actual Spotify API endpoint: https://api.spotify.com/v1/me/top/{type} and adds the specified parameters.

Then, I execute that request which returns a list (done by “Paging<Artist> artistPaging = getUsersTopArtistsRequest.execute()” above) of information regarding my top 10 recently listened to artist. To send the data to my frontend, I return that list.

Now to the frontend.

I created a TopArtists component to display the top artists returned when a fetch request is sent to the “http://localhost:8080/api/user-top-artists” endpoint. When the component mounts, it sends the fetch request and sets the state of userTopArtists to a JSON object of the user’s top artists.

I then go through all of the artists in the userTopArtists object and simply return an h1 that displays each artist’s name.

Aaaaaand here is the end result of all our hard work! Please forgive some of my music choices…

If you made it this far, you’re a champion! Thanks for reading and I hope this helps some of you out there!

--

--

Responses (2)