有问题的代码取自CodeSandbox:React OAuth Popup Examples and Templates
在 OAuth 2.0 中,有两个流程:
React OAuth 弹出窗口的目标:
只对处理 OAuth2 流程的第一部分感兴趣: Request authorization_code, 收到后关闭Popup
redirect_uri
.
request=code
, redirect_uri
.redirect_uri
为前缀的响应。redirect_uri
为前缀并获取响应 HTTP 状态代码。Google 登录页面的 React OAuth 弹出视图,通过 OAuth URL 引用
redirect_uri
baseURL:https://services.dev.docusign.netredirect_uri
baseURL的弹出URL:https://services.dev.docusign.netReact Post Google 登录响应,弹出 URL redirect_uri
代码:使用 AppOAuthPopup
const authURL= "https://accounts.google.com/o/oauth2/v2/auth/...
+ redirect_uri=https://services.dev.docusign.net..."
<AppOAuthPopup
url={authURL}
onCode={doOAuthPopupOnCode}
onClose={doOAuthPopupOnClose}
title="Auth"
>
<Button
text="CONNECT"
type="button"
/>
代码:AppOAuthPopup
export class AppOAuthPopup extends PureComponent<Props> {
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>;
}
}
Code AppOAuthPopup onCode, onClose
就到这里了,不知道该考虑什么代码了
const doOAuthPopupOnCode = () => {
try {
console.log('doOAuthPopupOnCode TRY');
} catch (error) {
console.log('doOAuthPopupOnCode ERROR', JSON.stringify({ error }, null, 2));
} finally {
console.log('doOAuthPopupOnCode FINALLY');
window.localStorage.removeItem('code'); //remove code from localStorage
}
};
const doOAuthPopupOnClose = () => {
console.log('doOAuthPopupOnClose');
};
目标:
redirect_uri
为前缀并获取响应 HTTP 状态代码。谢谢