OAuth popup cross-domain security React.js

前端 未结 2 1249
野趣味
野趣味 2021-02-13 21:19

I\'m interested in how to implement OAuth in React using popup (window.open).

For example I have:

  1. mysite.com — this is where I op
2条回答
  •  既然无缘
    2021-02-13 21:47

    Suggested by Khanh TO. OAuth popup with localStorage. Based on react-oauth-popup.

    Scheme:

    Code:

    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 {
    
      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 (
          
    {this.props.children}
    ); } }

    app.tsx

    import React, {FC} from 'react'
    
    const onCode = async (): Promise => {
      try {
        const res = await 
      } catch (e) {
        console.error(e);
      } finally {
        window.localStorage.removeItem('code'); //remove code from localStorage
      }
    }
    
    const App: FC = () => (
      }
        onCode={onCode}
        onClose={() => console.log('closed')}
        title="">
        
      
    );
    
    export default App;
    

提交回复
热议问题