如何获得隐式授权流 access_token

How to get Implicit Grant Flow access_token

我正在使用隐式授权流程。问题是在用户授予访问权限后,我无法接受重定向到 redirect_uri 之间的响应。我怎么知道已授予访问权限?以及如何获得access_token的值?

access_token 将在重定向的 url hash 中 URL。

redirect_uri#access_token=

后跟访问令牌。

要获取 access_token,您只需让设置为 redirect_uri 的页面解析 url 并获取哈希。下面的js应该可以做到:

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;

下面是如何实现隐式授权流程的完整代码示例:

// 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`;
}

它获取 URL 的哈希值并检查访问令牌。如果存在 none,它会重定向到 Spotify 授权。

这是一个 Glitch 示例,您可以重新混合以开始使用:https://glitch.com/~spotify-implicit-grant