How to access another user's data via the Graph API? - microsoft-graph-api

Using the Graph API and related authentication/authorization flows, how can I access data of all users in an organization? Also, multiple organizations/tenants need to be able to use the app.
As an example: I have an app which needs to read events from all calendars of all users under contoso.onmicrosoft.com. I would like that jack#contoso.onmicrosoft.com, the administrator, authorizes the app which will then be able to read the mentioned the data. Using the Managed API this can be easily done via impersonation.
However, I am trying to do the same with Graph API and OAuth, but I can't find a straight forward solution, or I must be missing something very obvious. I have created an app through manage.windowsazure.com (multi-tenant), and configured it so that it requires Microsoft Graph API (all application and delegated permissions).
I did the following:
1) Point jack#contoso.onmicrosoft.com towards https://login.microsoftonline.com/common/oauth2/authorize?response_type=code&redirect_uri=<my redirect url>&client_id=<my client id>
2) Jack authorizes the app
3) I get back: <my redirect url>/?code=<my authorization code>&session_state=<blah>
4) I send a POST request like below:
POST https://login.microsoftonline.com/common/oauth2/token
Headers: content-type: application/x-www-form-urlencoded
Body:
grant_type=authorization_code&code=<my auth code from step above>
&redirect_uri=<my redirect url>
&client_id=<my client id>
&client_secret=<my client secret>
&resource=https%3A%2F%2Fgraph.microsoft.com%2F
5) When I do the following:
GET https://graph.microsoft.com/v1.0/users/jack#contoso.onmicrosoft.com/messages
Headers: Authorization: Bearer <auth token from step #4>
I get a 200 OK response with the messages.
When I do the following:
GET https://graph.microsoft.com/v1.0/users/anyotheruser#contoso.onmicrosoft.com/messages
Headers: Authorization: Bearer <auth token from step #4>
I get a 403 Forbidden response with:
{
"error": {
"code": "ErrorAccessDenied",
"innerError": {
"date": "2016-06-07T08:47:27",
"request-id": "5b629e30-e6bd-474d-b3dd-8ce25c5ad1c4"
},
"message": "Access is denied. Check credentials and try again."
}
}

The flow/URLs you've referenced are for the authorization code flow which leverages delegated scopes.
A) If you want the app to only work (i.e. access all calendars) for admins then you are using the right flow.
B) If you want the app to work for all users after the admin consents to it, you'll need to use the app (client credentials) flow and use application scopes. This means that you'll need to separate out consent from the regular auth flow.
For consent you'll need to to point the admin to the following url:
GET https://login.microsoftonline.com/common/oauth2/authorize?resource=https://graph.microsoft.com/&client_id=<YourClientId>&client_secret=<YourClientSecret>&response_type=code&redirectUri=<YourRedirectUri>&prompt=admin_consent
For auth flow you'll need a single call from your web server:
POST https://login.microsoftonline.com/common/oauth2/token
body resource=https://graph.microsoft.com/&client_id=<YourClientId>&client_secret=<YourClientSecret>&response_type=code
Or better yet, just use ADAL's AquireToken(resource, clientCredentials) overload.
Once that's done, your app should be good to go to make requests to Graph.
Regardless if you want to stick to A) or switch over to B), to double check that things are set up correctly you can:
Check the token that you get back from Graph (the one you attach to the request along with Bearer) and confirm that it has a roles entry with the roles you need i.e. Calendars.Read
NOTE: The following steps 2.a & 2.b require you to have admin to a test tenant where you'd be consenting to the application.
2.a Use GraphExplorer (https://graphexplorer2.azurewebsites.net/) and confirm that consent has been properly set up by querying
beta/servicePrincipals?$filter=displayName eq '[YourApplicationName]'
If nothing shows up, then the no one has consented to the application.
2.b (only applicable for auth code flow with delegated scopes) Use GraphExplorer and confirm that either delegation has been authorized correctly by querying
beta/oauth2permissiongrants?$filter=clientId eq '[IdFrom ServicePrincipal in 2.a]'
And ensuring you get either a result for the specific user in question or for "AllPrincipals".
More info on app vs delegated scopes here: http://graph.microsoft.io/en-us/docs/authorization/permission_scopes
More info on app flow here: https://graph.microsoft.io/en-us/docs/authorization/app_only

Please use the app-only auth flow (see https://graph.microsoft.io/en-us/docs/authorization/app_only) to use the application permissions - for the token request (step 4) you need to pass grant_type=client_credentials instead of grant_type=authorization_code.

Related

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

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".

Microsoft Graph API Beta - Get Chat returns 401 Unauthorized

I am testing Get Chat Microsoft Graph API (which is still in Beta) and it seems to work successfully when it is called from Graph Explorer (which uses an user token), instead when I call this API from Postman with an application token, I get 401 Unauthorized with an Unknown Error as response.
https://graph.microsoft.com/beta/users/<user-id>/chats/<conversation-id>
My App Registration on Azure has these permissions:
And the decoded application token contains:
"aud": "https://graph.microsoft.com",
"roles": ["User.Read.All", "Chat.Read.All" ]
The same token it works for the Get User API
https://graph.microsoft.com/beta/users/<user-id>
Basically, it seems to have problems only the GET Chat API when called with an application token, although the documentation says it is supported. Am I missing something in the App Registration configuration?
EDIT
As I have already explained in the comments, this question doesn't help me, since:
audit is correct
permissions are present in the token and are granted by the admin in the App registration
scope is correct
Should I check something else?
Have you seen this message on the (English) documentation page?
Before calling this API with application permissions, you must request access. For details, see Protected APIs in Microsoft Teams.
It seems like Microsoft has implemented an extra layer of security for apps accessing "Teams" endpoints.

Is it possible to retrieve an OAuth2 access token from Google with client secret file of Google Apps Script project?

I want to reuse the OAuth2 client-secret of a Google Apps script project to access Google APIs on behalf of this script (e.g. via Sheets API reading a spreadsheet where the script has access). Users with a Google account granted the necessary scopes to the script. Now I'd like to replace the script with a new app without asking the users again for user consent. Typically, when the script (or the app) runs the users would be offline.
My first question would be, if this scenario is a supported OAuth2 use-case with Google API authorization, and if so, what would be the best way to implement it, especially to prevent security issues?
Client secrets of the script
OAuth2 client-secret file of the script from Google API Console, under Credentials. Also see Credentials, access, security, and identity and Setting up OAuth 2.0
The client-secrets.json looks like this:
{"web":{
"client_id": "57...1t.apps.googleusercontent.com",
"project_id": "project-id-95...70",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": "K2...y1",
"redirect_uris": ["https://script.google.com/oauthcallback"]
}}
The file would be deployed with the app code (App Engine). But an alternate location such as Cloud Storage would be possible.
OAuth2 access token
In absence of the user, I would like to use the client ID and secret with the same scopes that were granted to the script originally, for getting an access token from the Google authorization server, something like this:
HTTP 200 OK
Content-type: application/json
{
"access_token": "987tghjkiu6trfghjuytrghj",
"scope": "foo bar",
"token_type": "Bearer"
}
I would like to use the access token in the HTTP Bearer header for the requests to the Sheets API on behalf of the old script.
Client_credentials request to authorization server
My (limited) understanding is, that I can use the grant-type client_credentials to get the access token from the authorization server. The request would look like this:
POST /o/oauth2/token
Host: https://accounts.google.com
Content-Type: application/x-www-form-urlencoded
Accept: application/json
Authorization: Basic Base_64_string
grant_type=client_credentials&
scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fspreadsheets
Where the Basic HTTP authorization is client_id:client_secret values, separated by a colon, and base64 encoded.
If I ditch grant_type or scope in the body, I will get corresponding errors.
The version as above resulted in: {\n "error" : "invalid_request"\n} response, no specifics provided. I have tried with client_id and client_secret in the body in combination with and without the Authorization header, all with the same error.
First Off let me start by saying that i am not an expert in app script or sheets i have used both a few times but i dont consider myself an expert in the subject.
When you authenticate someone their authentication is granted based upon the client id from within a project. They are granting you access to their data and approving the credential request. Think of it as a recored in Googles database someplace.
User 321 has granted consent to client 123 to access their sheets data.
So you have a project Super Script App which has client id 123 you are asking for access to edit sheets. If i approve it i am giving Super Script App with client id 123 access to my sheets. While i am sitting at my machine your app will run accessing my data. Now when i log off Super Script App with client id 123 cant access my data unless you have offline access and have a refresh token. With that refresh token you will be able to access my data when i am not there by requesting a new access token.
Now you want to make a new app. If you take the client id 123 and use it in your new app I am going to have to login to my google account but it will not popup and request that i give you permissions to access my data I have already granted client id 123 access to my sheets. Unless you have a refresh token your not going to be able to access this data without me being there.
If at anytime you ask for an extra scope I am going to have to approve that.
Now comes the fun part. I haven't actually tried this in a while. If you go to Google Developer console and create client id 321 under the same project as client id 123, and then use that in your new Super Script App V2 will i still have to grant it permission to access my data? I am going to lean towards probably not. Note a refresh token created with client id 123 will not work with client id 321 they are locked to a client unless its mobile and there is some magic their.
I am not exactly sure what you are doing with your second app so i hope this helps clear things up.

Either scp or roles claim need to be present in the token

I'm trying to build an application that uses Microsoft Graph to automatically create and read pages in OneNotes stored in SharePoint 365.
I can successfully do this using Graph Explorer as long as I am logged in, but can't get it to work using a bearer token in Postman
The error I am getting is:
Either scp or roles claim need to be present in the token
I successfully get an access token using this:
https://login.microsoftonline.com/common/oauth2/v2.0/token
And passing in the grant_type, client_id, client_secret, code, redirect_uri and scope
Then I perform the following call, with the bearer token included in the header:
https://graph.microsoft.com/v1.0/sites
With the following getting returned:
{
"error": {
"code": "AccessDenied",
"message": "Either scp or roles claim need to be present in the token.",
"innerError": {
"request-id": "fa442c72-4ffe-493b-a33a-8e9e78c94f09",
"date": "2018-01-19T09:56:34"
}
}
}
I have set up graph permissions as per below. I have also tried enabling ALL Notes permissions configured with the same result though
Graph Permissions Image
One post I found said to check http://jwt.calebb.net/ what is returned in the token, and I found that it doesn't contain any roles, so I wonder if this is the problem.
You may need to state your tenant in the url when getting the token :
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token
Thanks to Tsuyoshi Matsuzaki as seen here : How to use Application Permission with Azure AD v2
Your application can get access token using the following HTTP request
(OAuth). Note that you cannot use
https://login.microsoftonline.com/common/oauth2/v2.0/token (which is
commonly used) for getting the token. Instead, you must use
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token, which
identifies the specific tenant.
The call that you mentioned "https://graph.microsoft.com/v1.0/sites" is not valid.
Also request to ~/sites/... routes may need other permissions in addition to Notes.ReadWrite.
Recommend to follow steps mentioned in the following references:
https://developer.microsoft.com/en-us/graph/docs/concepts/permissions_reference
https://developer.microsoft.com/en-us/graph/docs/concepts/auth_v2_user
https://developer.microsoft.com/en-us/graph/docs/concepts/auth_v2_service

Resources