We tried to setup the simplest possible application for reading emails from a mailbox in our organization, using Microsoft Graph.
It's a background service so we used ClientSecretCredential as authentication strategy.
Here is the code:
var credentials = new ClientSecretCredential("xxx-tenantID","xxx-clientId","xxx-clientSecret");
var graphServiceClient = new GraphServiceClient(credentials, new string [] {"https://graph.microsoft.com/.default"});
var result = await graphServiceClient.Users["myaddress#mycompany.com"].MailFolders["Inbox"] .Messages.Request() .GetAsync();
It seems to login correctly but then it gets an access denied when tring to access the specific inbox:
Unhandled exception. Status Code: Forbidden
Microsoft.Graph.ServiceException: Code: ErrorAccessDenied
Message: Access is denied. Check credentials and try again.
I think we miss some authorization on the azure side; in particular, we can't find the place where the application is authorized to access that specific mail box (myaddress#mycompany.com).
Update:
When we give to the application the authorization showed below, it works.
Unfortunately this gives access to all the mailboxes in the organization and this is unacceptable since this app should only access the service mail box it was designed to manage.
The question now is how to limit the access to the only mailbox required.
Sorry for italian language in the screenshot, the highlighted text means "Adminisrator consent" and is the settig that made the application work.
To summarize you want to use client credentials to access a single mailbox?
You can use this powershell command to create an access policy to restrict this application to a single mailbox or group of mailboxes.
https://learn.microsoft.com/en-us/powershell/module/exchange/new-applicationaccesspolicy
Connect-ExchangeOnline
New-ApplicationAccessPolicy -AccessRight RestrictAccess -AppId <String[]> -PolicyScopeGroupId your.service#account.com
I have Web API built in .net framework 4.6. I secure my API using Azure AD. For the purpose of development, I need to generate token so I can use it for testing and debugging. How can I generate token from Microsoft Graph that I can use to authenticate to my API?
I tried this https://login.microsoftonline.com/{tenantId}/oauth2/token endpoint but the token it generates is not valid. I get 401 using the token from that endpoint.
enter image description here
The error "401 unauthorized" usually occurs when you missed giving resource parameter while generating access token.
If that's the case, you will still get the access token but when you are using the token to authenticate to your API, you will get "Invalid token" error.
To resolve the error, please include below parameters while generating access token:
Make sure to include resource parameter and other required parameters like below:
I tried in my environment, after including the above parameters, I got the access token successfully like below:
If the above solution does not work, try with different grant_type parameter.
For more information, please refer below links:
401 Unauthorized Error–Azure Active Directory (AD) – Microsoft Azure Articles.. (wordpress.com).
Getting Access Token for Microsoft Graph Using OAuth REST API - DZone Security
Azure registered app error: The user or administrator has not consented to use the application with ID - Stack Overflow
Problem: How to authenticate in MS Graph using Azure AAD access token.
Current flow:
My web app has AAD configured with "Log in with AAD"
If I log into AAD my demo app is showing and if I go to https://******.azurewebsites.net/.auth/me
then I get the access_token.
What I tried:
So I tried a couple of things and this was the last, I copied the access_token as code and tried to send it, didn't work.
I'm searching for a solution to silently use the already logged-in user and call MS Graph.
The reason for the error is that you have used the wrong code. Don't try to send the access token as a code, you should request an authorization code in your browser.
https://login.microsoftonline.com/{tenant id}/oauth2/v2.0/authorize?
client_id={client id}
&response_type=code
&redirect_uri={redirect_uri}
&response_mode=query
&scope=https://graph.microsoft.com/.default
&state=12345
In addition, redirect_uri is also a required parameter.
For the already logged in user you need follow the below steps for access:
Make sure you have enable the allow access token for the register app as below
Write code to acquire access token for the for the logged in user Reference
Now you can pass this token in other successive call to get the result.
Scenario
I have an Exchange Online environment and service/daemin (no interactive user) application on the Azure VM. Service uses EWS managed API to work with emails in the mailbox of any tenant user. Now EWS client uses Basic authentication that, according to Microsoft, will become unsupported in EWS to access Exchange Online.
Question/Issue
So, I need to find a way to get valid access token for service/daemon application to use with EWS managed API.
My findings
The following article shows an example of using OAuth 2.0 with EWS managed API. This example works, but it uses interactive method of getting consent (sign-in form appears allowing user authenticate themselves and grant requested permission to application) that is not suitable for service/daemon app scenario, because there is no interactive user.
For service/daemon application I need to use client credential authentication flow.
Registered application
Using admin account on https://aad.portal.azure.com portal I registered application with Azure Active Directory. Added client secret for registered application.
Aforementioned article uses https://outlook.office.com/EWS.AccessAsUser.All as a scope. But I did not find permission with such a URL on the portal. I found only the following permissions under Office 365 Exchange Online > Application permissions > Mail:
https://outlook.office365.com/Mail.Read Allows the app to read mail in all mailboxes without a signed-in user
https://outlook.office365.com/Mail.ReadWrite Allows the app to create, read, update, and delete mail in all mailboxes without a signed-in user.
I added both of them and granted admin consent for all users.
Getting access token
For testing purposes and simplicity I did not use any auth libraries (ADAL, MSAL etc.). I used Postman to get access token, then set token variable in debug (see code snippet later in the post).
I tried different endpoints to get acess token.
OAuth 2.0 token endpoint (v2)
POST: https://login.microsoftonline.com/<TENANT_ID>/oauth2/v2.0/token
grant_type=client_credentials
client_id=***
client_secret=***
scope=https://outlook.office.com/EWS.AccessAsUser.All
Sending this request produces the following error response:
AADSTS70011: The provided request must include a 'scope' input parameter. The provided value for the input parameter 'scope' is not valid. The scope https://outlook.office.com/EWS.AccessAsUser.All is not valid.
I tried changing scope to https://outlook.office.com/.default. Access token was returned, but it appeared to be invalid for EWS. EWS client throws 401 error with the following value of x-ms-diagnostics response header:
2000008;reason="The token contains no permissions, or permissions can not be understood.";error_category="invalid_grant"
OAuth 2.0 token endpoint (v1)
POST: https://login.microsoftonline.com/<TENANT_ID>/oauth2/token
grant_type=client_credentials
client_id=***
client_secret=***
resource=https://outlook.office.com
Access token was returned, but also appeared to be invalid for EWS. EWS client throws 401 error with the same value of x-ms-diagnostics response header as described ealier in #1.
Use aquired access token with EWS managed API
Here is code sample that I used to test EWS client with access token acquired in Postman:
var token = "...";
var client = new ExchangeService
{
Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx"),
Credentials = new OAuthCredentials(token),
ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress,
"user#domain.onmicrosoft.com"),
};
var folder = Folder.Bind(client, WellKnownFolderName.SentItems);
We had a similar problem: We wanted to use a Service Account to connect to a single mailbox and just doing some stuff with the EWS API (e.g. searching in the GAL) and the full_access_as_app seems like an overkill.
Fortunately it is possible:
Follow the normal "delegate" steps
And use this to get a token via username/password:
...
var cred = new NetworkCredential("UserName", "Password");
var authResult = await pca.AcquireTokenByUsernamePassword(new string[] { "https://outlook.office.com/EWS.AccessAsUser.All" }, cred.UserName, cred.SecurePassword).ExecuteAsync();
...
To make this work you need to enable the "Treat application as public client" under "Authentication" > "Advanced settings" because this uses the "Resource owner password credential flow". (This SO answer helped me alot!)
With that setup we could use a "tradional" username/password way, but using OAuth and the EWS API.
You can protect your client application with either a certificate or a secret. The two permissions that I needed to get this to work were Calendars.ReadWrite.All and full_access_as_app. I never tried acquiring my token via PostMan, but use AcquireTokenAsync in Microsoft.IdentityModel.Clients.ActiveDirectory. In that call, the resource parameter I use is https://outlook.office365.com/. It's pretty simple once you know all the little twists and turns. And full disclosure: I was one lost puppy until MSFT support helped me through this. The doc on the web is often outdated, conflicting, or at best, confusing.
You need to register your app in Azure and use certificate based authentication. https://blogs.msdn.microsoft.com/emeamsgdev/2018/09/11/authenticating-against-exchange-web-services-using-certificate-based-oauth2-tokens/
I run into the same issue while following Microsoft official docs for OAuth 2.0 client credentials flow
According to the Microsoft identity platform and the OAuth 2.0 client credentials flow, the scope "should be the resource identifier (application ID URI) of the resource you want, affixed with the .default suffix" (see default scope doc).
So the question is how to convert https://outlook.office.com/EWS.AccessAsUser.All into the resource identifier.
Experimentally I manage to make it working using scope=https://outlook.office365.com/.default. I granted full_access_as_app (Office 365 Exchange Online / Application permissions) and got administrator consent for it.
I did face this issue while implementing OAuth for EWS. My application is not using EWS Managed API. Here is what all I did to make it working.
Added permission Office 365 Exchange Online > full_access_as_app to application.
Acquired access token for scope https://outlook.office365.com/.default.
POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token
form-data = {
client_id,
client_secret,
grant_type: 'client_credentials',
scope: 'https://outlook.office365.com/.default',
};
Added access token as Authorization header and ExchangeImpersonation SOAP header to the request.
<SOAP-ENV:Header>
<t:ExchangeImpersonation>
<t:ConnectingSID>
<t:PrimarySmtpAddress>user#domain.com</t:PrimarySmtpAddress>
</t:ConnectingSID>
</t:ExchangeImpersonation>
</SOAP-ENV:Header>
Late answer, but since this seems to come up, and I was just working with this... why not.
If you use Microsoft's v2.0 URLs for OAUTH2 (https://login.microsoftonline.com/common/oauth2/v2.0/authorize and .../common/oauth2/v2.0/token) then the scope for Office 365 EWS is:
https://outlook.office365.com/EWS.AccessAsUser.All
You'll probably want to combine this scope with "openid" (to get the signed in user's identity) and "offline_access" (to get a refresh token). But then offline_access may not be necessary when using client credentials (because you don't have to prompt a human user for them every time you need an access token).
In other words:
params.add("client_id", "...")
...
params.add("scope", "openid offline_access https://outlook.office365.com/EWS.AccessAsUser.All")
If using v1 OAUTH2 URLs (https://login.microsoftonline.com/common/oauth2/authorize and .../common/oauth2/token) then you can use a "resource" instead of a "scope". The resource for Office 365 is https://outlook.office365.com/.
Or in other words:
params.add("resource", "https://outlook.office365.com/")
Note that in the latter case, you're not asking for any scopes (it's not possible to combine "resource" with scopes). But the token will automatically cover offline_access and openid scopes.
I used this method successfully:
Install Microsoft Authentication Library module ( MSAL.PS)
https://www.powershellgallery.com/packages/MSAL.PS/4.2.1.3
Configure Delegate Access as per MSFT instructions: https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-authenticate-an-ews-application-by-using-oauth
Configure ApplicationImpersonation for a service account as normal
Grab your token
$cred = Get-Credential
$clientid = ""
$tenantid = ""
$tok = Get-MsalToken -ClientId $clientid -TenantId $tenantid -UserCredential $cred -Scopes "https://outlook.office.com/EWS.AccessAsUser.All"
I am using the GraphServiceClient in my code to access multiple endpoints for data. I have a service account who logs in with Azure AD, with the following scopes: Group.Read.All, User.Read.All, Mail.Read.
However, with these needed scopes I cannot get the MailFolders for a users profile or a birthdate from the user. It gives the following error:
ServiceException: Code: -2147024891, System.UnauthorizedAccessException.
The delegated permissions in Azure AD have already granted by admin (https://imgur.com/iFb0rx9).
Example MailFolders:
var result = await client
.Users[user.Id]
.MailFolders
.Request()
.GetAsync();
This is the error that came back:
ServiceException:
Code: ErrorAccessDenied
Message: Access is denied. Check credentials and try again.
Can I not access other users profiles or am I missing something else?
If you have Mail.Read as a delegated permission (meaning you've logged in with a user), then you can only read your own mail, even if someone has given you permissions to their mailbox. In order to read other mailboxes, you need to request the Mail.Read.Shared permission.
If you have Mail.Read as an application permission (meaning no logged in user to your app, using the client credentials flow), then you can read all mailboxes in your org.
I believe that the question is already answered here.
Even when you app has admin consent to do something it does not override the Exchange delegate permission if you know what I mean.
You would need that specific user's token or try to access it as a user who is delegated in Exchange online.