不带后端的OAuth 2.0隐式流程与React

时间:2018-11-22 18:00:40

标签: javascript reactjs oauth oauth-2.0 frontend

我正在尝试使用OAuth 2.0隐式流连接到服务,这是因为我正在检查新打开的窗口的URL以查看它是否包含访问令牌,但是我得到这个错误

SecurityError:阻止了源为“ http://localhost:3000”的框架访问跨域框架。

这是有道理的,但我不知道还有其他方法。

我也尝试使用window.location获取url,尽管结果相同

您知道我在做什么错吗?

这是我的代码:

import React from "react";
import { connect } from "react-redux";

import { Login } from "./actions";

class Connection extends React.Component {
  constructor(props) {
    super(props);

    this._logIn = this.logIn.bind(this);
  }

  checkPopup() {
    const check = setInterval(() => {
      const { popup } = this;
      console.log(popup.location)
      if (!popup || popup.closed || popup.closed === undefined) {
        clearInterval(check);
        this.props.Login("RESET");
      } else if (popup.document.url.includes("access_token")) {
        let url = popup.document.url;
        console.log(url);
        let token = url.substring(
          url.indexOf("#access_token=") + 14,
          url.indexOf("&state")
        );
        console.log(token);
        this.props.Login("SUCCESS", token);
      }
    }, 100);
  }

  logIn() {
    const width = 600,
      height = 600;
    const left = window.innerWidth / 2 - width / 2;
    const top = window.innerHeight / 2 - height / 2;

    const url = "****";
    const clientId = "****";
    const redirect = "http%3A%2F%2F127.0.0.1:3000";
    const state = Math.floor(Math.random() * Math.floor(10000000));

    const generatedUrl = `${url}?response_type=token&client_id=${clientId}&redirect_uri=${redirect}&scope=voice&state=${state}`;

    this.popup = window.open(
      generatedUrl,
      "",
      `toolbar=no, location=no, directories=no, status=no, menubar=no, 
    scrollbars=no, resizable=no, copyhistory=no, width=${width}, 
    height=${height}, top=${top}, left=${left}`
    );

    this.checkPopup();
  }

  render() {
    return (
      <Modal show={true}>
        <Modal.Card>
          <Modal.Card.Body>
            <Heading>Test</Heading>
          </Modal.Card.Body>
          <Modal.Card.Foot>
            <p href="" className="link" onClick={this._logIn}>
              Log in
            </p>
          </Modal.Card.Foot>
        </Modal.Card>
      </Modal>
    );
  }
}

const mapStateToProps = state => {
  return {
    error: state.connection.error
  };
};

const mapDispatchToProps = { Login };

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Connection);

0 个答案:

没有答案