Accessing onenote via API MS graph - azure-active-directory

I've read lots of docs and different posts, but I can't get the right access token to read my own OneNote via api.
I have MS account and app in azure portal.
In graph-explorer I CAN read my OneNote.
If I copy access token from graph-explorer, then my code works fine.
BUT:
If I request access token from https://login.microsoftonline.com/{tried 'common' or my tenant_id here}/oauth2/v2.0/token,
then it does not work:
The OAuth token provided does not have the necessary scopes to complete the request. Please make sure you are including one or more of the following scopes: Notes.ReadWrite.All,Notes.Read.All
I created app in azure portal and gave it all read permissions, which I found ( for both one-note and ms graph APIs, both delegated and application... just for test) and generated secret
I'm trying following request:
token_request_data = {
'client_id': 'id from my app', # also tried 'common'
'scope': 'https://graph.microsoft.com/.default', # other scopes cause errors
'client_secret': 'secret from my app',
'grant_type': 'client_credentials'
}
Perhaps somebody could give me a clue what I'm doing wrong ? :)
Sample request via graph explorer:
https://graph.microsoft.com/v1.0/users/{my_username}#outlook.com/onenote/sections
Permissions in app (azure portal) screenshot
Permissions in graph explorer screenshot

Notes.Read.All and Notes.readWrite.All are valid for Work or school accounts only. Please refer this document.

Related

Permissions for listing virtual machines with Graph API

I am trying to use the request:
GET https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}?api-version=2020-12-01
From microsoft graph API:https://learn.microsoft.com/en-us/rest/api/compute/virtualmachines/get#code-try-0.
I created an app registration within the an AD subscription. When I try to use the oauth2 credentials associated with the app registration I receive a 401. I believe this is due to a permissions error. I tried using https://developer.microsoft.com/en-us/graph/graph-explorer, but I am unable to assume the app registration to simulate the request. Any insight as to why this might be happening or how to debug the issue would be very helpful
Unlike the accepted answer, I had to set the scope to access this url...
https://management.azure.com/subscriptions/{SubscriptionID}/providers/Microsoft.Compute/virtualMachines?api-version=2020-12-01
to:
https://management.azure.com/.default
Your error is not a lack of permissions but the use of the wrong scope.
The error is actually very simple, you need to grant Azure Service Management api permissions instead of MS graph permissions, and then you need to set the scope to: https://management.azure.com/user_impersonation.
Next, use the auth code flow to obtain an access token.
Request an authorization code in the browser.
https://login.microsoftonline.com/{tenant id}/oauth2/v2.0/authorize?
client_id={client id}
&response_type=code
&redirect_uri={redirect_uri}
&response_mode=query
&scope=https://management.azure.com/user_impersonation
&state=12345
Redeem token.
Call api:
Please note that do not use graph-explorer test, because you are not calling MS graph api, you can use postman.

Microsoft Graph User.Read

I am writing an .Net Core application with Angular Frontend.
Now users are authenticated with Azure Active Directory, which is configured over the Azure Portal.
The users are succesfully authenticated, but as a developer, I still do not now, which user has authenticated.
There are lots of exmaples how to retrieve the information about the user, which is done with
https://graph.microsoft.com/v1.0/me. But when I call this, I am getting an 401 Unauthorized response. So there must be a way to get a Token or something like that.
I am having an client-ID, tenant-ID as well as an AppServiceAuthSession Cookie. Can anyone provide an code example?
For your requirement, you can go to Resource Explorer find your app and then locate "config" --> "authsettings". Edit the additionalLoginParams in json as:
"additionalLoginParams": [
"response_type=code id_token",
"resource=<the client id of your app in azure ad>"
],
Apart from this, you also need to edit the redirect uri of your app like:
https://yourapp.azurewebsites.net/.auth/login/aad/callback
After that, you can get the access token by request https://yourapp.azurewebsites.net/.auth/me. You can use the access token to request graph api https://graph.microsoft.com/v1.0/me. By the way, maybe there are some information in the response of https://yourapp.azurewebsites.net/.auth/me. If the information is enough, you do not need to use access token request the graph api.
You are getting 401 Unauthorized response as you don't have right token to access the API https://graph.microsoft.com/v1.0/me. The right approach is to use MSAL libraries to get token for your application(by authenticating) and use it for API.
Please find step-by-step tutorial using .Net core here and code sample here.
Please find step-by-step tutorial using Angular here and code sample here.
The solution was to add an secret to the application and then call https://xyz.azurewebsites.net/.auth/me.

SharePoint API: Can't authenticate 'Sites.FullControl.All' in client_credential flow

I've have an App that would like to access SharePoint API.
I've registered it in AD, and gave it the following permissions:
But when I ask it to be authenticated with the following scopes
- https://graph.microsoft.com/User.Read.All
- https://graph.microsoft.com/Group.Read.All
- https://graph.microsoft.com/Sites.Read.All
- https://graph.microsoft.com/Calendars.Read.Shared
- https://graph.microsoft.com/MailboxSettings.Read
- https://graph.microsoft.com/Files.Read.All
- https://graph.microsoft.com/Directory.Read.All
- https://graph.microsoft.com/AuditLog.Read.All
- https://graph.microsoft.com/AuditLog.Read.All
- offline_access
- https://manage.office.com/ActivityFeed.Read
- https://microsoft.sharepoint-df.com/Sites.FullControl.All
- https://microsoft.sharepoint-df.com/Sites.Read.All
- https://microsoft.sharepoint-df.com/User.Read.All
I get this error:
invalid_client&error_description=AADSTS650053:
enter code here`The application 'XXX' asked for scope
'Sites.FullControl.All' that doesn't exist on the resource
'00000003-0000-0ff1-ce00-000000000000'.
Contact the app vendor.
What does this mean that it that doesn't exist on the resource?
With all the other scopes (except SharePoint's) it all works fine
Looks like the Sites.FullControl.All has moved to the Graph API section but trying to add it in the Azure portal results in a different error saying that permission is not currently supported (see on screenshot below).
In my test application, I succeeded using AllSites.FullControl (AllSites as a single word, no periods) and then listing all sites on SharePoint Online tenant with MSAL for .NET.
var app = PublicClientApplicationBuilder.Create(MyAppId)
.WithAuthority("https://login.microsoftonline.com/common", false)
.WithDefaultRedirectUri()
.Build();
return await app
.AcquireTokenInteractive(new string[] { "https://tenantxx.sharepoint.com/.default" })
.WithParentActivityOrWindow(parentWindow) // optional, used to center the browser on the window
.WithPrompt(Prompt.SelectAccount)
.ExecuteAsync();
API Permissions in the Azure portal:
I ran into this same thing. It took a while but this was my clue: How to Access Sharepoint Online API with v1 Azure AD Application and Client Credentials
Using client secret, I could get a token but it would fail. Using a certificate, I was able to successfully authenticate.

How to solve "NoPermissionsInAccessToken" returned by Microsoft Graph when reading calendar or sending mail

Within our department we have a Classic ASP website that has been using our corporate Google accounts for authentication and to insert events into our Google Calendars. The organisation has just switched from Google to Office 365 and I'm trying to switch the code to use Outlook instead - with no success.
I can use the access token to GET https://graph.microsoft.com/v1.0/me and see the basic profile, but if I try to read calendar events or send an e-mail I see the message:
"error": {
"code": "NoPermissionsInAccessToken",
"message": "The token contains no permissions, or permissions can not be understood."
I created an Azure account with my personal Microsoft account and added an application. I added my colleagues and my corporate account as guest users. I set the permissions required and did the admin consent thing:
I then followed the steps on this page.
I first visit https://login.microsoftonline.com/{tenant id}/oauth2/v2.0/authorize, including the following query items:
client_id={client id}
response_type=code
redirect_uri={our URL}
response_mode=query
scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
state={number}
This returns a "code", which I send to https://login.microsoftonline.com/{tenant id}/oauth2/v2.0/token, including:
grant_type=authorization_code
client_secret={client secret}
client_id={client id}
scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
state={same number as above}
redirect_uri={same URL as above}
code={code returned from /authorize}
This returns the id, access and refresh tokens. If I decode the access token using https://jwt.ms/, it seems to contain the appropriate audience and scope:
"aud": "https://graph.microsoft.com"
"scp": "Calendars.ReadWrite email Mail.Send openid profile User.Read"
...although I notice that there is no "roles" entry, which I see in some of the documentation. Is that an issue?
I then send the access token to https://graph.microsoft.com/v1.0/me with the following headers:
"Authorization", "Bearer {access token}"
"Host", "graph.microsoft.com"
"Content-Type", "application/json"
"Prefer", "outlook.timezone Europe/London"
That will return my e-mail address, etc., but if I change the URL to anything else, such as /me/photo/$value, /me/calendar/events, or try to send an e-mail I'm told that there are no permissions in the token.
I see that there are other similar questions, but they are mostly for the client_credentials flow (I'm not sure that makes any difference), and none of the answers has helped me resolve my problem.
Can someone please let me know if I've obviously missed anything - or I'm going about this in the wrong way to access Graph data on the client side? It seemed so straightforward with Google, but I'm finding the Microsoft documentation and examples a bit less detailed.
Adding guest users is meaningless.
What you have done is Admin consent for the Azure AD with your personal Microsoft account.
What you actually need to do is Admin consent for the target Azure AD/ O365 tenant.
Construct a consent link as following:
https://login.windows.net/{tenant ID of the target Azure AD}/oauth2/authorize?response_type=id_token&client_id={client ID}&redirect_uri={reply url}&response_mode=form_post&nonce=a4014117-28aa-47ec-abfb-f377be1d3cf5&resource=https://graph.microsoft.com&prompt=admin_consent
Access it in a browser and log in with an admin account of target Azure AD.
Another issue is that you are using Get access on behalf of a user. So you have to assign Delegated permissions rather than Application permissions in the Azure AD app.

Delete groups in Microsoft Graph API in C#

I get an authorization 401 error code when I try to delete a Group from the API in C# but if I try it in postman it succeeds. Feels kinda weird because I run the same command but it doesn't work...
The problem I think I have is that to DELETE a group in Office 365 I need to login to my account and that the application can't makes this action.
I gave all Group.ReadWrite.All access and all other permissions for the application. So I think I need to pass my Login credentials for Azure AD or am I incorrect.
Request :
StatusCode: 401,
ReasonPhrase: 'Unauthorized',
Version: 1.1,
Content: System.Net.Http.NoWriteNoSeekStreamContent,
Headers:
EDIT
I tried to not use my GetAccessToken() and use the token I got when using OAUTH 2.0 verification in Postman. If I took that bearer token I had no problem running my script and using DELETE.
So my question what the difference of using ADAL in C# code and the call that Postman Auth2.0. When using Postman I get a login page where I login to my Azure account, can I replicate this in code? For the authentication in C# I use this example.
NEW EDIT
As one wrote in the chat, I checked the access token and what roles I had on a website.
roles: [
"EduRoster.Read.All",
"Mail.ReadWrite",
"User.ReadWrite.All",
"Calendars.Read",
"People.Read.All",
"Group.Read.All",
"Directory.ReadWrite.All",
"MailboxSettings.Read",
"Contacts.ReadWrite",
"Group.ReadWrite.All",
"Notes.Read.All",
"Directory.Read.All",
"User.Read.All",
"Mail.Read",
"Calendars.ReadWrite",
"Mail.Send",
"MailboxSettings.ReadWrite",
"Contacts.Read",
"Member.Read.Hidden",
"Notes.ReadWrite.All"]
Some clarification: If you have a token and it doesn't have the necessary claims/permissions to make the API call you are trying, you'll should get a 403 Forbidden. If the token is missing in the API request or malformed, you'll get a 401 Unauthorized. Please see https://developer.microsoft.com/en-us/graph/docs/concepts/errors.
Are you making direct HTTP REST calls to Graph, or are you using the client library? I suggest that you look at some of our samples to get started for examples of token acquisition together with calls to Microsoft Graph. Try https://github.com/microsoftgraph/console-csharp-snippets-sample (uses a .Net client library) or https://github.com/microsoftgraph/aspnet-connect-rest-sample (uses direct HTTP REST calls).
Also are you acquiring a token in the context of a (signed-in) user, or in the context of the application (no signed in user)? If the former, you need to request a "delegated" permission. If the latter, you need to request an "application" permission. Please see these concepts: https://developer.microsoft.com/en-us/graph/docs/concepts/auth_v2_user and https://developer.microsoft.com/en-us/graph/docs/concepts/auth_v2_service
Hope this helps,
You're on the right track.
The Delete Group method support both Delegated (Authorization Code or Implicit OAUTH grants) and Application (Client Credentials OAUTH grant) models. Both Delegated and Application flows require the Group.ReadWrite.All scope.
The reason you're getting a 401 Unauthorized error is that your application hasn't received Admin Consent for the tenant you're connected too. When using Client Credentials there is no User to authenticate so before your application can interact with the tenant, an Admin must first explicitly authorize your application and the scopes you're requesting.
You can find a walk through at v2 Endpoint and Admin Consent.

Resources