Microsoft Graph Api - Post Subscription gives Internal Server Error - microsoft-graph-api

I'm trying to post subscription request to graph api via https://graph.microsoft.com/v1.0/subscriptions endpoint. However, I keep getting this error:
"code": "ExtensionError",
"message": "Operation: Create; Exception: [Status Code: InternalServerError; Reason: Expected 1 response for tenant lookup for tenant id ... but received 0]
My request:
{
"changeType": "created,updated",
"notificationUrl": "https://.../notification",
"resource": "communications/callRecords",
"expirationDateTime": "2021-03-24T18:23:45.9356913Z",
"clientState": "secretClientValue"
}
I'm able to get token with my tenant id as grant_type = client_credentials (OAuth 2.0 client credentials grant flow). I do not understand why my tenant gives error when subscribing, although token creation is successful.
What am I doing wrong? Please help!
Thanks.
Update:
Permissions of my application:
Calendars.ReadWrite Application
CallRecords.Read.All Application
Directory.ReadWrite.All Application
OnlineMeetings.Read.All Application
Admin consent is granted for all.

I assume since you say "grant_type = client_credentials (OAuth 2.0 client credentials grant flow)" you are using Delegated CallRecords.Read.All permission.
If you read this page, it says that CallRecord subscriptions only support the Application CallRecords.Read.All permission. So you have to use application client for authentication and not client credentials.
===== UPDATE =====
Based on the comments I can guess I number of possible problems:
Since the "free" azure accounts don't have teams licenses, one guess that the subscription call will fail with something. This may be why it's failing for you with a weird message.
The other setup is that your azure application is in the "free" account and the subscription is for another tenant (like your work tenant). For this to work you would need:
azure application set to multi-tenant
admin consent in the work tenant by their admin
in the generate token call the "myTenantId" has to be the tenantid of the work tenant

Related

Send mail via Microsoft Graph as Application (Any User)

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

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.

using microsoft graph api to read mail behalf of users in the enterprise

I am trying to get the messages inside the mailbox of users in the enterprise via the admin account.
In my app I have the following permissions:
I used the https://login.microsoftonline.com/common/adminconsent?... to grant the application permissions to read mail in all mailboxes and after that, I used the OAuth2 authentication to get a Bearer token.
This is the response I got from the token endpoint:
{
"token_type": "Bearer",
"scope": "Mail.Read User.Read User.Read.All profile openid email",
"access_token": "<token>",
"expires_in": 3599,
"ext_expires_in": 3599
}
When I used this to access a mailbox via https://graph.microsoft.com/v1.0/users/USER-ID/messages, I got the following response
{
"error": {
"code": "ErrorAccessDenied",
"message": "Access is denied. Check credentials and try again.",
"innerError": {
"request-id": "a31bcf73-4bd6-4fed-bfee-d70328e0703e",
"date": "2018-11-26T15:20:37"
}
}
}
However, when I use this endpoint with the User ID of the authenticated admin account, I am able to access the messages in that mailbox.
But I would like to access the mailboxes of all users in the organization via Microsoft Graph.
The Outlook endpoints operate a little differently than most of the Graph endpoints, rather than having a .all variation of their scopes (i.e. user.read vs user.read.all), it depends on which scope type (Delegated vs. Application) is being used.
When Delegated scopes are being used, Mail.Read only provides access to the authenticated user's mailbox (the only exception being those that have been explicitly shared with that user).
When Application scopes are being used, Mail.Read provides access to any user's mailbox.
Now, this is where things get a little wonky, the type of scope that gets applied is entirely dependant on the OAuth Grant used to obtain the token.
When using Implicit or Authorization Code grants, Delegated scopes are applied.
When using the Client Credentials grant, Application scopes are applied.
So in order for you to access any user's mailbox via /v1.0/users/{someUser}/messages, you first need to obtain your token using the Client Credentials OAuth grant. You can find a walkthrough on how this works in the documentation under "Get access without a user".

Unable to access Graph API when using Microsoft App Developer API key

I'm still not able to access the Graph API when using my developer API key from the Microsoft App Registration Portal (Azure AD v2.0 endpoint) as the "client_secret" and I receive the following error message when using the below URL in my web browser to test manually:
Error message:
{
"error": {
"code": "InvalidAuthenticationToken",
"message": "Bearer access token is empty.",
"innerError": {
"request-id": "902fec23-3ac7-433a-952c-4b0c4213869",
"date": "2018-06-05T15:23:11"
}
}
}
URL:
https://graph.microsoft.com/v1.0/sites/<tenant_name>.sharepoint.com/_api/web/lists?client_id=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&client_secret=xxXXxxxxxxxxx
I'm trying to do test this without authenticating with my O365 account as this will go into a script to perform callouts to Sharepoint Online.
You cannot use Microsoft Graph without authenticating. Every call to the Graph must include a valid access token in the Authorization header:
From the documentation:
To call Microsoft Graph, your app must acquire an access token from Azure Active Directory (Azure AD), Microsoft's cloud identity service. The access token contains information (or claims) about your app and the permissions it has for the resources and APIs available through Microsoft Graph. To get an access token, your app must be able to authenticate with Azure AD and be authorized by either a user or an administrator for access to the Microsoft Graph resources it needs.

Microsoft Graph API: 403 Forbidden error when trying to retrieve policies on tenant

I'm trying to retrieve the policies created for my tenant on the Azure AD portal using the Microsoft Graph API. As I understand from the graph API documentation, all the policy CRUD operations require a scope of Directory.AccessAsUser.All.
This scope translates to the permission Access directory as the signed-in user as mentioned here - https://developer.microsoft.com/en-us/graph/docs/authorization/permission_scopes
I have been trying to configure my application on the both the new Azure portal and the old one with different failure points.
On the new portal:
I have created a Web Application in my tenant following instructions on https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal.
When configuring access control, the only subscription for my tenant is Access to Azure Active Directory and I'm not able configure access control on this in the new portal. From the browser, when I select Access Control (IAM), I see the error - "Call to ARM failed with httpCode=BadRequest, errorCode=DisallowedOperation, message=The current subscription type is not permitted to perform operations on any provider namespace. Please use a different subscription., reason=Bad Request."
The "Add" roles button is disabled as well.
Can I not configure Access control on the subscription Access to Azure Active Directory? If so, is there no other way to retrieve the policies for my tenant using the API?
On the old portal:
For my app, I configured permissions for:
Microsoft Graph
Windows Azure Active Directory
I verified on the portal that both the APIs are configured with the permission Access directory as the signed-in user. Even in this case, I keep getting a 403 Forbidden when I try to access the https://graph.microsoft.com/beta/policies endpoint to list the policies on my tenant.
Here is the payload on my access token I obtained (https://login.microsoftonline.com/{my tenant name}/oauth2/token)
{
"aud": "https://graph.microsoft.com",
"iss": "https://sts.windows.net/8b49696d-462a-4a71-9c5c-f570b2222727/",
"iat": 1491256764,
"nbf": 1491256764,
"exp": 1491260664,
"aio": "Y2ZgYAi68q2XUTk0ykH7/TZzrhYbAA==",
"app_displayname": "test-app",
"appid": "951bb92d-5b68-45ae-bb8b-d768b2696ccc",
"appidacr": "1",
"idp": "https://sts.windows.net/8b49696d-462a-4a71-9c5c-f570b2222727/",
"oid": "7ccea836-d389-4328-a155-67092e2805e9",
"roles": [
"Device.ReadWrite.All",
"User.ReadWrite.All",
"Directory.ReadWrite.All",
"Group.ReadWrite.All",
"IdentityRiskEvent.Read.All"
],
"sub": "7ccea836-d389-4328-a155-67092e2805e9",
"tid": "8b49696d-462a-4a71-9c5c-f570b2222727",
"uti": "4fmUDNWWHkSoTn2-7gtTAA",
"ver": "1.0"
}
Obviously the Directory.AccessAsUser.All role is missing on this token which is causing the 403 error. So either I'm missing something here or there is a bug in the API that is preventing all the permissions from being correctly configured. Greatly appreciate any help/pointers on this!
Please note:
I'm only using the beta APIs because I didn't find the corresponding endpoint for policies on the v1.0 APIs and the Azure Graph API documentation recommends using the Microsoft Graph API.
With the same configuration, using the Azure Graph API endpoints also returns a 403 Forbidden error for the policies endpoint(https://msdn.microsoft.com/zh-cn/library/azure/ad/graph/api/policy-operations#list-policies)
Based on the claims in the access token, you were acquire the access token using the client credentials flow which the token used to delegate the app. There is no such delegate permission for user in this kind of token.
To get the access token for the delegate permission for users, you need to using the other flows like Authorization code grant flow. You can refer this link for the detail.

Resources