【问题标题】:Spotify authentication with implicit grant in React not redirecting after completionSpotify 身份验证与 React 中的隐式授权在完成后不重定向
【发布时间】:2018-07-19 21:29:39
【问题描述】:

我想使用他们文档中的隐式授权方法完成 Spotify 身份验证。我已经将看似相关的代码复制到了 React 组件中。 我设法登录到 Spotify,但页面没有重定向回重定向 uri。

我已将 URI 添加到 Web 控制台的列表中,但即使我确实使用了未注册的 URI,它也不会显示错误。它甚至不尝试重定向。

身份验证后如何让它重定向?

组件是页面上唯一呈现的东西:

import React from "react";

const stateKey = "spotify_auth_state";

const SpotifyLogin = class extends React.Component {
  ComponentDidMount() {
    localStorage.removeItem(stateKey);
  }

  handleClick = () => {
    const client_id = "e5abbee6e0fd4e4bbd080c6d212ca520";
    const redirect_uri = "http://localhost:3000";
    const scope = "user-read-private user-read-email";
    const state = generateRandomString(16);

    localStorage.setItem(stateKey, state);

    const url = `https://accounts.spotify.com/authorize
                 ?response_type=token
                 &client_id=${encodeURIComponent(client_id)}
                 &scope=${encodeURIComponent(scope)}
                 &redirect_uri=${encodeURIComponent(redirect_uri)}
                 &state=${encodeURIComponent(state)}`;

    window.location = url;
  };

  render() {
    return <button onClick={this.handleClick}>Log in</button>;
  }
};

const generateRandomString = length => {
  let text = "";
  const possible =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  while (text.length <= length) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }

  return text;
};

export default SpotifyLogin;

【问题讨论】:

  • 您是否将 redirect_uri 放入了您的 spotify 应用的白名单中?
  • 是的,但即使使用未列入白名单的 URI 也会产生相同的效果。它甚至没有达到无效的 uri 错误。

标签: javascript reactjs authentication client spotify


【解决方案1】:

问题是我使用了多行字符串模板。这使得字符串有几行,并且没有将字符串连接成一行。

修复:

let url = "https://accounts.spotify.com/authorize";
url += "?response_type=token";
url += `&client_id=${encodeURIComponent(client_id)}`;
url += `&scope=${encodeURIComponent(scope)}`;
url += `&redirect_uri=${encodeURIComponent(redirect_uri)}`;
url += `&state=${encodeURIComponent(state)}`;

【讨论】:

    猜你喜欢
    • 2018-11-29
    • 2013-11-15
    • 2019-01-27
    • 2011-09-27
    • 2016-02-15
    • 2014-02-23
    • 2012-03-25
    • 2011-03-12
    相关资源
    最近更新 更多