Send mail via Microsoft Graph as Application (Any User) - microsoft-graph-api

We recently migrated from on premise exchange to Microsoft 365 and I'm wanting to turn on 2FA for all users (Enable security defaults). However this disables SMTP authentication which we have been using for sending mail from a distribution group address. (Not achievable via EWS as it doesn't have a physical mailbox)
From what I can see, the only method would be to set up a SMTP relay or send via Microsoft Graph.
I've tried going down the Microsoft Graph route, and here's what I've got so far.
Create application in Azure Active Directory > App Registrations
Add Mail.Send and User.Read.All (Application, not delegated) API Permissions and have granted Admin Consent.
Request token using the following
Generate auth code via https://login.microsoftonline.com/{AzureApi.TenantId}/oauth2/v2.0/authorize?response_type=code&client_id={AzureApi.ClientId}&redirect_uri={WebUtility.UrlEncode(RedirectUrl)}&scope=offline_access%20Mail.Send%20User.Read.All [using admin credentials]
Post request to https://login.microsoftonline.com/{AzureApi.TenantId}/oauth2/v2.0/token with the following request body.
{ "grant_type": "authorization_code", "client_id": "AzureApi.ClientId", "client_secret": "AzureApi.ClientSecret", "code": "insert auth code", "redirect_uri": "insert redirect URL" } to get the bearer token
Once I have the token, Now I perform a request to send some mail
https://graph.microsoft.com/v1.0/users/{fromAddress}/sendMail
This works when fromAddress is the email address of the user that requested the token, however when I try to send from a different address it gives this error {"error":{"code":"ErrorAccessDenied","message":"Access is denied. Check credentials and try again."}}
I even tried adding the SendAs permission to the token user for the mailbox I was trying to send as, but this didn't make any difference. Regardless - I want to be able to send as any user without delegating permissions to each mailbox.
Glad of any help. Thanks!!

The behavior you are getting is expected because you are using delegated permissions - authorization code flow. This flow will not allow your app to send email as any user except the user that is signed in/"requested the token".
In your case you can add the permissions as application permissions and then use Client Credentials flow with either secret or certificate(more secure). Your token request will look like the Get Access Token Section. Note that this means two things:
Your app will need to be secured on server side to protect the credentials.
An admin will need to consent to the permissions on Azure AD
Your app will be able to send emails as any user in your tenant so it is very sensitive.
With application permissions you only need Mail.Send

Related

Error response when using Resource owner password credentials flow (ROPC) in Azure Active Directory

I am trying to set up a resource owner password credentials flow (ROPC) in Azure Active Directory.
My objective is to generate an OAuth 2.0 Access token using my Company org AAD username/password.
I have registered an AAD App with Application (client) ID: “d76b7a4f-xxxxx-xxx” that has these permissions:
I then used Postman to send a request:
However, I am getting this above error. The username/password is correct, but still I am not sure why I am getting this above error message. Probably something to do with the "invalid_grant"?
I have followed these Microsoft articles to build up this ROPC flow:
https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth-ropc
https://learn.microsoft.com/en-us/azure/active-directory-b2c/add-ropc-policy?tabs=app-reg-ga&pivots=b2c-user-flow
In the above 2nd article, I am missing this part (Create a resource owner user flow): https://learn.microsoft.com/en-us/azure/active-directory-b2c/add-ropc-policy?tabs=app-reg-ga&pivots=b2c-user-flow#create-a-resource-owner-user-flow
Maybe that is the reason? Please note, I also don't have an admin role at my company's AAD.
What I am targeting here is to generate the identity of the AAD user in the form of an access token, which is then passed onto the backend system, which then responds based on the identity of the user accordingly.
I could generate the access token using the “client_credential” flow (see below), but I need the access token against the owner password credentials flow (ROPC).
Could you please help me out here.

Cannot authenticate to IMAP on office365 using JavaMail

We are trying to connect a javamail (1.6) client to our office365 mailbox hosted on office365 using OAUTH2 authentication.
No matter what we do, we keep getting A1 NO AUTHENTICATE failed.
We have registered our application with
API Permission
we followed all instructions stated at
https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth
including running the powershell commands to create the principal using the app id and object id, and we granted the app full access to emailbox we want to access.
For authentication we do an HTTP POST as following which generates an access token
This is a client credentials flow with shared secret as explained here
https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow
https://login.microsoftonline.com/{our tenant id}/oauth2/v2.0/token
with
client_id=...
client_secret=...
grant_type=client_credentials
scope=https://outlook.office365.com/.default
our javamail configuration
mail.store.protocol="imap"
mail.imap.host="outlook.office365.com"
mail.imap.port="993"
mail.imap.ssl.enable="true"
mail.imap.starttls.enable="true"
mail.imap.auth="true"
mail.imap.auth.mechanisms="XOAUTH2"
mail.imap.user="<email box>"
then in our java code we connect the store with the access token obtained from the above HTTP POST
store.connect(host, user, oauth2_access_token);
We also tried this powershell script, which returns the same error
https://github.com/DanijelkMSFT/ThisandThat/blob/main/Get-IMAPAccessToken.ps1
I do not believe that problem is specific to JavaMail.
It is extremely difficult to determine if an access token has the correct rights or there is something else that prevents the authentication
What else can we try?
Update 1
If we use the powershell script
https://github.com/DanijelkMSFT/ThisandThat/blob/main/Get-IMAPAccessToken.ps1
passing only the client id and the redirectUri the script prompts me for approval and it succeeds
but if we use clientsecret authorization fails
Update 2
I can successfully use javamail with the access token generated by the powershell script.
Clearly the token created with the clientsecret does not have enough rights to access IMAP or the mailbox
I start to wonder if token requests using client secret do not work because our Azure Active Directory has "security defaults" enabled.
May be MFA is enforced therefore any non-interactive requests are blocked
Update 3
https://jwt.ms allows to decode access tokens
The token created with just the clientid (code grant flow) is very different from the one created with the client_secret (client credentials flow).
In token from "code grant interactive" there is an attribute called "scp" Set of Scopes, which lists scopes regardless of what I have in my client app API permission ????
"scp": "IMAP.AccessAsUser.All Mail.Read Mail.Read.All Mail.Read.Shared Mail.ReadBasic User.Read"
The second token from the client credentials flow, has an attribute "roles", but does not have scopes
"roles": ["IMAP.AccessAsApp"]
RESOLVED!
looking at the access token we noticed that the client credentials flow subject (sub) was an id that we did not setup.
Here is the catch: when creating the service principal using powershell in exchange online, for serviceid you have to use the objectid of the enterprise application.
New-ServicePrincipal -AppId {clientid} -ServiceId {enterprise application objectid} -Organization {tenantid}
When creating an app registration Azure AD, you also create an enterprise application
The application object id is different from enterprise application object id.
The client credentials flow uses the enterprise application object id as the user asking for authorization.
The same for granting access to the mailbox using powershell
Add-MailboxPermission -Identity {email} -User -ServiceId {enterprise application objectid} -AccessRights FullAccess
it is unfortunate that the authentication process is so cumbersome
My two cents on this , if you are still facing authentication failure from javamail trying to connect to mailbox and read emails, First and foremost make sure the application setup in azure active directory has below permissions.
IMAP.AccessAsApp
Mail.Read
Mail.Send (For Sending)
Secondly, Create service principal with the enterprise application id as mentioned in the original post.
Once done check here if your generated token has all the roles you have assigned.
Even if you assigned necessary roles and you can able to connect to mailbox via powershell still you might get AUTHENTICATE failed from javamail because you might be using this property (mail.imap.auth.mechanisms) wrongly , replace mail.imap with mail.imaps and it should solve the problem.
"mail.imaps.auth.mechanisms"="XOAUTH2"
"mail.imap.host"="outlookoffice365.com"
"mail.smtp.port"=993
"mail.store.protocol"="imaps"
session.getStore("imaps")
store.connect(host,port,user,token)
Good luck !!

Error Access Denied on mailboxSettings for users

I'm trying to hit https://graph.microsoft.com/v1.0/users/{userId}/mailboxSettings endpoint with an auth token and in return receiving a 403 Error Access Denied response.
I have granted both application level and delegated permissions for MailboxSettings.Read, MailboxSettings.ReadWrite. I can verify that these permissions are enabled on the installed application via examination of my decoded auth token with the jwt.ms. Here is the exert from the decoded token:
"scp": "Directory.AccessAsUser.All Files.ReadWrite.All Group.ReadWrite.All Mail.Read Mail.ReadWrite Mail.Send MailboxSettings.Read MailboxSettings.ReadWrite Sites.ReadWrite.All"
I have also verified that the user I am requesting mailboxSettings for has been granted access via Admin Consent.
I am able to return mailboxSettings if I hit the endpoint for either the admin userId or the https://graph.microsoft.com/v1.0/users/me/mailboxSettings endpoint. Any help would be much appreciated.
Quickly I tested with Microsoft Graph Explorer and it works for me. So i would request you to test the above API call with Graph Explorer and see if you can repro the issue or not.
I believe the problem is that your token was generated using Delegated scopes. The Delegated flavor of MailboxSettings.Read and MailboxSettings.ReadWrite may only access the currently authenticated user’s mailbox.
In order to access other users, you need to use Application scopes. You can read more about how these scopes work (and how to select them) in this blog post: Application vs Delegated Scopes.
As others have stated, delegated token only works for reading the mailboxSettings of the currently authenticated user. I had enabled mailboxSettings as an Application scope, yet I was getting the same error. The culprit of the issue was that I was using the Auth code grant for the token.
After switching to Client Credentials grant, I am successfully retrieving an Auth token that contains the mailboxSettings Application level scope, and am able to get 200 responses on endpoints for all users.

Microsoft Graph - No mailbox found

I have Office365 developer account with a couple of users. I am attempting to access their mail via a daemon app (i.e. headless) using the Microsoft Graph API.
I have verified that mailboxes exist for these users, but I'm getting an error:
ErrorNonExistentMailbox
No mailbox was found that includes the specified identity: `xx#yy.onmicrosoft.com`
I have previously obtained a token as a registered app (via apps.dev.microsoft.com) and included it with the following request URL:
https://graph.microsoft.com/v1.0/users/xx#yy.onmicrosoft.com/messages
Any guidance?
The token comes to me in the first operation like this:
{
"token_type": "Bearer",
"expires_in": 3599,
"ext_expires_in": 0,
"access_token": "eyJ0eXAiOiJKV1QiLCJub25jZSI6IkFRQUJBQUFBQUFEWDhHQ2k2SnM2U0s4MlRzRDJQYjdyblpfdTg3QjlwS2hFeG5ncFRpS1gwczVwY2k1YnpobHZDdTFlVi1uRlFkRk0yMHlJZ1MxdnlBbC1UUnBYdGNoakxIYkhMb21hT28wb3UxaTkxYnJKRENBQSIsImFsZyI6IlJTMjU2IiwieDV0IjoiaUJqTDFSY3F6aGl5NGZweEl4ZFpxb2hNMllrIiwia2lkIjoiaUJqTDFSY3F6aGl5NGZweEl4ZFpxb2hNMllrIn0.eyJhdWQiOiJodHRwczovL2dyYXBoLm1pY3Jvc29mdC5jb20iLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC83MmY5ODhiZi04NmYxLTQxYWYtOTFhYi0yZDdjZDAxMWRiNDcvIiwiaWF0IjoxNTI3NTM1NTU5LCJuYmYiOjE1Mjc1MzU1NTksImV4cCI6MTUyNzUzOTQ1OSwiYWlvIjoiWTJkZ1lHaTl6Zi9XNWVTTXlPZ0ppc3NxMThUSkFRQT0iLCJhcHBfZGlzcGxheW5hbWUiOiJJbmZvcm1hdGljYSBDQUkgaXoiLCJhcHBpZCI6IjQ0YTA4YWU3LTZiYzItNGEzMy04MmNiLTAzNzZhMzkxYjdhZCIsImFwcGlkYWNyIjoiMSIsImlkcCI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0LzcyZjk4OGJmLTg2ZjEtNDFhZi05MWFiLTJkN2NkMDExZGI0Ny8iLCJ0aWQiOiI3MmY5ODhiZi04NmYxLTQxYWYtOTFhYi0yZDdjZDAxMWRiNDciLCJ1dGkiOiI4RnlhZUZ0ZHVFdWRjcFBNYmswYkFBIiwidmVyIjoiMS4wIn0.DMpgiNfazeDd2KsEjHAggKAg3STMeK59ls9-whHaf-UEON_fvP45ay6PrqfAnwdqz-QKmX-8ikyiM8zuE5r8IGL1d7zYzJCnIECeQwtg8OKzYJPyDW7V0RAF0yePT2fg22luGhFz5yqzjSGlxhWauZmkmXq7JrGrO7fhzAUwoJh7XJrIOlfj098LPoTrmfAaOn36hBmmcQyuFNDhW5E6oXqZsyssJ5SKvaXN_w62IrXv2-nmIkZwyqcrVlCnX_Q1ytrFuc_xItL0FFe_5MbRiF-JIxdbeFNE8LR06mFWfEGHyJu01SJvgxE9500nVzok94qCX-r5lxN0WqVLOuTqEg"
}
I found what I was doing wrong. When requesting the token initially, I was using "common" as the tenant portion of the URL. Apparently, although legal, this does not give the appropriate permissions. The token I got back, when decoded, does not list any permissions, and this would have been a clue if only I had been a little more familiar with the JWT token content and format.
Once I changed the tenant portion of the URL to either the tenant GUID (retrieved from AD), or the fully qualified domain name (something like yy.onmicrosoft.com in my case), I got back a different token, one that includes a list of the Microsoft Graph permissions I had granted in the app registration portal.
Using this new token, I was able to retrieve the mail from the mailbox of any user in my domain. Thanks to Marc for pointing me in the right direction.
Just to clarify Aldu's answer, I did also have the same issue.
Obtaining the admin consent, it is fine to use /common as in step 2 of the instructions .
However, then requesting an access token from the microsoft auth server via client_credentials at https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token, I found I needed to replace tenant with a tenant ID. That changed my access token and allowed access to the resources.

office365/azure oauth using delegated user id

My goal is to write some code to enable an Office 365 user to access files in OneDrive for business via REST API. I have registered an application in Azure AD (Web App/single tenant) and have a redirect URI to receive the OAuth token. I want to use the "delegated user identity with OAuth" scenario. To see how it works, I use the "Office 365 OAuth Sandbox" here: https://oauthplay.azurewebsites.net/. When I "Authorize using own account" and enter any valid Office 365 user credentials, I get an access token back. When I replace the client ID and redirect URI in the authorization URL with the info of my registered app, I can only get the token when I enter a user registered in my app (otherwise I get an error 50012 during sign-in). What do I have to change in my configuration to allow any Office 365 user to get an authorization token (like the Sandbox does) ?
You need to mark your web application as multitenant, or Azure AD will constrain all callers to be from the tenant in which you provisioned the application.
Take a look at https://github.com/AzureADSamples/WebApp-WebAPI-MultiTenant-OpenIdConnect-DotNet for an example of a web app that is multitenant and invokes a Microsoft API. Note that you don't necessarily need to validate issues as shown in the sample, just do what makes sense for your scenario (which might mean even not validating).

Resources