Customized Spotify Authentication - dirkgroenen/mopidy-mopify GitHub Wiki

To integrate Spotify in Mopify I had to 'tweak' the default API authentication system. When working with API's you usually have to fill in a callback URL. This URL will be used to send the authentication tokens to after a user logged in. For security reasons these callback URLs always have to equal to the callback URLs filled in by the developer on the services app page.

This is where a problem raises. Mopify's users will all have an other URL so I can't fill in a default callback URL. So I had to add something extra which will return the authentication tokens to Mopify. The result: an extra, online, page.

This page is running on http://mopify.bitlabs.nl/ and will take care of all API problems like cross origin requests and dynamic callback URLs.

##How it works When Mopify is opened an iframe is inserted in the page. This iframe opens the following URL: http://mopify.bitlabs.nl/auth/spotify/frame/. This page contains the following code:

window.onmessage = function(e) {
    var payload = JSON.parse(e.data);

    switch(payload.method) {
        case 'set':
            localStorage.setItem(payload.key, JSON.stringify(payload.data));
            break;
        case 'get':

            var parent = window.parent;
            var key = localStorage.getItem("spotify-tokens");

            parent.postMessage({
                service: "spotify",
                key: key    
            }, "*");
            break;
        case 'remove':
            localStorage.removeItem(payload.key);
            break;
    }
};

When the user enables the Spotify service it starts sending get requests to this iframe. At the moment the page receives such a message it returns the current value of the localStorage item. Mopify will check that value and if it contains valid tokens it will use them to make the calls.

When the user has logged in to Spotify successfully and granted the permissions Spotify will send an authentication token to http://mopify.bitlabs.nl/auth/spotify/callback/. This page will request a new authentication and refresh token. When it receives those tokens it will save them in the localstorage. At this moment Mopify is still sending get requests to the iframe page.

The localstorage items between the frame and callback pages are shared since they are under the same domain. So when the tokens are received and saved in the localstorage, Mopify will get those tokens and can use them to make further requests.

The refresh token is used to refresh the authentication token so Mopify won't have to show the login popup every time the authentication token is expired.