【发布时间】:2018-05-11 23:23:04
【问题描述】:
我正在尝试在 Angular 2 ( Electron ) 应用程序中实现 OAuth2 身份验证。
我通过在用户单击“登录”按钮后调用的弹出窗口实现这一点。
在弹出窗口中,用户键入他们的凭据并允许访问并返回确认代码,并且我能够捕获重定向请求,这在没有弹出窗口的情况下是无法做到的。
这是有效的实现:
return Observable.create((observer: Observer<any>) => {
let authWindow = new electron.remote.BrowserWindow({ show: false, webPreferences: {
nodeIntegration: false
} });
authWindow.maximize();
const authUrl = AUTHORIZATION_WITH_PROOF_KEY_URL
+ `?client_id=${CLIENT_ID}&response_type=code&scope=api_search&`
+ `redirect_uri=${REDIRECT_URL}&code_challenge=${challenge}&code_challenge_method=S256`;
if (this.clearStorage) {
authWindow.webContents.session.clearStorageData({}, () => {
this.clearStorage = false;
authWindow.loadURL(authUrl);
authWindow.show();
});
} else {
authWindow.loadURL(authUrl);
authWindow.show();
}
authWindow.webContents.on('did-get-redirect-request', (event, oldUrl, newUrl) => {
const code = this.getCode(newUrl, authWindow);
if (!code) {
this.clearStorage = true;
return;
}
this.requestToken({
grant_type: 'authorization_code',
code: code,
code_verifier: verifier,
redirect_uri: REDIRECT_URL
})
.subscribe((response: { access_token: string, refresh_token: string }) => {
observer.next(response);
});
});
// Reset the authWindow on close
authWindow.on('close', () => {
authWindow = null;
});
});
正如您在上面的代码中看到的,我正在创建新的 BrowserWindow:
new electron.remote.BrowserWindow({ show: false, webPreferences: {
nodeIntegration: false
} });
通过这种方法,我可以使用以下开头的代码块来赶上重定向请求:
authWindow.webContents.on('did-get-redirect-request', (event, oldUrl, newUrl) => {
....
}
但如果没有弹出窗口(模态),我无法解决这个问题。
这是我的尝试:
return Observable.create((observer: Observer<any>) => {
let authWindow = electron.remote.getCurrentWindow();
const authUrl = AUTHORIZATION_WITH_PROOF_KEY_URL
+ `?client_id=${CLIENT_ID}&response_type=code&scope=api_search&`
+ `redirect_uri=${REDIRECT_URL}&code_challenge=${challenge}&code_challenge_method=S256`;
if (this.clearStorage) {
authWindow.webContents.session.clearStorageData({}, () => {
this.clearStorage = false;
authWindow.loadURL(authUrl);
});
} else {
authWindow.loadURL(authUrl);
}
authWindow.webContents.on('did-get-redirect-request', (event, oldUrl, newUrl) => {
debugger;
// this is not called, I'm not able to catch up redirect request
});
// Reset the authWindow on close
authWindow.on('close', () => {
authWindow = null;
});
});
通过我的方法,我在当前窗口中从远程 URL 获取登录屏幕,但问题是我无法通过 ('did-get-redirect-request') 事件捕获重定向请求。
我还尝试了“will-navigate”和许多其他的。
【问题讨论】:
-
你成功获得同一个窗口了吗??