How to authorize service to use Microsoft Graph user account without user interaction? - azure

I want my server application to interact with it's own Excel files using Microsoft Graph. That is, the files belong to the application, not a particular user of the application.
I have registered an application with Azure ID and granted "Have full access to all files user can access" permission for Microsoft Graph.
I am trying to use OAuth Resource Owner Password Credentials Grant.
I can get an authorization token like this:
POST https://login.microsoftonline.com/common/oauth2/token
Content-Type: application/x-www-form-urlencoded
grant_type=password
&resource=https://graph.microsoft.com
&client_id=<ID of application registered with Azure AD>
&username=<Microsoft username>
&password=<password>&scope=Files.ReadWrite.All
But the response only indicates scope User.Read:
{
"token_type": "Bearer",
"scope": "User.Read",
"expires_in": "3600",
"ext_expires_in": "0",
"expires_on": "1494467388",
"not_before": "1494463488",
"resource": "https://graph.microsoft.com",
"access_token": "eyJ0e...",
"refresh_token": "AQAB..."
}
And when I try to list files in the account's One Drive, I do not get an error, but the response contains no items:
Request:
GET https://graph.microsoft.com/v1.0/me/drive/root/children
Authorization: bearer eyJ0e...
Response:
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('<account ID>')/drive/root/children",
"value": []
}
When I make the same request in Graph Explorer when logged in with same account the response includes all the items in that account's one drive root.
I understand that Microsoft Graph does not currently support application-only file access, when authorized via OAuth Client Credentials Grant (as per instructions for calling Microsoft Graph in a service), but since I am getting authorization for a particular user account (not just application) I would expect to get access to that users files.
Am I doing something wrong, or is file access not supported using Resource Owner Password Credentials Grant either?
If the latter, how can I achieve allowing my application to use user credentials to manipulate Excel files via Microsoft Graph without user interaction?
UPDATE:
I have had administrator permissions assigned to the account I am using, and re-set the application permissions for Microsoft Graph in the Azure Portal, but it still is not working for me.
Here are details of the account I am using:

Please try to click Grant Permissions(better using admin account) in "Required permissions" blade after granted "Have full access to all files user can access" permission for Microsoft Graph:
After that acquire token using Resource Owner Password flow , you will find Files.ReadWrite.All in scp claims . Then you could call microsoft graph api to list files .
Update
Here is the steps how i make the resource owner flow work :
register a native app , Add the "Have full access to all files user can access" delegate permission for Microsoft Graph(don't click grant permissions button as above picture shown) . using Resource Owner Password Credentials Grant and get the access token ,only find User.Read in scp claim :
POST https://login.microsoftonline.com/common/oauth2/token
Content-Type: application/x-www-form-urlencoded
grant_type=password&client_id=XXXXXXXXXX&resource=https://graph.microsoft.com/&username=XXXXXX&password=XXXXXXX
click grant permissions button as above picture shown , using Resource Owner Password Credentials Grant and get the access token ,you could find Files.ReadWrite.All User.Read in scp claim :

The issue with this is due to permissions on the Graph API. The reason is since you are logged in under a specific user for the Microsoft Graph Explorer - you are able to see everything ... due to the fact you have authenticated as a single person ... the reason you see nothing is because the app-only permissions does not work.

Related

Microsoft Graph to send mail with Client Credential Flow (application permission) and personal account

I am learning Microsoft Graph and for this I use Graph Explorer and Postman.
With Graph Explorer : I am Signed In with my personal user account (hotmail). As soon as I am connected, I can see the token. Strangely when I copy/paste this token in jwt.io it cannot be decoded. Yet I can perform query like https://graph.microsoft.com/v1.0/me which returns me some infos of myself as a user (with http 200). Or this query https://graph.microsoft.com/v1.0/me/sendMail which allow me to send a test and receive a test mail (with http 202). All of these requests was "delegated permission". So I don't have any problem using Graph Explorer with my personnal account (hotmail).
With Postman : this time I will perform some tests with "application permission". I followed the steps below:
On the Azure Portal
Step 1: App registrations / New registration / I give a name / Choose the 3rd account type (Accounts in any organizational directory and personal Microsoft accounts) / Click on Register button
Step 2: Api permissions / Add permission / Microsoft Graph / Application permissions / Mail.Send (send mail as any user)
Step 3: Grand admin consent for... button to activate the permission
Step 4: Certificate & Secrets / New client secret / Enter a description / Click Add button
Step 5: Obtain a token in Postman
POST
https://login.microsoftonline.com/{my-tenant-id-here}/oauth2/v2.0/token
HEADERS
Content-Type: application/x-www-form-urlencoded
BODY
client_id: {my-client-id-here}
client_secret: {my-client-secret-here}
grant_type: client_credentials
scope: https://graph.microsoft.com/.default
OK I got a token
When copy/paste this token in jwt.io I see this:
Step 6: Query for listing all users
GET
https://graph.microsoft.com/v1.0/users
AUTHORIZATION
Bearer token: {bearer-token-received-previously}
HEADERS
Content-Type: application/json
OK I got infos for all users (as json)
Step 7: Query for sending a mail
POST
https://graph.microsoft.com/v1.0/users/{user-principal-name}/sendMail
AUTHORIZATION
Bearer token: {bearer-token-received-previously}
HEADERS
Content-Type: application/json
BODY (JSON)
{
"message": {
"subject": "This is my subject",
"body": {
"contentType": "Text",
"content": "This is my content"
},
"toRecipients": [
{
"emailAddress": {
"address": "thierry.langie#skynet.be"
}
}
],
"ccRecipients": [
]
},
"saveToSentItems": "false"
}
NOT OK Error: MailboxNotEnabledForRESTAPI - REST API is not yet supported for this mailbox
I would like to know why I got this error ? I can send email with Graph Explorer (when using delegated permission) and not with Postman (when using application permission).
As you can see below, I grant admin consent in Enterprise applications on the Azure Portal.
I read somewhere that the error means the user doesn't have the mailbox in EXO cloud. EXO is O365 Exchange Online Cloud. So if you don't have mailbox in the cloud O365 Exchange REST APIs will not work for these users. If that is the case, what would you do ?
I have a Web application which should send mails from a shared mailbox. No matter which user is connected, this is always the same mailbox which is used to send mails. That's why I go with "application permission" and "Client credential flow".
As explained above, I use my personal account (hotmail) for testing purpose but in production I'll use a work account (not accessible from my dev environment).
As a side note, I know there are libraries to facilitate the process and avoid using REST API calls (urls) but I don't think that can explain the problem I am facing.
"MailboxNotEnabledForRESTAPI - REST API is not yet supported for this mailbox" This error message means that the email account you are using to send email doesn't have an Exchange Online license.
For a personal account, you should use Delegated permission, which you have tried in Microsoft Graph Explorer. See Permissions here.
.
If we add the personal account to your tenant as a guest user, although we can Assign a license to a guest user (I assume we can assign EXO license to the guest user), the mailbox hosted in EXO is different from the mailbox of the personal account. They are totally 2 separated mailboxes. And in fact I failed to assign EXO license to the guest.
So in this case Client Credential Flow applies to the AAD users, not the personal account.
UPDATE:
For personal account which uses Delegated permission (you have tried in Microsoft Graph Explorer), the authority endpoint is https://login.microsoftonline.com/commonm/oauth2/v2.0/authorize or https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize.
But when you use client credential flow with Application permission, you have to specify the tenant id in the request https://login.microsoftonline.com/{tenant id}/oauth2/v2.0/authorize.
Although your personal account is added into the tenant as a guest user, it doesn't have EXO license (based on test we are unable to assign EXO license to it), so it won't be hosted in O365.
That is why we can't use client credential flow with personal account.

Why aren't the application permissions being added to my MS Graph token?

I'm trying to get a subscription created with the callRecord resource (https://learn.microsoft.com/en-us/graph/api/subscription-post-subscriptions?view=graph-rest-beta&tabs=http)
In the app registration section of the Azure portal, I've created a multi-tenant app with a client secret. That app has permissions for application-level "CallRecords.Read.All" as well as the default delegated "User.Read". The statuses also have a green checkbox for being granted against my organization by an admin.
I am able to get an access token with the following HTTP POST request to https://login.microsoftonline.com/common/oauth2/v2.0/token:
grant_type:authorization_code
scope:https://graph.microsoft.com/.default
client_secret:<client_secret>
client_id:<client_id>
code:<code>
redirect_uri:http://localhost:3000
However, that token is not able to generate a subscription to my callRecord resource. I get a response with this message: "Operation: Create; Exception: [Status Code: Forbidden; Reason: The request is not authorized for this user or application.]"
The message suggests that the app has not been granted admin-level authorization, but in fact it has. This used to work for me. I'm wondering if there has been a regression on the MS Graph side.
Further, when I examine the JWT, I see that the scope is "User.Read profile openid email". There is no mention of the application-level permission (specifically, CallRecords.Read.All)
Thanks.
Because when you use the auth code flow, just the Delegated permission will take effect. So even if you grant the Application permission, the token you got will not include the permission.
From the doc, to call this API Get callRecord, just the Application permission is supported.
To get the token which include the permission, your option is to use the client credential flow.
Note: You need to use <tenant-id> instead of common in this flow.
POST https://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/token
client_id=xxxxxxx
&scope=https://graph.microsoft.com/.default
&client_secret=xxxxxxx
&grant_type=client_credentials
Decode the token in https://jwt.io, the roles includes the CallRecords.Read.All permission:

Microsoft OAuth 2.0 Client Credentials - Unable to retrieve permission to scope even with Granted Admin Consent on Azure

I am working on daemon service that retrieves the list of contacts from Microsoft Graph, that does not prompt Microsoft Authentication to the user. However, I'm not able to retrieve the permissions I set in Microsoft Azure even with granted admin consent.
I use Postman to generate a token with the following information.
https://login.microsoftonline.com/0835055b-8a00-4130-b07a-037430dd000d/oauth2/v2.0/token
The following json is the result I get
{
"token_type": "Bearer",
"scope": "profile openid email https://graph.microsoft.com/User.Read https://graph.microsoft.com/.default",
"expires_in": 3600,
"ext_expires_in": 3600,
"access_token": "{MY_TOKEN_HERE}"
}
Token is generated successfully but the token returned does not include the permission with granted admin consent I set in MS Azure at portal.azure.com > Registered App > API Permission.
I have Microsoft Graph - Users.Read and Contacts Read with green ticks on admin consent required. See image below:
Microsoft Azure - API Permission
And without the scope, I'm not able to retrieve the list of contacts with given token.
{
"error": {
"code": "ErrorAccessDenied",
"message": "Access is denied. Check credentials and try again.",
"innerError": {
"request-id": "63a24a22-34f7-42a1-a9d5-d7aaf598f4d6",
"date": "2019-07-01T02:59:15"
}
}
}
Is there anything I missed? I assumed when the admin has granted consents, I should be able to include the API in scopes to generate tokens.
I saw there is a similar issue here but there is no solutions that work for me:
Microsoft graph API: Unable to fetch users with the generated access token
Based on your screenshot, the contacts.read you granted is an application permission. And, you have only one delegated permission: user.read .
However, if you want to call the graph api : graph.microsoft.com/v1.0/me/contacts , you need to use delegated permission. It will represent the user. So you can get the information for "me". And based on the official documentation , you need to grant the Contacts.Read (Contacts.ReadWrite for writing) delegated permission.
If you want to use application permission, then you need to get access token with client credentials flow. Token got in this way can be used for application permission. And you should call the api as following : graph.microsoft.com/v1.0/users/{id | userPrincipalName}/contacts

Missing application permission scopes in Azure AD JWT token

Our application is managing Office 365 calendars without requiring explicit consent from users using the Office 365 Exchange Online API. This works as expected for existing installations at customers, but for new customer all requests to the Exchange Online API return a 401 Unauthorized response. We've narrowed this down to a roles claim missing in the JWT token.
Our question is if this roles claim missing in the JWT is a bug, or if this is by design. Perhaps someone from the Azure AD team can share their thoughts.
How to reproduce
In Azure AD, we've created an app registration. A public key has been uploaded in order to authenticate via ADAL4j. Next to this, some application permissions have been granted to Exchange Online:
We can successfully request a access token via ADAL4j, using https://outlook.office365.com/ as the Resource Id. The JWT looks something like this (removed some irrelevant information):
{
typ: "JWT",
alg: "RS256",
},
{
aud: "https://outlook.office365.com/",
iss: "https://sts.windows.net/yyy/",
app_displayname: "Test",
appid: "app-id",
ver: "1.0"
}
As can be seen, the property roles is missing in the JWT token.
When calling the Exchange Online API (e.g. https://outlook.office365.com/api/v2.0/users/user#tenant.onmicrosoft.com/calendars), sending the JWT as a Bearer token, a 401 Unauthorized is returned. The x-ms-diagnostics header mentions:
2000008;reason="The token contains no permissions, or permissions can not be understood.";error_category="invalid_grant"
Expected behaviour
When using an old application registration (created using the Azure Classic Portal, if I recall correctly), the JWT does contain a Roles property with the role we've requested:
{
typ: "JWT",
alg: "RS256",
},
{
aud: "https://outlook.office365.com/",
iss: "https://sts.windows.net/yyy/",
app_displayname: "Test",
appid: "app-id",
roles: [
"Calendars.ReadWrite.All"
],
ver: "1.0"
}
Using this JWT as a Bearer token when calling the Exchange Online API works as expected.
Workaround
We've worked around the issue by using the Grant Permissions button for the new app registration:
Now, the Calendars.ReadWrite.All role is present in the JWT, so everything is working as expected.
Question
In the past we've never had to execute the Grant Permissions action. Also, this page mentions (emphasis added):
As an administrator, you can also consent to an application's
delegated permissions on behalf of all the users in your tenant.
Administrative consent prevents the consent dialog from appearing for
every user in the tenant, and can be done in the Azure portal by users
with the administrator role. From the Settings page for your
application, click Required Permissions and click on the Grant
Permissions button
However, the "Read and write calendars in all mailboxes" permission is an application permission, and not a delegated permission, as mentioned at this page.
Is the workaround the correct solution to our missing Roles claim issue, or is something else wrong on the Azure AD side?
The workaround is the correct solution. When your application needs application permissions, an admin must consent by either clicking in the "grant permissions" button (as you did) or by passing admin_consent to the login URL. This applies to the AAD v1 application model. For the AAD v2 application model, there is a different way to get admin consent. More information here.
In the past (Azure Classic Portal), when you added application permissions to an application, the consent was granted automatically. This is not the case in the new Azure Portal.

Getting the access token for Microsoft Graph API

I'm trying to get the access token for the Microsoft Graph API in order to access a SharePoint document library. My application is a windows service, hence I'm following the procedure described here.
But when I try to get the access token, the response that I get doesn't have the scope value. Below is my response:
{
"token_type": "Bearer",
"expires_in": "3600",
"expires_on":"1492452559",
"not_before": "1492448659",
"resource": "https://graph.microsoft.com",
"access_token": "Token"
}
Because of this when I try to query the Graph API with this access token, I'm getting an error saying: Either scp or roles claim need to be present in the token
Can someone please help me on how to get this working? Thanks in advance.
That seems your client application hasn't set the appropriate app permissions when using client credential flow , below is an illustration of application permissions section in Azure AD classic portal. Please select appropriate permissions needed and retry :
And in addition , when using client credential flow to get the access token , you could check the roles claims in access token(that is the way to check the app permission, not in token response) , using a tool like http://jwt.calebb.net/ to decode the access token and check the app permissions :

Resources