使用Spotify弹出窗口实现登录 [英] Implement Log In With Spotify Popup

查看:18
本文介绍了使用Spotify弹出窗口实现登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我想在我的网站上实现使用Spotify功能登录,但我不想将用户重定向到不同的页面,我只想打开一个弹出窗口。我想要的行为的一个例子可以在https://developer.spotify.com中找到。在那里,当您点击登录时,会打开一个弹出窗口,这样您就可以在没有任何重定向的情况下登录Spotify。

推荐答案

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

  1. 打开一个弹出窗口,打开/api/Authorize。一旦用户允许该应用程序,它会将他重定向到回调页面。
  2. 在回调页面,使用返回的授权码(GET参数code),通过POST请求/api/Token(查看文档)生成访问/刷新令牌。这应该在服务器端完成,因为它需要发送客户端ID和客户端密钥。
  3. 将访问/刷新令牌存储在本地存储中并关闭弹出窗口。
  4. 检测关闭事件,从本地存储获取令牌并将其用于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();

这篇关于使用Spotify弹出窗口实现登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆