Spotify API Implicit Grant Flow Authentication Error after some time (401)

71 Views Asked by At

I use the Implicit Grant flow to communicate with the Spotify API in an express project, but after some time it seems like my access_token is expired. But I've read that with Implicit Grant flow, the token wont expire? I tried getting a new one from the Api, when the old one expires, but this didn't work.

(function () {

    var stateKey = 'spotify_auth_state';

    function getHashParams() {
        var hashParams = {};
        var e, r = /([^&;=]+)=?([^&;]*)/g,
            q = window.location.hash.substring(1);
        while (e = r.exec(q)) {
            hashParams[e[1]] = decodeURIComponent(e[2]);
        }
        return hashParams;
    }

    function generateRandomString(length) {
        var text = '';
        var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

        for (var i = 0; i < length; i++) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        }
        return text;
    };

    var userProfileSource = document.getElementById('user-profile-template').innerHTML,
        userProfileTemplate = Handlebars.compile(userProfileSource),
        userProfilePlaceholder = document.getElementById('user-profile');

    oauthSource = document.getElementById('oauth-template').innerHTML,
        oauthTemplate = Handlebars.compile(oauthSource),
        oauthPlaceholder = document.getElementById('oauth');

    var params = getHashParams();

    var access_token = params.access_token,
        state = params.state,
        storedState = localStorage.getItem(stateKey);
    if (access_token == "") {
        access_token = localStorage.getItem('spotifyAuthToken');
    }
    if (access_token && (state == null || state !== storedState)) {

    } else {
        localStorage.removeItem(stateKey);
        if (access_token) {
            $.ajax({
                url: 'https://api.spotify.com/v1/me',
                headers: {
                    'Authorization': 'Bearer ' + access_token
                },
                success: function (response) {
                    userProfilePlaceholder.innerHTML = userProfileTemplate(response);

                    $('#login').hide();
                    $('#loggedin').show();
                }
            });
            localStorage.setItem('spotifyAuthToken', access_token);
        } else {
            $('#login').show();
            $('#loggedin').hide();
        }

        document.getElementById('login-button').addEventListener('click', getAccessToken, false);

        function getAccessToken() {
            var client_id = '7c35e3a74f364538866db979db4f35f1'; // Your client id
            var redirect_uri = 'http://localhost:3000'; // Your redirect uri

            var state = generateRandomString(16);

            localStorage.setItem(stateKey, state);
            var scope = 'user-read-private user-read-email user-read-playback-state app-remote-control user-modify-playback-state user-read-currently-playing streaming';

            var url = 'https://accounts.spotify.com/authorize';
            url += '?response_type=token';
            url += '&client_id=' + encodeURIComponent(client_id);
            url += '&scope=' + encodeURIComponent(scope);
            url += '&redirect_uri=' + encodeURIComponent(redirect_uri);
            url += '&state=' + encodeURIComponent(state);

            window.location.href = url;
        }
    }
})();

In the console I get a 401 Error when making further http requests.

0

There are 0 best solutions below