Permissions for listing virtual machines with Graph API - azure-active-directory

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.

Related

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.

Authorization request to get access on behalf of a user results in a 'cookiesDisabled' page

I'm trying to do an Authorization request following the documentation about it on Microsoft (Getting access on behalf of a user: https://learn.microsoft.com/en-us/graph/auth-v2-user). I'm making the request using Azure's Logic Apps. I already made an app registration in Azure AD and gave it the following permissions (I used the app for a few different requests before so that's why it contains a lot of unnecessary api permissions). I already succeeded in getting access without a user (https://learn.microsoft.com/en-us/graph/auth-v2-service). Now I really don't know what I'm doing wrong, so if anybody has an idea of what it is, please let me know. I will try to explain as carefully as possible using screenshots so you guys get the idea of what I'm trying to do.
On the first screen below you can see the api permission I added to my app registration. For this request I'm only asking authorization for the one with arrow next to it(as you will see later on).
On the second screen you can see the HTTP post request I'm trying to make to the authorize endpoint. I blurred out the Tenant and Client_id for privacy reasons. I only added the required parameters in the body as described by Microsoft. In the scope parameter you can see the api permission I'm asking permission for.
On the third screenshot you can see the output of the request. Instead of getting an Authorization code as requested, I get an HTML body.
When I paste that HTML body into a browser it gives me the following result:
I have no clue what I'm doing wrong. I tripled checked to make sure cookies are enabled, made sure third-party cookies are not disabled and added login.microsoftonline to my trusted websites.
I'm starting to think I'm doing something very simple wrong, but I can't figure out exactly what. Any help is welcome! :D
Sorry can't add a comment so posting as an answer
What you are trying to implement is the Authorization Code grant flow of OAUTH 2.0. In Authorization code grant flow following steps occur
1) User is presented with the scopes that an application requires when accessing certain resources,
2) The user authorizes this. and the user is redirected to a redirect url
3) The application then exchanges the code sent with the redirect url to get the actual token which in this case will be sent to the Microsoft Graph for validation.
4) User then sees the information pulled.
The major crux of Authorization Code grant flow is that "User Authorization is required" This basically means that this flow is used when the call is invoked from a browser client where the user is actually interacting. This flow should not go through the Azure Logic Apps. If you want a service or a daemon to access the resources in that case you should use Client Credentials Grant flow

invalid_grant error when obtaining access token

I am trying to build a website where a user can log in via Azure AD B2C. After logging in, I'm trying to present a secure area where the user can change their Azure B2C user attributes (first name, last name, etc) via the Microsoft Graph API.
I am attempting to follow along with the Get a Token documentation
Everything is working up to step #3, where a call gets made out to https://login.microsoftonline.com/common/oauth2/v2.0/token to obtain an access_token using the code I received on my return URL.
Here's the general flow of what I am doing:
End user clicks a login link on my localhost site that links out to my Azure B2C tenant policy. Link looks something like this:
https://login.microsoftonline.com/mytenantname.onmicrosoft.com/oauth2/v2.0/authorize
?client_id=[MyAppID]
&response_type=code+id_token
&redirect_uri=http%3A%2F%2Flocalhost%3A17000%2Fprocessing%2Findex
&response_mode=query
&scope=openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.read%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.write
&state=[MyCustomState]&p=[MyCustomPolicy]
User logs in and gets redirected to the redirect_uri.
redirect_uri successfully recieves code, id_token, and state values.
I take the code value from that and makes a POST https://login.microsoftonline.com/common/oauth2/v2.0/token request with the following body:
POST https://login.microsoftonline.com/common/oauth2/v2.0/token
HTTP/1.1
grant_type=authorization_code
&code=[code]
&client_secret=[application secret]
&scope=openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.read%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.readwrite
&redirect_uri=http%3A%2F%2Flocalhost%3A17000%2Fprocessing%2Findex
The response code I receive back from that endpoint is the above error message.
{
"error": "invalid_grant",
"error_description": "AADSTS9002313: Invalid request. Request is malformed or invalid.\r\nTrace ID:6d7a8e32-bcbf-4fc4-a37a-87dae4781b00\r\nCorrelation ID:252912b7-5775-491a-968f-00ab03696dd9\r\nTimestamp: 2019-06-2722:11:18Z",
"error_codes": [9002313],
"timestamp": "2019-06-27 22:11:18Z",
"trace_id": "6d7a8e32-bcbf-4fc4-a37a-87dae4781b00",
"correlation_id": "252912b7-5775-491a-968f-00ab03696dd9"
}
Other StackOverflow posts mention verifying that the redirect_uri's have to match between the initial login and the subsequent access_token requests. They appear identical to me, but I am still receiving errors.
Any ideas what could be going wrong?
This is something you need to understand about OAuth on B2C before you are able to successfully request for a token.
This error means that the requested scope (resource) can’t be accessed by you (login user) because of the lack of permissions.
So, to fix that, you need to grant these required permissions to access that resource, by following these steps:
Define a new scope.
Grant Admin consent on that scope.
Request that scope when you request for a token.
In other words, in B2C-->App Registrations--> (Your App), shown in the image below, start with “Expose an API”, here you define a new scope of access, scope of resources or API, just a metadata that you know it represents some resources or API.
Then you click on “API Permissions”, here you will add the scope you just created and grand admin access in needed. But al least you need to add permissions to your newly defined scope.
The third and last step is when you hit: https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/{policy}/oauth2/v2.0/token
Make sure to pass the scope that you added. (Use the scope that you added)
The details are explained in here but I can simplify it for you.
configure b2c
So you need to go to your B2C
Seems you are trying to get access token using Authorization Code Grant V2.0
Your request doesn't match with Authorization Code Grant V2.0 format and you have encountered that error.
You should send token request for Authorization Code Grant V2.0 is like below:
Token Endpoint: `https://login.microsoftonline.com/common/oauth2/v2.0/token`
client_id:b603c7be-_YourApp_ID-e6921e61f925
scope:https://graph.microsoft.com/User.ReadWrite.All
redirect_uri:https://www.getpostman.com/oauth2/callback
grant_type:authorization_code
client_secret:Vxf1SluKbgu4P_YourAppSecret_DSeZ8wL/Yp8ns4sc=
code:OAQABAAIAAADCoMpjJXrxTq9VG9te-7FXrnBIp82sWR1nC
See Screen shot for details:

Client Credentials access token not working office 365

I am using client credentials flow to generate an access token. Following is the request.
I received the access token and I am using to call Web API like
https://graph.microsoft.com/v1.0/me/mailfolders/inbox/messages
Following is the screenshot
Calling Web API gives InvalidAuthenticationToken Error.
Any workaround on this.?
You're resource should be set to https://graph.microsoft.com.
In your screenshot, theresource is set to https://outlook.office.com but you're calling a Microsoft Graph. Since you're providing an access_token for a different resource, Microsoft Graph is rejecting it.
You also need to make sure you've requested the proper Microsoft Graph permissions in the Azure Portal. To call /mailFolders/inbox/messages for example, you need request permission for either Mail.Read or Mail.ReadWrite.
Finally, you cannot use /me with the Client Credentials grant. The /me is simply shorthand for /users/{current-user-id}/. Since Client Credentials does not have a current user, the API has no idea which user me is. You will need to reference a specific user entity in the path:
/v1.0/users/{userPrincipalName}/mailfolders/inbox/messages

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