invalid_grant error when obtaining access token - azure-active-directory

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:

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.

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

What Scope and or resource to set to get token that works with office 365 api?

We have acquired the Admin consent in both delegated and application ServiceHealth.Read permissions in Office 365 Management API for our Client app in Azure AD.
We are unable to figure out what the scope and or resource needs to be in token acquisition process if we want to make calls to the office365 management api.
Whether its the client_credentials grant method of direct token acquisition
Or the authorization code then token for signed-in user method
It would be preferable if its for the client_credentials grant method, but if it has to be through auth code, that's fine too.
We can use the following already to grab our reports but do not know how to allow that authentication to also cover Office365 Management API Service Health
curl --location --request GET "https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/token" \
--header "Content-Type: application/x-www-form-urlencoded" \
--data "client_id={clientid}&client_secret={clientsecret}&scope=https://graph.microsoft.com/.default&grant_type=client_credentials"
When adding ServiceHealth.Read to the end or by itself it returned invalid_scope as an error
When place only https://manage.office.com/ServiceHealth.Read/.default in the scope it gives the error invalid_resource with the description including that the resource not found in tenant
A similar problem occurred when trying to get the authorization code and setting the resource as ServiceHealth.Read and while setting that as the scope instead gave a authorization code, the resulting token was deemed invalid.
Authorization Code Grant Flow
I quickly tried this out with an Azure AD app registration that has ServiceHealth.Read delegated permission for Office 365 Management APIs.
Scope value used - https://manage.office.com/ServiceHealth.Read
I was able to successfully get back an access token following the Authorization Code Grant flow. I'll share the detailed request parameters passed shortly, but this should answer your direct question about what scope value to use.
Since I used Azure AD V2 endpoints, I didn't really need to specify a resource. In your sample requests mentioned in question I see that you are also using Azure AD V2 endpoint.
Detailed steps
Step 1 - Get the Authorization Code
For this step, I directly used browser and then sign in using a valid user from my Azure AD tenant.
// Line breaks only for clear reading. Remove line breaks and paste in browser URL to test.
https://login.microsoftonline.com/mytenant.onmicrosoft.com/oauth2/v2.0/authorize?
client_id=29a95b.....
&response_type=code
&redirect_uri=https://rohitapp/
&response_mode=query
&scope=https://manage.office.com/ServiceHealth.Read
&state=12345
Response should be something like
https://rohitapp/?code=
OAQABAAIAAACQN9QBRU....
&state=12345&session_state=f5da06....
Step 2 - Acquire Token from token endpoint
Take the Authorization code from last step.
For this step I used POSTMAN. You can use CURL as well.
POST https://login.microsoftonline.com/mytenant.onmicrosoft.com/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded
Request Body
client_id=29a95b....
&scope=https://manage.office.com/ServiceHealth.Read
&code=OAQABAAIAAACQN9QBRU....
&redirect_uri=https://rohitapp/
&grant_type=authorization_code
&client_secret=Aj....
Final Token received, decoded in https://jwt.ms
Client Credentials Grant Flow
Scope value used - https://manage.office.com/.default
I did add the related app permission and give consent for it.
For this one I used POSTMAN again. You can use CURL as well.
POST https://login.microsoftonline.com/mytenant.onmicrosoft.com/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded
Request Body
client_id=29a95....
&scope=https://manage.office.com/.default
&grant_type=client_credentials
&client_secret=Aj....
Final Token received, decoded in https://jwt.ms
Take a look at this Microsoft documentation around scope value for Client Credentials Grant.

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.

Missing Application Claims when completed SignUp policy on Azure B2C

I am implementing the Azure B2C preview in our mobile app but I am having trouble retrieving the application claims once the Signup policy has completed and the redirect_uri is called. I have specified the claims I need returned through the "Application claims" section of the policy blade and similarly through the other two policies (Sign-in and Profile) but I never receive a JWT along with the access code on the callback to the redirect_uri.
I have also tried HTTP and HTTPS in the redirect_uri and using the different response_mode settings but all i get is the code returned.
Am i missing something, or does the signup policy not support returning other claims at this point. I was planning on using them to send a welcome email to the new user.
I think i may have just realised - i need to make a call to the token endpoint to swap my code for the id_token and then i can get the claims.

Resources