Jiang Wen
Jiang Wen

Reputation: 57

How to get Implicit Grant Flow access_token

i'm useing Implicit Grant Flow. the problem is after the user grants access, Ican't accept Respond between redirects to redirect_uri. How can I know that granted access? and how to get the value of access_token?

Upvotes: 1

Views: 2237

Answers (2)

arirawr
arirawr

Reputation: 1275

Here's a complete code example of how to implement Implicit Grant flow:

// Get the hash of the url
const hash = window.location.hash
.substring(1)
.split('&')
.reduce(function (initial, item) {
  if (item) {
    var parts = item.split('=');
    initial[parts[0]] = decodeURIComponent(parts[1]);
  }
  return initial;
}, {});
window.location.hash = '';

// Set token
let _token = hash.access_token;

const authEndpoint = 'https://accounts.spotify.com/authorize';

// Replace with your app's client ID, redirect URI and desired scopes
const clientId = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
const redirectUri = 'http://localhost:8888';
const scopes = [
  'user-read-birthdate',
  'user-read-email',
  'user-read-private'
];

// If there is no token, redirect to Spotify authorization
if (!_token) {
  window.location = `${authEndpoint}?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scopes.join('%20')}&response_type=token`;
}

It grabs the hash of the URL and checks for an access token. If none is present, it redirects to Spotify authorization.

Here's a Glitch example that you can remix to get started: https://glitch.com/~spotify-implicit-grant

Upvotes: 4

Ed Smilovici
Ed Smilovici

Reputation: 304

The access_token will be in the url hash of the redirect URL.

redirect_uri#access_token=

followed by the access token.

To get the access_token you just have to have the page you set as your redirect_uri parse the url and get the hash. The following js should do it:

function parseURLHash () {
    var search = location.hash.substring(1);
    var urlHash = search?JSON.parse('{"' + search.replace(/&/g, '","').replace(/=/g,'":"') + '"}',
                     function(key, value) { return key===""?value:decodeURIComponent(value) }):{}
    return urlHash;
}
urlHash = parseURLHash();
var authToken = urlHash.access_token;

Upvotes: 0

Related Questions