首先要说,auth code grant flow 是一种交互式身份验证,它需要交互式登录(由用户)。所以如果你使用get请求到urlhttps://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/authorize,它会响应登录页面的html。
要实现验证码授权流程,您需要使用弹出窗口进行验证。我找到下面提供的代码示例供您参考:
this.authWindow = new BrowserWindow(
{
alwaysOnTop : true, // keeps this window on top of others
webPreferences : {
nodeIntegration : false, // again, don't need to specify these if Electron v4+ but showing for demo
contextIsolation : true // we can isolate this window
}
}
);
this.authWindow.on('closed', () => {
this.authWindow = null;
});
authWindow.loadURL(`
https://login.microsoftonline.com/${config.auth.tenantId}/oauth2/v2.0/authorize?
client_id=xxxxxxx
&response_type=code
&redirect_uri=xxxxxxx
&response_mode=query
&scope=xxxxxxx
`);
在新的浏览器窗口中,您需要登录进行身份验证。
然后我们需要监听它何时返回 URL 中的查询参数,其中包含 ?code= 并且将具有用于获取访问令牌的授权代码。您可以参考下面的代码示例:
authWindow.webContents.on('did-finish-load', () => {
session.defaultSession.webRequest.onCompleted({ urls: [`{redirect_uri}/?code=` + '*'] }, details => {
const _url = details.url.split('?')[1]; // get the equivalent of window.location.search for the URLSearchParams to work properly
const _params = new URLSearchParams(_url);
const _accessCode = _params.get('code');
if (_accessCode) {
const tokenRequestUrl = `https://login.microsoftonline.com/${config.auth.tenantId}/oauth2/v2.0/token`;
const tokenRequestBody = {
grant_type : 'authorization_code',
client_id : xxxxxxx,
code : _accessCode,
redirect_uri : xxxxxxx,
scope : xxxxxxx,
client_secret : xxxxxxx //Only required for web apps
};
request.post(
{ url: tokenRequestUrl, form: tokenRequestBody },
(err, httpResponse, body) => {
if (!err) {
console.log('Token Received!\n', body);
} else {
// Probably throw an error?
}
}
);
} else {
// Probably throw an error?
}
});
});
之后,你可以在上面代码的body中获取访问令牌(在上面的console.log('Token Received!\n', body);中)