Getting access token using Auth code flow in Outlook web add-in - azure

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]

Looks like the immediate problem is that your Azure AD client needs to be a Single Page App as in step 6 of my post, so that you get past the CORS error.
DESKTOP FLOW?
I believe you are operating within the context of a desktop app (Outlook). If so then the official OAuth option would be to use the following ingredients:
Authorization Code Flow (PKCE)
Use the system browser to login
Listen for the response on a loopback url, such as http://localhost:8000
See my Desktop Tutorial + Code Sample for an example of this

Thanks for your replies, I managed to generate access token using auth code flow. It turned out I wasn't providing code challenge and did not fully understood the flow of authentication particularly for Outlook web add-ins.
The solution is here.
Requirement to make this solution work.
Replace: <Tenant ID> = your tenant id from Azure App registration
Replace: <Client ID> = your client id from Azure App registration
Set https://localhost:44300/Auth_Result_SPA as your redirect URI in Authentication-> SPA platform.
Set Scope to your requirement, and make sure you add the scope in API permissions after registering you application in Azure.
Make sure the app url matches when you load project in visual studio.
app url = SSL URL in TestGraphWeb project properties
Refernces:
Refer this to generate code challenge and code verifier
Refer this for auth code flow information.
This is sample Outlook web add-in with Application Name as "TestGraph". When app is loaded in task pane it will generate access token using Auth code flow silently. This app will pop up dialog if user action is required to generate authentication code. After generating access token it will load page with only button "Refresh Access Token" which will generate new access token and refresh token.

Related

Replicate Postman Oauth 2.0 using Python

I have this Authorization request that works.
How can I replicate it in Python?
I am using an Azure AD to authenticate the access.
Since you are working with python, your case is a : Oauth2 login for SSR web applications with Microsoft
Goal
Get an access_token from interactive login using the oauth2 authorization code grant
Steps
Here I will list all the steps required to do it with any language
Create a web with session with at least these endpoints
/ : home page
/callback : server route or path able to receive query params like /callback?code=123456. This along with your base domain will be called redirect_uri. Sample : http://localhost:8080/callback or http://acme.com/callback
Create and configure an app in Azure Dev Console. Same process is in Google, Facebook, Linkedin, etc. As a result you should have a clientId, clientSecret and a redirect url
Create a simple web with classic session in which if user is not logged-in, redirect (302) to this url:
https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=foo&response_type=code&redirect_uri=foo&response_mode=query&scope=offline_access%20user.read%20mail.read
clientid and redirect_uri are important here and should be the same of previous step
After that, browser should redirect the user to the platform login
If user enters valid credentials and accepts the consent warning, Microsoft will perform another redirect (302) to the provided redirect_uri but with special value: The auth code
http://acme.com/callback?code=123456798
In the backend of /callback get the code and send it to this new endpoint
Add a client_id & client_secret parameters
Add a code parameter with the code sent by microsoft
Add a redirect_uri parameter with previously used and registered on azure. Sample http://acme.com/callback or http://localhost:8080/callback
Add a grant_type parameter with a value of authorization_code
Issue the HTTP POST request with content-type: application/x-www-form-urlencoded
You should get a response with the precious access_token:
{
token_type: 'Bearer',
scope: 'Mail.Read User.Read profile openid email',
expires_in: 5020,
ext_expires_in: 5020,
access_token: 'eyJ0oVlKhZHsvMhRydQ',
refresh_token: 's_Rcrqf6xMaWcPHJxRFwCQFkL_qUYqBLM71UN6'
}
You could do with this token, whatever you configured in azure. Sample: If you want to access to user calendar, profile, etc on behalf of the user, you should have registered this in the azure console. So the clientid is related to that and human user will be prompted with something like this
Libraries
There is some libraries provided by microsoft (c#, nodejs) which will save you a little work. Anyway the previous explanation are very detailed.
Advice
Read about oauth2 spec: https://oauth.net/2/
Read about oauth2 authorization code flow login before the implementation with python
https://www.digitalocean.com/community/tutorials/an-introduction-to-oauth-2
https://auth0.com/docs/get-started/authentication-and-authorization-flow/authorization-code-flow
https://github.com/msusdev/microsoft_identity_platform_dev/blob/main/presentations/auth_users_msalnet.md
Check this to understand how configure the azure web console: https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app
Check my gist https://gist.github.com/jrichardsz/5b8ba730978fce7a7c585007d3fd06b4

Getting Error AADB2C99067 when trying to request access token from Azure B2C

I have an Azure AD B2C tenant setup with an Angular app on the front-end using Authorization Code Flow with PKCE and a back-end api. Everything is working fine. I now have a need to allow the user to access certain pages on the front-end anonymously. I would prefer to still protect the apis these pages will call using the same access token.
I have followed the article here to set up Client Credentials flow. I am able to get an access token successfully using Postman and use it to call my back-end apis fine. However, when I try to do the same from the Angular app, I get the following error:
{"error":"invalid_request","error_description":"AADB2C99067: Public Client XXXXX-XXXXXX is not supported for Client Credentials Grant Flow\r\nCorrelation ID: 2b3346ef-1828-4900-b890-06cdb8e0bb52\r\nTimestamp: 2022-07-28 04:12:21Z\r\n"}
Below is the code snippet I am using in Angular to retrieve the access token.
const urlencoded = new URLSearchParams();
urlencoded.set('grant_type', 'client_credentials');
urlencoded.set('client_id', '<clientid>');
urlencoded.set('client_secret', '<clientsecret>');
urlencoded.set('scope', '<scope>');
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }),
};
const url = 'https://<b2ctenant>.b2clogin.com/<b2ctenant>.onmicrosoft.com/<customPolicy>/oauth2/v2.0/token';
return this.httpClient.post(url, urlencoded, httpOptions);
Any ideas what could be missing?
Thanks!
Though azureadb2c supports client_credential flow.One may not use them with SPA apps.
This scenario is not supported by MSAL.js. Client credential flow/ grant type will not work in SPAs(Angular) because browsers cannot securely keep client secrets.
As they may end up in the browser, visible to everyone and to attackers that load them.
Note:As the application's own credentials itself are being used, they must be kept safe - never publish that credential in your source
code
If you are using it for web app , please make sure to select the platform as web or change the reply url type to be web.
"replyUrlsWithType": [
{
"url": "https......",
"type": "Web"
},
]
Please refer :
Configure authentication in a sample Angular SPA by using Azure
Active Directory B2C | Microsoft Docs
OAuth 2.0 client credentials flow on the Microsoft identity platform- Microsoft Entra | Microsoft Docs

SharePoint Online Webhook Subscription: "Access is Denied" Error?

I have been following this tutorial on how to create a SharePoint webhook subscription, and after authenticating and getting the access token, actually trying to send the request to add a webhook subscription to a SharePoint list through Postman gives me an "Access is denied HRESULT: 0x80070005" error:
Error message
Going into the Postman console to see a more verbose error message shows "917656; Access+denied.+Before+opening+files+in+this+location%2c+you+must+first+browse+to+the+web+site+and+select+the+option+to+login+automatically."
I have tried all of the following:
Gone into SharePoint to enable Sites.Manage.All permissions for my Azure AD App
Reauthorized with several accounts with various access levels
Verified that ngrok, my webhook receiver, and Azure AD App were all running and all connection strings/client ids/secrets were valid.
Could it be that I'm missing something else in regards to SharePoint permissions for my Azure AD App, or is it another issue?
I tried to reproduce in my environment its working fine getting the access token added webhook subscription to a SharePoint list through Postman
First, Check whether you are added content-type and accept in header
This error may cause because of some security issue postman is not authenticated and not authorized to get data from the SharePoint. For this try to register an app using your URL modify at end /_layouts/15/appregnew.aspx
For sample:
https://imu.sharepoint.com/sites/mirror/_layouts/15/appregnew.aspx
Hope you have access, try to register your app as below:
Here, you need to give permission to that particular app such as Full control permission as below snip link :
In App's permission request XML apply permission as below:
And, Click Create and pop up will display trust it. click trust it site setting tab will display if you click that site collection app permission your postman right side will display client id#tenant id
To get the access token click launchpad -> create request ->https://accounts.accesscontrol.windows.net/Tenant ID()/tokens/OAuth/2/
Try to add values in Body tab like
grant_type - client_credentials
Client_id - ClientID#TenantID
Client_secret - Clientsecret
resource - resource/siteDomain#TenantID
Make sure in your Url remove parenthesis in your TenanID and site domain is in your Url like ***.sharepoint.com
Finally, i have added Authorization in header and in value Bearer access token make sure to remember space between bearer and Your access token, I am getting result successfully without any Access Denied error.
For your Reference :
OfficeDev/TrainingContent
Revisit these things
App registered in AD is having AllSites.Manage permission (delegated) and admin consent granted.
While getting access token via postman, use scope as https://yourtenant.sharepoint.com/.default
headers : Content-Type = application/json, Accept = application/json;odata=verbose

Facebook : URL blocked This redirect failed because the redirect URI is not white-listed in the app's client OAuth settings

Recently I have used Facebook Login option in my website. I have wrote all the APIs needed and tested them thoroughly in using "localhost" as domain. While configuring settings in my APP in Facebook developers account, I have setup all the necessary settings like giving Oauth redirect URL, adding domain name in basic settings and other things. Everything worked fine then. So, I have requested required app permissions like pages_manage_posts, pages_read_enagagment, pages_show_list and applied for them. Facebook approved them in the app review.
the Redirect URL ("https://execute.app/#/socialmedia/management/") that I used in Facebook is correctly put in the Facebook Oauth redirect URL path as shown in the pic below.
I have used server side APIs for Facebook login and graph APIs. I have used Oauth2 for Facebook login. You can see the code below
var OAuth2 = require('oauth').OAuth2;
var oauth2 = new OAuth2(CONSTANTS.FB_APP_Key,
CONSTANTS.FB_APP_Secret,
"", "https://www.facebook.com/dialog/oauth",
"https://graph.facebook.com/oauth/access_token",
null);
app.get('/api/document/facebook/auth', function (req, res) {
var redirect_uri = "https://execute.app/#/socialmedia/management/";
console.log("redirect_uri ", redirect_uri);
var params = { 'redirect_uri': redirect_uri, 'scope': 'email,public_profile,pages_manage_posts,pages_show_list,pages_read_engagement' };
var authUrl = oauth2.getAuthorizeUrl(params);
res.send({
"status": true,
"message": "login url generated successfully",
"url": authUrl
});
});
I will explain the problem in two scenarios below.
Scenario-1: When there is and existing active Facebook session in browser i.e, when some user is already logged into Facebook in facebook.com or developers.facebook.com and when we try to login into Facebook from our website, Oauth Authentication API gets called and returns Facebook login URL with status code 200 and the url gets opened in a new tab, its works fine, we don't need to enter Facebook login credentials again, we can just click on "**Continue as USER**" button and then we get the login code, with which we can get user access token. After getting token everything works as planned.
Scenario-2: But if no user is already logged into Facebook in browser and when I click on **login to Facebook** button, API call is made and it returns login URL, but the response status code sent by Oauth login API is 304. A new Facebook login tab is opened, but there is a warning displaying a message saying "URL blocked.
This redirect failed because the redirect URI is not white-listed in the app's client OAuth settings. Make sure that the client and web OAuth logins are on and add all your app domains as valid OAuth redirect URIs."
But you can see that I have added correct Redirect URL in Facebook already. It works in scenario-1 and does not work in another as I mentioned above.
Note: the Facebook login URL returned by Oauth Authentication API is same regardless the status code 200 or 304 . It goes as " https://www.facebook.com/dialog/oauth?redirect_uri=https%3A%2F%2Fexecute.app%2F%23%2Fsocialmedia%2Fmanagement%2F&scope=email%2Cpublic_profile%2Cpages_manage_posts%2Cpages_show_list%2Cpages_read_engagement&client_id=88XXXXXXX663"
Please help me in solving this issue ,thanks in advance
The OAuth RFC states for the redirect URI that:
The endpoint URI MUST NOT include a fragment component.
It might be a bug in Facebook that it works for some scenarios and does not work for others, but in fact it's best to avoid a URI with a fragment component. If Facebook's documentation states that you can use redirect URIs with fragments I would try to contact them ask why this doesn't work in some scenarios.

Asking for user info anonymously Microsoft Graph

In an old application some people in my company were able to get info from Microsoft Graph without signing users in. I've tried to replicate this but I get unauthorized when trying to fetch users. I think the graph might have changed, or I'm doing something wrong in Azure when I register my app.
So in the Azure portal i have registered an application (web app), and granted it permissions to Azure ad and Microsoft graph to read all users full profiles.
Then I do a request
var client = new RestClient(string.Format("https://login.microsoftonline.com/{0}/oauth2/token", _tenant));
var request = new RestRequest();
request.Method = Method.POST;
request.AddParameter("tenant", _tenant);
request.AddParameter("client_id", _clientId);
request.AddParameter("client_secret", _secret);
request.AddParameter("grant_type", "client_credentials");
request.AddParameter("resource", "https://graph.microsoft.com");
request.AddParameter("scope", "Directory.Read.All");
I added the last row (scope) while testing. I still got a token without this but the result is same with or without it.
After I get a token I save it and do this request:
var testClient = new RestClient(string.Format("https://graph.microsoft.com/v1.0/users/{0}", "test#test.onmicrosoft.com")); //I use a real user here in my code ofc.
testRequest = new RestRequest();
testRequest.Method = Method.GET;
testRequest.AddParameter("Authorization", _token.Token);
var testResponse = testClient.Execute(testRequest);
However now I get an error saying unauthorized, Bearer access token is empty.
The errors point me to signing users in and doing the request, however I do not want to sign a user in. As far as i know this was possible before. Have Microsoft changed it to not allow anonymous requests?
If so, is it possible to not redirecting the user to a consent-page? The users are already signed in via Owin. However users may have different access and i want this app to be able to access everything from the azure ad, regardless of wich user is logged in. How is the correct way of doing this nowadays?
Or am I just missing something obvious? The app has been given access to azure and microsoft graph and an admin has granted permissions for the app.
Edit: just to clarify, i tried both "Authorization", "bearer " + _token.Token, and just _token.Token as in the snippet.
Yes, it's still possible to make requests to Graph without a user present using application permissions. You will need to have the tenant admin consent and approve your application.
Edit / answer: Adding the 'Authorization' as a header instead of a parameter did the trick. It works both with 'bearer token' and just 'token'

Resources