1
votes

i'm using the Implicit grant flow to use Spotify API with AngularJS, but i can't have my access_token.

I implemented implicit grant flow this way :

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 = 'bcb7a7...13727c';
const redirectUri = 'http://localhost/~mathieu/';
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`;
}

When i go on the url, i am well redirected to the Spotify authentification, but when i connect, the browser enters in a loop of redirection : spotify redirects me to localhost/~mathieu which redirects me to spotify etc...

I suppose that after Spotify redirects me, my script can't get the token so i am redirected again, but i can't find a solution.

Please, help me

1
Why is this tagged angular? - Jacopo Sciampi
You're right, angularjs tag is better, thanks Oh, maybe you ask why angularjs ? Because i want to use the Spotify API in an angularJS project, and since i don't know the source of the issue, i prefer to give all the informations. - Mathieu
You could use an OAuth library for Angular, instead of managing this on your own, maybe. - Zlatko
I followed the Spotify api documentation, you mean I can have access_token in an easier way ? - Mathieu
No no, I just cliecked this question because of the angular tag and then I've red that you are doing this in angularJS. - Jacopo Sciampi

1 Answers

0
votes

If you're using a router in angular, it's likely that the router strips the hash of the URL before this code can grab the value out of it. You need to make sure that this code runs before your angular router code runs. Alternatively you can hook into the angular router and retrieve the hash there. This question seems to suggest that's possible.