Implement Log In With Spotify Popup

生来就可爱ヽ(ⅴ<●) 提交于 2020-08-24 03:51:11

问题


Hi I want to implement a Log In with Spotify feature in my website but I don't want to redirect users to a different page, I would like to just open a popup window. An example of the behavior I want is found at https://developer.spotify.com. There when you click on log in, a pop up window is opened so you can log in with spotify without any redirect.


回答1:


That's how Spotify Developer website does it:

  1. Open a popup window to /api/authorize. Once the user has allowed the application, it will redirect him to the callback page.
  2. On the callback page, use the returned authorization code (GET parameter code) to generate access/refresh tokens by doing a POST request to /api/token (check out the documentation). This should be done on server side because it requires sending client ID and client secret keys.
  3. Store the access/refresh tokens in the localStorage and close the popup.
  4. Detect close event, get the tokens from the localStorage and use them for the API.

Example

Login page:

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

Callback page:

// 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();



回答2:


Following up on Teh's response above. If you don't want to use localStorage, I registered a global window function and simply passed the token as a payload back to parent window. Works well for a pass-through experience like saving playlists.

Popup:

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

Callback Function:

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
  })
}

Callback Page:

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

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

I wrote about this technique in more detail on Medium.



来源:https://stackoverflow.com/questions/45580904/implement-log-in-with-spotify-popup

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!