Authentication And Login Popup Window Handling For Social Media APIs [code example]

Authentication And Login Popup Window Handling For Social Media APIs [code example]

Reading Time: 12 minutes

This post will show how to handle user login to different social medias (for now the example is for Spotify Web API, but the idea is the same for most of the apps).
So lets say you are building great Gallery App using the Instagram API, or maybe an awesome music player with Spotify API features, and you want to grab information about user’s profile/images/playlists or whatever. you want to make user’s life easiest as you can UX-wise, and one of the annoying things user faces with web applications is logging in every single time he wants to refresh / open browser / etc. What I’m going to show is first how to handle the login popup and second how to store the key that gives the user the ability to stay logged in even after refreshing browser or restarting computer or whatever action that will require re-login.

So first thing you want to do is to create an app in the Spotify Developers console, create an account and add a new app. you need to grab your client id for running the example.

check out the code on github

If you want to run the code locally you are more than welcome to grab the code from the github repository above, play with it, ruin it, make it better 🙂

I use here regular jQuery lib and it is probably written not the best way you can think of, but we are not building here a real scalable web app. You can easily transform this code into a React component, or Angular directive or whatever.

The structure is very straight forward, we have entry point of index.html which includes index.js, we also have callback_spotify.html with respectively callback_spotify.js file. The callback should be added into you application configuration page in the spotify developers page as in the image:

(sorry image was deleted from old server, if you have troubles please contact me)

This callback URL is the URL Spotify redirects to after login and app approval has been made by the user, the redirect is made with addition of token parameter after hash, so the redirect URL ends up looking something like this: http://localhost:3001/callback_spotify.html#access_token=SOME_VERY_LONG_HASHED_STRING&token_type=Bearer&expires_in=3600 

This is what we get from Spotify and the access_token is what we basically need, this is the key that keeps our client logged in and get his information for our app. This key is private, so keep it in a safe place if you want your app to be secure, we will keep it on the clients end, on the user’s browser local storage.

So lets do some code:

So here we have very basic HTML file and the interesting parts are the div’s with the “spotify-login-form” and “spotify-details” classes, we are going to toggle them and show them based on the user’s login state, logged in or not. One of the divs has only login button and the other (where we later throw user data) has only logout button.

index.js

Here is where magic begins.
First, as I said earlier, we are going to store the auth token we get from Spotify in the user’s browser’s local storage. So the first check is if we have this token, and if true we are invoking the setSpotifyDetailsfunction that get as a parameter the token string (we are going to look at that function later, but for now lets say that it toggles the div that show info of user that is logged in).

Next we are setting an event listener to the click action of the login button. When user wants to log in and clicks the button handleSpotifyConnect function is invoked, lets jump straight to the function’s code. The first thing we do in the function is declaring some constants that we need in order to create the connect window’s URL . Notice that you should replace SPOTIFY_CLIENT_ID =YOUR_CLIENT_ID with your own id that you got from the Spotify Developer Console, and the redirect URL should be the same as we entered to the Spotify Developers Console earlier, as for response type, leave it ‘token’, it tells Spotify that in the response to our request they should pass the token to our callback.

Next thing is the assembling of the URL, nothing special here, we just concatenating the constants we declared earlier. Then we are opening a window with the URL we just created (notice that we are assigning the window to the w variable, this is very important so we have the window reference on our side, this is how we handle messaging between windows) and finally we set the event listener to message we have to get back from the window, this message will pass the token that Spotify gave us back to the callback URL (we are going to see the code for the callback URL handler in a moment).

We take the token string and invoke inner function called callback which is doing 2 things, first set the token to the local storage so when user next time refreshes the page we can pull it from there and we won’t have to re-authenticate him every single time page refreshed, and second we invoke the function handleSpotifyConnect we talked about earlier. This function makes a call to the Spotify api, with the token which ensures that the user is authenticated and we have permission to get his data, and we get back users data, we hide the login form and show the user’s username (could be any data we have permission to grab, not only the username) and logout button.

The logout button does 3 simple things, first removes the token from local storage, second removes user data from screen, third show again the login form (button) so the user can re-login.

callback_spotify.html

In this file the only important thing is the include of the callback_spotify.js file we will talk about in a moment, other than that it only shows “loading…” string you can replace with a fancy loader or something.

callback_spotify.js

So here we are first declaring the host url string that we are sending message to, and declaring the hash empty object in which we are going to hold the token key we receive from Spotify. Next there’s a function that take the windows location string after the hash sign and assigns it to the hash object, so lets say the locations string is “http://localhost:3001/spotify_callback.html#token=BLAH” we get and object looks like hash = { token: “BLAH” }. Then we check if the access_token exists in this object and if true we are posting it as a message to the window of the login form index.html and close the current window. You can read about the window messaging here, very very useful and good to know thing there, especially the security concerns.

That’s it, we are now logged in and very very happy 🙂