OAuth弹出式跨域安全React.js

问题描述 投票:6回答:1

我对如何使用弹出窗口(window.open)在React中实现OAuth感兴趣。

例如,我有:

  1. mysite.com-这是我打开弹出窗口的地方。
  2. passport.mysite.com/oauth/authorize-弹出。

主要问题是如何在window.open(弹出窗口)和window.opener之间建立连接(众所周知,由于跨域安全性,window.opener为null,因此我们不能再使用它了。

window.opener每当您导航到其他主机时(出于安全原因)将被删除,无法绕开它。如果可能的话,唯一的选择应该是在框架内付款。顶层文档需要保留在同一主机上。

Scheme:

enter image description here

可能的解决方案:

  1. 使用setInterval中所述的here检查打开的窗口。
  2. 使用cross-storage(不值得,恕我直言)。

那么,2019年推荐的最佳方法是什么?

React包装器-https://github.com/Ramshackle-Jamathon/react-oauth-popup

javascript reactjs oauth popup authorization
1个回答
1
投票

Khanh TO建议。带有localStorage的OAuth弹出窗口。基于react-oauth-popup

Scheme:

enter image description here

代码:

oauth-popup.tsx:

import React, {PureComponent, ReactChild} from 'react'

type Props = {
  width: number,
  height: number,
  url: string,
  title: string,
  onClose: () => any,
  onCode: (params: any) => any,
  children?: ReactChild,
}

export default class OauthPopup extends PureComponent<Props> {

  static defaultProps = {
    onClose: () => {},
    width: 500,
    height: 500,
    url: "",
    title: ""
  };

  externalWindow: any;
  codeCheck: any;

  componentWillUnmount() {
    if (this.externalWindow) {
      this.externalWindow.close();
    }
  }

  createPopup = () => {
    const {url, title, width, height, onCode} = this.props;
    const left = window.screenX + (window.outerWidth - width) / 2;
    const top = window.screenY + (window.outerHeight - height) / 2.5;

    const windowFeatures = `toolbar=0,scrollbars=1,status=1,resizable=0,location=1,menuBar=0,width=${width},height=${height},top=${top},left=${left}`;

    this.externalWindow = window.open(
        url,
        title,
        windowFeatures
    );

    const storageListener = () => {
      try {
        if (localStorage.getItem('code')) {
          onCode(localStorage.getItem('code'));
          this.externalWindow.close();
          window.removeEventListener('storage', storageListener);
        }
      } catch (e) {
        window.removeEventListener('storage', storageListener);
      }
    }

    window.addEventListener('storage', storageListener);

    this.externalWindow.addEventListener('beforeunload', () => {
      this.props.onClose()
    }, false);
  };

  render() {
    return (
      <div onClick={this.createPopup)}>
        {this.props.children}
      </div>
    );
  }
}

app.tsx

import React, {FC} from 'react'

const App: FC = () => {

  const onCode = () => {
    try {
      const res = <your_fetch>
    } catch (e) {
      console.error(e);
    } finally {
      window.localStorage.removeItem('code'); //remove code from localStorage
    }
  }

  return (
    <OAuthPopup
      url={<your_url>}
      onCode={onCode}
      onClose={() => console.log('closed')}
      title="<your_title>">
      <button type="button">Enter</button>
    </OAuthPopup>
  );
};

export default App;
© www.soinside.com 2019 - 2024. All rights reserved.