Error Access denied when trying to get mailfolders using Graph Api? - microsoft-graph-api

I am trying to rech the endpoint
https://graph.microsoft.com/v1.0/users/{emailaddress}/mailFolders('InBox') but am receiving
Error Access Denied response.
I have granted both Mail.Read.Shared and Mail.ReadWrite.Shared on delegated permission.
The scenario I have is that in Azure AD there are a number of users , Manager#acme.com and Tests#acme.com , so they exist under the same tennant /organization.
I have an app whereby I login as Manager#acme.com as the current user. I the create a connection to the App using client id , secret etc and receive an Auth toke n to use in my api calls.
but when i try to call
https://graph.microsoft.com/v1.0/users/Tests#acme.com/mailFolders('InBox') with that token I
get the following error:
{
"error": {
"code": "ErrorAccessDenied",
"message": "Access is denied. Check credentials and try again."
}
}
Do i ned to grant both Mail.Read.Shared and Mail.ReadWrite.Shared on Application level ?
Or do i need to create a shared folder in Outlook ?

I don't believe Mail.Read.Shared or Mail.ReadWrite.Shared exist as assignable application permissions.
The only permission your App Registration should need is Mail.Read, unless you're intending on the using Graph to delete / send emails etc.
You will likely also need an ApplicationAccessPolicy. You can either create one in the Exchange Online Admin Center, or through PowerShell. I recommend you create a mail enabled security group for all addresses which you need to access and grant restricted access to your app through that policy.
I prefer PowerShell, so in that case you would need the ExchangePowerShell module, and connect to Exchange Online. You'll need some Exchange admin role to be able to do this.
So, let's assume you've created a mail enabled security group called GraphAccessibleUsers#acme.com. You can set the property to hide this from the GAL so users can't see it.
You would then create a policy as follows:
New-ApplicationAccessPolicy -AccessRight RestrictAccess -AppId "<Your-App-Registration-Id" -PolicyScopeGroupId GraphAccessibleUsers#acme.com -Description "Allow App access to users in GraphAccessibleUsers#acme.com"
The -PolicyScopeId parameter will accept:
Name
Distinguished name (DN)
Display name
Email address
GUID
If you only have a few addresses, you may opt to create an individual ApplicationAccessPolicy for each email address.
Finally, I don't think your Graph API URI is correct.
If you want to access the Inbox of Tests#acme.com, then try this instead:
https://graph.microsoft.com/v1.0/users/Tests#acme.com/mailFolders/Inbox
Please refer to mailFolder Resource Type here.

Related

Microsoft Graph - Access Deneined when accessing to calendar events with specifiying user

I am working on creating application which uses Microsoft Graph API to access to calendar events for the users that belongs to an organization.
There is no issue getting event using below endpoint
https://graph.microsoft.com/v1.0/me/calendar/events
However, when accessing to below end point cause 403 error.
https://graph.microsoft.com/v1.0/users/xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/calendar/events
403 - Forbidden
{"error":{"code":"ErrorAccessDenied","message":"Access is denied. Check credentials and try again."}}
So far I have below:
Application is registed to Aure with granting
Application.ReadWrite.All
Calendars.ReadWrite
offline_access
User.ReadWrite.All
Have logic to retrieve the access / refresh token.
When the access token is decoded, below scoes are availalbe
"scp": "Application.ReadWrite.All Calendars.ReadWrite User.ReadWrite.All profile openid email"
Others:
Below endpoints work
https://graph.microsoft.com/v1.0/users
https://graph.microsoft.com/v1.0/users/xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Below endpoints errors with access denied
https://graph.microsoft.com/v1.0/users/xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/calendars
I also tried using User Principal Name instead of ID but it didn't make any difference.
Can someone please help why I am not able to access to the user calendar / events when specifying the user?
Error message showed Access is denied, we can understand that your account doesn't have enough permission to call that api(querying others' calendar events). Since the request calling only related with the access token, no matter whether you have an admin role or not. So let's assume whether you want other users to sign in your app and then they are able to query your calendar events.
According to your description, your token contained scp claim, so I'm sure you are using the delegate permission, which means you signed in and calling api on behalf yourself. And this may be the reason why the access is denied.
We can see the permissions in the screenshot above, I think the application permission type can solve your issue. Using permission type means the api calling is executed by your application itself, but not on behalf of some user. So the application can query any users' calendar events in your tenant.
Using application permission required you to assign application api permission like screenshot below.
Then if you are just testing via tools like postman, using request below to generate access token:
POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded
client_id=535fb089-9ff3-47b6-9bfb-4f1264799865
&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
&client_secret=sampleCredentia1s
&grant_type=client_credentials
If are composing an asp.net core application and trying to call graph api via graph sdk, follow code snippet below:
using Microsoft.Graph;
using Azure.Identity;
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "tenant_name.onmicrosoft.com";
var clientId = "aad_app_id";
var clientSecret = "client_secret";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var events = await graphClient.Users["{user_id}"].Events
.Request()
.Header("Prefer","outlook.timezone=\"Pacific Standard Time\"")
.GetAsync();
Whenever you are trying to access another user calendar events, make sure you have Calendars.Read delegated permission , you can check what type of permission you have in azure portal -
https://learn.microsoft.com/en-us/graph/migrate-azure-ad-graph-configure-permissions?tabs=http%2Cupdatepermissions-azureadgraph-powershell

Microsoft Graph Mail Query - Getting "ErrorAccessDenied"

My company is using Microsoft 365 Business Standard licenses. We are using email through these accounts. We also have a few shared mailboxes. We are trying to create an app that uses the microsoft graph application permissions (rather than the delegated permissions) so the application can access one of the shared mailboxes without needing to be authenticated under the current user.
This is the steps we have taken so far:
Within Microsoft Azure, we have an application in which we have granted application api permissions for Mail.Read, and we have accepted Admin consent.
We authorized as an app, not as a user, in the application using this endpoint https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize, pointing out the required parameters for sending a request. Then, MS API builds this link:
https://login.microsoftonline.com/{some_string}/oauth2/v2.0/authorize?state={some_string}&scope=offline_access%20https%3A%2F%2Fgraph.microsoft.com%2F.default&response_type=code&approval_prompt=auto&redirect_uri=http%3A%2F%2Flocalhost&client_id={some_string}
When we follow the link, we get to the standard authorization form on the site. After we log in, a link is created, where we take the code and create the token: http://localhost/?code={some_string}&state={some_string}&session_state={some_string}
When we try to hit this endpoint: https://graph.microsoft.com/v1.0/users/sharedmailbox#domain.com/messages, we get this response:
{
"error": {
"code": "ErrorAccessDenied",
"message": "Access is denied. Check credentials and try again.",
"innerError": {
"date": "2020-09-14T11:22:30",
"request-id": "{some_string}",
"client-request-id": "{some_string}"
}
}
}
I am thinking that hitting this endpoint https://graph.microsoft.com/v1.0/users/sharedmailbox#domain.com/messages requires us to pass the token previously generated and/or specify which application is making the query?
Any help or direction on what needs to be done to make this query work would be greatly appreciated. Thank you!
I am thinking that hitting this endpoint https://graph.microsoft.com/v1.0/users/sharedmailbox#domain.com/messages requires us to pass the token previously generated and/or specify which application is making the query?
Yes you would need to send the AccessToken in the Authorization header, you should also include the x-anchormailbox header which helps route the request to correct mailbox eg
GET https://graph.microsoft.com/v1.0/users/sharedmailbox#domain.com/messages HTTP/1.1
Host: graph.microsoft.com
Authorization: Bearer EwAoA8l6BAAU ... 7PqHGsykYj7A0XqHCjbKKgWSkcAg==
X-AnchorMailbox: sharedmailbox#domain.com
The other thing you might want to check is to ensure you have the correct scopes in your token you can use https://jwt.io/ for that
In order to use application permissions you will need to use the client credentials auth flow (not the authorization code auth flow which uses delegated permissions). To get a token make a request against "/oauth2/v2.0/token" and specify "grant_type=client_credentials" in the request. See examples of client credentials auth flow here for more details: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow

Unable to access users calendar using application daemon token

I have been trying to access a user's data using the MS graph API. I have been following the official documentation and I have correctly configured the apps and the permission.
I am also following this code_sample and using this I have been able to fetch the daemon token for the application.
Using the token I am able to successfully fetch the data against the following endpoint:
https://graph.microsoft.com/v1.0/users/204e3e4f-xxxx-xxxx-xxxx-509934e1
The data looks like:
{"#odata.context":"https://graph.microsoft.com/v1.0/$metadata#users/$entity","businessPhones":[],"displayName":"developers#outlook.com Tiwari","givenName":"developers#outlook.com","jobTitle":null,"mail":null,"mobilePhone":null,"officeLocation":null,"preferredLanguage":null,"surname":"Tiwari","userPrincipalName":"developers_outlook.com#EXT##webdevelopers.onmicrosoft.com","id":"204e3e4f-x-xxxxx-xxxxxxx-509934e14fa8"}
However, I can't fetch any more data than this. All the other endpoints throw a 401 Unauthorised exception even when I have checked all the Application permission for my app.
I am trying to hit the following endpoints for fetching calendar of the above user:
https://graph.microsoft.com/v1.0/users/204e3e4f-xxxx-xx-xxxxz-509934e14fa8/calendar
https://graph.microsoft.com/v1.0/users/204e3e4f-xxx-xxx-xxxxx-509934e14fa8/calendars
both of these give 401.
Can someone suggest if I am missing something. I even decompiled my jwt token and it clearly shows all the following scopes added:
"roles": [
"Schedule.ReadWrite.All",
"OnlineMeetings.Read.All",
"Mail.ReadWrite",
"OnlineMeetings.ReadWrite.All",
"User.ReadWrite.All",
"Calendars.Read",
"Mail.ReadBasic.All",
"Files.ReadWrite.All",
"User.Read.All",
"Schedule.Read.All",
"Files.Read.All",
"Organization.ReadWrite.All",
"Mail.Read",
"Calendars.ReadWrite",
"Mail.Send",
"Organization.Read.All",
"Mail.ReadBasic"
],
Please help.
To get access to calendar events you should call the following endpoint:
GET /users/{id | userPrincipalName}/events
The documentations for calendars is here: https://learn.microsoft.com/en-us/graph/api/user-list-events
From your comment on Chris Johnson's answer, you're using a personal account. App-only tokens won't work to access a personal account, and you shouldn't be able to even obtain one using a personal account, since there's no concept of an admin.
App-only requires an admin to consent, and when she does, she grants access to all resources in her tenant. Personal accounts are not in work/school tenants, so they aren't in scope. Even if you've added that personal account as a guest in the work/school tenant, their calendar is hosted outside of the tenant, and is off limits.

Can't set hideFromAddressLists in Logic Apps call to Graph API

I have a Logic App that is calling the Graph API to create lots of O365 Groups. For the creation, I am using Application permissions with a registered Azure app which works great.
However, I am now trying to hide O365 groups from the GAL.
I need to set these parameters:
{
"hideFromAddressLists": true,
"hideFromOutlookClients": true
}
I am having the same issue described here. But I can't figure out how to call the Graph API on behalf of a user, with Delegated permissions. I've tried setting up an Azure Managed Identity and setting it's permissions as per these instructions, but I am getting error:
"code": "ErrorGroupsAccessDenied"
"message": "User does not have permissions to execute this action.",
Can anyone help?
These are the App permissions I have set, but I am still getting "ErrorGroupsAccessDenied" "User does not have permissions to execute this action."
As your mentioned it requires to be called with delegated permission, so you can't get the access token just by MSI. According to the page you provided about MSI, it seems just use the service principal to verify the permissions. It still use application permission but not delegated permission. So please refer to the steps below to get the access token and then request the graph api.
1. Create an "HTTP" action to get the access token(we need to use username/password grant flow in this http request).
2. Use "Parse JSON" action to parse the response data from the HTTP action above.
3. Request the graph api to update the group(with the access token from "Parse JSON" action).
Please notice there is a space between "Bearer" and "access_token".

Access is denied returned when calling /me/messages

I am currently trying to make REST calls to get mailbox message stats for a particular account (i.e. read/unread count). I have done this in the Microsoft Graph Explorer and have managed to get the relevant User.Read and many other non-admin permissions.
When I try to replicate this process in Postman, I get "Access is denied. Check credentials and try again.". I followed this guide right until here where I can't move forward despite the correct permissions.
Even my token generation response contains the "scope": "User.Read"
I just want to make a call to GET https://graph.microsoft.com/v1.0/me/messages
The registered app is the account of the email I am trying to monitor. I can make this call successfully Graph Explorer, but I am unable to replicate the results with Postman, PowerShell, or groovy
To make a request to read the signed-in user's mail (GET .../me/messages), your application needs the delegated permissions (i.e. scope) Mail.Read. Just having User.Read is not sufficient. This is also described in the documentation: https://learn.microsoft.com/en-us/graph/api/user-list-messages?view=graph-rest-1.0
It turned out Delegated Permissions weren't enough, despite the fact that it was what I understood my circumstance.
It only started working after I gave it APP Permissions

Resources