Reactjs Spotify隐式授权流与React-用户登录

Reactjs Spotify隐式授权流与React-用户登录,reactjs,spotify,Reactjs,Spotify,下面的React组件使用将应用程序连接到Spotify,在为用户获取令牌后将应用程序重定向回我的客户端 import React, { Component } from 'react'; import Credentials from './spotify-auth.js' import './Spotify.css' class SpotifyAuth extends Component { constructor (props) { super(props); t

下面的React组件使用将应用程序连接到Spotify,在为用户获取令牌后将应用程序重定向回我的客户端

import React, { Component } from 'react';
import Credentials from './spotify-auth.js'
import './Spotify.css'


class SpotifyAuth extends Component {  
  constructor (props) {
    super(props);
    this.state = {
      isAuthenticatedWithSpotify: false,
      menu: this.props.userId.menu
    };
    this.state.handleRedirect = this.handleRedirect.bind(this);
  };


  generateRandomString(length) {
    let text = '';
    const possible =
      'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    for (let i = 0; i < length; i++) {
      text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    return text;
    } 

  getHashParams() {
    const hashParams = {};
    const r = /([^&;=]+)=?([^&;]*)/g;
    const q = window.location.hash.substring(1);
    let e = r.exec(q);
    while (e) {
      hashParams[e[1]] = decodeURIComponent(e[2]);
      e = r.exec(q);
    }
    return hashParams;
  }

  componentDidMount() {
    //if (this.props.isAuthenticated) {
    const params = this.getHashParams();

    const access_token = params.access_token;
    const state = params.state;
    const storedState = localStorage.getItem(Credentials.stateKey);
    localStorage.setItem('spotifyAuthToken', access_token);
    localStorage.getItem('spotifyAuthToken');

    if (window.localStorage.getItem('authToken')) {
      this.setState({ isAuthenticatedWithSpotify: true });
    };
    if (access_token && (state == null || state !== storedState)) {
      alert('Click "ok" to finish authentication with Spotify');
    } else {
      localStorage.removeItem(Credentials.stateKey);
    }
    // DO STUFF WITH ACCEES TOKEN HERE
    this.props.onConnectWithSpotify(access_token); 
  };

  handleRedirect(event) {
    event.preventDefault()
    this.props.createMessage('You linked your Spotify account!', 'success');

    const params = this.getHashParams();
    const access_token = params.access_token;
    console.log(access_token);

    const state = this.generateRandomString(16);
    localStorage.setItem(Credentials.stateKey, state);

    let url = 'https://accounts.spotify.com/authorize';
    url += '?response_type=token';
    url += '&client_id=' + encodeURIComponent(Credentials.client_id);
    url += '&scope=' + encodeURIComponent(Credentials.scope);
    url += '&redirect_uri=' + encodeURIComponent(Credentials.redirect_uri);
    url += '&state=' + encodeURIComponent(state);
    window.location = url; 
  };

  render() {
      return (
        <div className="button_container">
            <h1 className="title is-4"><font color="#C86428">Welcome</font></h1>
            <div className="Line" /><br/>
              <button className="sp_button" onClick={(event) => this.handleRedirect(event)}>
                <strong>LINK YOUR SPOTIFY ACCOUNT</strong>
              </button>
        </div>
      )
  }
}
export default SpotifyAuth;
import React,{Component}来自'React';
从“./spotify auth.js”导入凭据
导入“./Spotify.css”
类SpotifyAuth扩展组件{
建造师(道具){
超级(道具);
此.state={
isAuthenticatedWithSpotify:false,
菜单:this.props.userId.menu
};
this.state.handleRedirect=this.handleRedirect.bind(this);
};
GeneratorDomainString(长度){
让text='';
常数可能=
‘ABCDEFGHIJKLMNOPQRSTUVXYZABCDFGHIJKLMNOPQRSTUVXYZ0123456789’;
for(设i=0;i
this.handleRedirect(事件)}>
链接您的SPOTIFY帐户
)
}
}
导出默认的SpotifyAuth;
但是,在重定向之前,我想描述以下页面或弹出窗口,其中包含定义的范围和“同意”按钮:



根据Spotify docs for,将用户重定向到
https://accounts.spotify.com/authorize?client_id=5fe01282e94241328a84e7c5cc169164&redirect_uri=http:%2F%2Fexample.com%2Fcallback&scope=user-读取私人%20用户读取电子邮件和响应\u type=token&state=123

…执行两个操作:

用户被要求在作用域内授权访问。Spotify Accounts>服务提供正在寻求访问的作用域的详细信息。 如果用户未登录,系统会提示他们使用Spotify>用户名和密码登录。 当用户登录时,会要求他们授权访问范围中定义的数据集>

当我调用
https://accounts.spotify.com/authorize?
,我刚拿到令牌

怎么了


我发现了这个codepen示例,其中提示用户登录页面:

如何将此功能添加到上面的组件?

注意: 一旦您使用一个电子邮件id接受了范围,您将不会再次显示范围页面。范围在开始时只被询问一次。如果要再次查看范围页面,则必须授权新的电子邮件id。

我已经创建了一个react应用程序来感受你的代码是如何工作的。我运行了以下代码:

import React, { Component } from 'react';

export const authEndpoint = 'https://accounts.spotify.com/authorize';
class SpotifyAuth extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isAuthenticatedWithSpotify: false
      // menu: this.props.userId.menu
    };
    this.state.handleRedirect = this.handleRedirect.bind(this);
  }

  generateRandomString(length) {
    let text = '';
    const possible =
      'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    for (let i = 0; i < length; i++) {
      text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    return text;
  }

  getHashParams() {
    const hashParams = {};
    const r = /([^&;=]+)=?([^&;]*)/g;
    const q = window.location.hash.substring(1);
    let e = r.exec(q);
    while (e) {
      hashParams[e[1]] = decodeURIComponent(e[2]);
      e = r.exec(q);
    }
    return hashParams;
  }

  componentDidMount() {
    //if (this.props.isAuthenticated) {
    const params = this.getHashParams();

    const access_token = params.access_token;
    const state = params.state;
    const storedState = localStorage.getItem('stateKey');
    localStorage.setItem('spotifyAuthToken', access_token);
    localStorage.getItem('spotifyAuthToken');

    if (window.localStorage.getItem('authToken')) {
      this.setState({ isAuthenticatedWithSpotify: true });
    }
    if (access_token && (state == null || state !== storedState)) {
      alert('Click "ok" to finish authentication with Spotify');
    } else {
      localStorage.removeItem('stateKey');
    }
    console.log(access_token);
    // DO STUFF WITH ACCEES TOKEN HERE
    // this.props.onConnectWithSpotify(access_token);
  }

  handleRedirect(event) {
    event.preventDefault();
    console.log('You linked your Spotify account!', 'success');

    const params = this.getHashParams();
    const access_token = params.access_token;
    console.log(access_token);

    const state = this.generateRandomString(16);
    localStorage.setItem('stateKey', state);

    // let url = 'https://accounts.spotify.com/authorize';
    // url += '?response_type=token';
    // url +=
    //   '&client_id=' + encodeURIComponent('f09fbf600009433dadce5836c57584c3');
    // url += '&scope=' + encodeURIComponent('user-top-read');
    // url += '&redirect_uri=' + encodeURIComponent('http://localhost:3000/abc');
    // url += '&state=' + encodeURIComponent(state);
    // url += '&show_dialog=true';
    let url =
      'https://accounts.spotify.com/authorize' +
      '?response_type=code' +
      '&client_id=f09fbf600009433dadce5836c57584c3' +
      '&scope=' +
      encodeURIComponent('user-read-private%20user-read-email') +
      '&redirect_uri=' +
      encodeURIComponent('http://localhost:3000/loginsuccess');
    window.location = url;
  }

  render() {
    return (
      <div className="button_container">
        <h1 className="title is-4">
          <font color="#C86428">Welcome</font>
        </h1>
        <div className="Line" />
        <br />
        <button
          className="sp_button"
          onClick={(event) => this.handleRedirect(event)}
        >
          <strong>LINK YOUR SPOTIFY ACCOUNT</strong>
        </button>
      </div>
    );
  }
}

export default SpotifyAuth;
import React,{Component}来自'React';
导出常量authEndpoint=https://accounts.spotify.com/authorize';
类SpotifyAuth扩展组件{
建造师(道具){
超级(道具);
此.state={
isAuthenticatedWithSpotify:false
//菜单:this.props.userId.menu
};
this.state.handleRedirect=this.handleRedirect.bind(this);
}
GeneratorDomainString(长度){
让text='';
常数可能=
‘ABCDEFGHIJKLMNOPQRSTUVXYZABCDFGHIJKLMNOPQRSTUVXYZ0123456789’;
for(设i=0;i