Skip to content

Instantly share code, notes, and snippets.

@arirawr
Last active December 3, 2021 15:43
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save arirawr/f08a1e17db3a1f65ada2c17592757049 to your computer and use it in GitHub Desktop.
Save arirawr/f08a1e17db3a1f65ada2c17592757049 to your computer and use it in GitHub Desktop.
Basic implicit grant implementation for Spotify API OAuth
// 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`;
}
@devricardogalan
Copy link

Hi arirawr, I'm trying to implement this code on my project but I'm getting some errors. I'm learning angular that's why my question may sound stupid. So I've been trying to do this auth flow but I've been getting some CORS errors, and I found this code, I'm trying to implement it on my getTokenFromAPI() method on my service, but I'm getting this errors on typescript.

On your line 15:
Property 'access_token' does not exist on type '{}'

And On your line 30:
Type 'string' is not assignable to type 'Location'

` getTokenFromAPI() {
// 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 = this.clientId;
const redirectUri = 'http://localhost:4200/#/home';
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;
}
}`

I really would appreciate if you helped me, thank you so much in advanced.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment