After all my research and reading Microsoft docs, am unable to conclude how to generate access token using auth code flow in outlook web add-ins. I can successfully generate access token using implicit grant flow with the help of Dialog API which simply opens up URL and we read access token from address bar.
To be more secured , I am trying to generate access token to graph API/(custom SharePoint sites) using registered app in azure utilizing auth code flow.
Azure app Settings: API permissions added under Microsoft Graph. [User.Read, Sites.Read.All] Redirect Web URI: myapp/Auth_Result Redirect SPA URI: myapp/Auth_Result_SPA
Code in Outlook Web add-in:
Using Dialog API I open myapp/Auth page which redirects to
https://login.microsoftonline.com/<Tenant ID>/oauth2/v2.0/authorize
?client_id=<Client ID>
&response_type=code
&redirect_uri=https%3A%2F%2Flocalhost%3A44333%2FAuth_result.html
&response_mode=query&scope=https%3A%2F%2Fgraph.microsoft.com%2Fuser.read
&state=12345
The above URL generates Authorization code in redirected page myapp/Auth_result which is read.
Code in Auth_Result page
function GetAccessToken(authCode) {
try {
var url = 'https://login.microsoftonline.com/<Tenant ID>/oauth2/v2.0/token';
var params = 'client_id=<Client ID>&scope=https%3A%2F%2Fgraph.microsoft.com%2Fuser.read&code=' + authCode + '&redirect_uri=https://localhost:44333/Auth_Result_SPA.html&grant_type=authorization_code';
var xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function (result) {
AccessTokenCallback(result);
}
xhr.send(params);
}
catch{ }
}
The above request fails with
Access to XMLHttpRequest at 'https://login.microsoftonline.com/<Tenant ID>/oauth2/v2.0/token' from origin 'https://localhost:44333' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
MessageRead.js:780 POST https://login.microsoftonline.com/<Tenant ID>/oauth2/v2.0/token net::ERR_FAILED
App domains in Manifest
<AppDomain>https://login.microsoftonline.com/<Tenant ID>/oauth2/v2.0/token</AppDomain>
<AppDomain>https://login.microsoftonline.com</AppDomain>
<AppDomain>https://localhost:44333</AppDomain>
<AppDomain>https://localhost:44333/Auth</AppDomain>
<AppDomain>https://localhost:44333/Auth_Result</AppDomain>
<AppDomain>https://localhost:44333/Auth_Result_SPA</AppDomain>
<AppDomain>https://graph.microsoft.com</AppDomain>
I am not sure what am I missing? Now I am questioning is it even possible to use auth code flow in outlook web add-in?
Guys any suggestions would be helpful.
Thanks
------Edited-------------
I tried above solution with redirect URI as Web platform.
If I use SPA platform redirect URI in azure app Authentication then I get following error:
For some reason image is not coming up. Error Text:
AADSTS9002325: Proof Key for Code Exchange is required for cross-origin authorization code redemption.
[![enter image description here][1]][1]