First to say, auth code grant flow is an interactive authentication, it is interactive login(by user) required. So if you use get request to the url https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/authorize, it will response the html of the login page.
To implement auth code grant flow, you need to use a pop-up window for authenticating. I find a code sample provided below for your reference:
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
`);
In the new browser window, you need to login for authenticating.
Then we need to listen for when it has returned with query parameters in the URL, which contain ?code= and will have the granted code for obtaining access token. You can refer to the code sample below:
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?
}
});
});
After that, you can get the access token in the body of above code(in console.log('Token Received!\n', body); above)