使用 Spotify 弹出窗口实现登录

Implement Log In With Spotify Popup

您好,我想在我的网站上使用 Spotify 登录功能,但我不想将用户重定向到其他页面,我只想打开一个弹出窗口 window。在 https://developer.spotify.com 中可以找到我想要的行为示例。当您点击登录时,会打开一个弹出窗口 window,因此您可以使用 spotify 登录而无需任何重定向。

Spotify 开发者网站就是这样做的:

  1. 打开 window 到 /api/authorize 的弹出窗口。一旦用户允许该应用程序,它将把他重定向到回调页面。
  2. 在回调页面上,使用返回的授权代码(GET 参数 code)通过向 /api/token 发出 POST 请求来生成 access/refresh 令牌(查看文档)。 这应该在服务器端完成,因为它需要发送客户端 ID 和客户端密钥。
  3. 将 access/refresh 令牌存储在 localStorage 中并关闭弹出窗口。
  4. 检测关闭事件,从 localStorage 获取令牌并将它们用于 API。

例子

登录页面:

// Open the auth popup
var spotifyLoginWindow = window.open('https://accounts.spotify.com/authorize?client_id=REPLACE_ME&redirect_uri=REPLACE_ME&response_type=code');

// Close event
spotifyLoginWindow.onbeforeunload = function() {
  var accessToken = localStorage.getItem('sp-accessToken');
  var refreshToken = localStorage.getItem('sp-refreshToken');

  // use the code to get an access token (as described in the documentation)
};

回调页面:

// Assuming here that the server has called /api/token
// and has rendered the access/refresh tokens in the document
var accessToken = "xxx";
var refreshToken = "xxx";
/////////////////////////

// Store the tokens
localStorage.setItem("sp-accessToken", accessToken);
localStorage.setItem("sp-refreshToken", refreshToken);

// Close the popup
window.close();

跟进 Teh 上面的回复。如果您不想使用 localStorage,我注册了一个全局 window 函数并将令牌作为有效负载简单地传递回父 window。非常适合保存播放列表等传递体验。

弹出窗口:

popup = window.open(
  AUTHORIZATION_URL,
  'Login with Spotify',
  'width=800,height=600'
)

回调函数:

window.spotifyCallback = (payload) => {
  popup.close()

  fetch('https://api.spotify.com/v1/me', {
    headers: {
      'Authorization': `Bearer ${payload}`
    }
  }).then(response => {
    return response.json()
  }).then(data => {
    // do something with data
  })
}

回调页面:

token = window.location.hash.substr(1).split('&')[0].split("=")[1]

if (token) {
  window.opener.spotifyCallback(token)
}

我在 Medium 上更详细地介绍了这项技术。