msal-node error trying to resolve endpoints - node.js

I have been using MSAL in my React app for some time with success. One of the tokens that my app requests is for scope 'https://management.core.windows.net/user_impersonation'. I have a nodeJS server that I want to push that token acquisition to so I installed msal-node (1.12.1) and tried using the OBO flow:
const pca = new msal.ConfidentialClientApplication({
auth: {
clientId: settings.config.azure.clientId,
clientSecret: settings.config.azure.clientSecret,
authority: "https://login.microsoftonline.com/<tenantid>",
knownAuthorities: ["https://login.microsoftonline.com/<tenantid>"],
}
});
const request = {
scopes: ['https://management.core.windows.net//user_impersonation'],
oboAssertion: <token_extracted_from_auth_header>
}
const response = await pca.acquireTokenOnBehalfOf(request);
return response.accessToken;
However the above code results in the following error:
ClientAuthError: endpoints_resolution_error: Error: could not resolve endpoints. Please check network and try again. Detail: ClientAuthError: openid_config_error: Could not retrieve endpoints. Check your authority and verify the .well-known/openid-configuration endpoint returns the required endpoints. Attempted to retrieve endpoints from: https://login.microsoftonline.com/tenantid/v2.0/.well-known/openid-configuration
If I visit the URL it complains about I do get back some metadata so not really sure why it is failing.
Anybody have a suggestion?
Also in regards to OBO flow:
For my nodeJS app I have added that permission to the required API list
I presume the oboAssertion field is the token that is passed to my nodeJS app by the client? I simply extracted it from the Auth header

The actual error message there means that the URL that we are trying to contact is wrong. And it is wrong https://login.microsoftonline.com/tenantid/v2.0/.well-known/openid-configuration returns an error.
A coorrect one is: https://login.microsoftonline.com/19d5f71f-6c9a-4e7f-b629-2b0c38f2b167/v2.0/.well-known/openid-configuration
Notice how I used an actual teanant_id there. You can get yours from the Azure Portal - it's the "directory id"
If your web api is single tenant, i.e. it is only meant for the people in 1 organization, then the is the tenant id of that organization. It is also known as "directory id". You get it from the Azure Portal.
However, if your api is multi-tenant, i.e. it's a bit more complicated, and the "correct" answer is to use the tenant id of the incoming assertion. It's the tid claim in it.

Related

Postman with OAuth2.0 to a registered app in Azure Active Directory fails with Invalid Resource

I am following the tutorial here: https://learn.microsoft.com/en-us/sharepoint/dev/apis/webhooks/get-started-webhooks
I am having trouble finishing step 5. Postman always gives me this error and I am not sure why.
Troubleshooting details
If you contact your administrator, send this info to them.
Copy info to clipboard
Request Id: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
Correlation Id: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
Timestamp: 2022-11-18T09:34:11Z
Message: AADSTS650057: Invalid resource. The client has requested access to a resource which is not listed in the requested permissions in the client's application registration. Client app ID: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX(Postman App). Resource value from request: https://<mysite>.sharepoint.com. Resource app ID: 00000003-0000-0ff1-ce00-000000000000. List of valid resources from app registration: fe7b6ec1-3281-4dd6-8864-dff33cd1021e, 00000003-0000-0000-c000-000000000000.
Flag sign-in errors for review: Enable flagging
If you plan on getting help for this problem, enable flagging and try to reproduce the error within 20 minutes. Flagged events make diagnostics available and are raised to admin attention.
00000003-0000-0000-c000-000000000000 is Graph.
fe7b6ec1-3281-4dd6-8864-dff33cd1021e is SharePoint Online Client Extensibility Web Application Principal Helper.
In the error it says the app id (00000003-0000-0ff1-ce00-000000000000) that I am trying to use and then lists the valid resources form my app. I can add another resource to the app and it will be listed there in the error message but I do not know how to add my specific resource to the list. Does anyone know how I can do that or if that is even what I need to be doing?
I tried to reproduce the same in my environment and got the results successfully like below:
I created an Multi-Tenant Azure AD application and consented the below API permissions:
To generate the access token, I used below parameters:
Grant Type : Authorization Code
Callback URL : redirect_uri
Auth URL : https://login.microsoftonline.com/common/oauth2/authorize?resource=https://TENANT.sharepoint.com
Access Token URL : https://login.microsoftonline.com/common/oauth2/v2.0/token
Client ID : CLIENTID
Client Secret : ClientSecret
Access token successfully generated like below:
To get Documents list Id click on Use Token and execute the query like below:
GET https://XXXX.sharepoint.com/_api/web/lists/getbytitle('Documents')?$select=Title,Id

Azure B2C React SPA dose not providing access token

I am working on my first project of connecting Azure B2C with MERN App. I wanted to Sign In using Azure B2C and authorise my web API using the Access Token.
I configured everything and applied configurations to this sample React tutorial provide by their documentation.
The problem arises while calling the Web API. The Web API call are sending without any token. When I check the code, acquireTokenSilent function returning empty accessToken from response.
instance.acquireTokenSilent({
scopes: protectedResources.apiHello.scopes,
account: account
}).then(async (response) => {
console.log(response)
The Request is:
Even though I looked many forums and Microsoft technical forums, no answer is not working.
But what I noticed is, it is requesting for grant_type: authorization_code but am not seeing access token in the response. Posting here the API call, request and response.
The Response is producing id_token but not access token,
I gave grant permission in the SPA App permission for task.read scope. I tried everything but I am still receiving the access token as empty. How could I fix this issue?
I tried to reproduce the same in my environment and got below results:
I registered one Azure AD B2C application for app1 and added scopes(task.read) as below:
Now I created one SPA registration and added API permissions by granting consent like this:
I created Sign up and sign in policy and ran the user flow as below:
Please Check authentication and access token and id token:
I signed in as user it gave me auth code in address bar.
https://<tenant name >.b2clogin.com/<tenant name> .onmicrosoft.com/oauth2/v2.0/authorize?p=B2C_1_susi&client_id=<app id>&nonce=defaultNonce&redirect_uri=https://jwt.ms&scope=openid%20https%3A%2F%2F<tenant name>.onmicrosoft.com tasks.read&response_type=code&prompt=login&code_challenge_method=S256&code_challenge=<challenge paramater>
I generated the access token via Postman with commands like this:
POST https://tenant.b2clogin.com/tenant.onmicrosoft.com/policy/oauth2/v2.0/token
grant_type: authorization_code
client_id: SPA_appid
scope: https://tenant.onmicrosoft.com/app1/task.read
redirect_uri: redirect_uri
code: code
code_verifier: code_verifier
Postman
When I decode the token i getting scp in jwt .ms

ASP.NET Core Web App using Work (Azure AD) Authentication works debugging locally, but not after publish to Azure

My ASP.NET Core web app works great when running and debugging locally, but fails to run once published to Azure.
I enabled Organizational Authentication and selected the appropriate domain upon publishing.
The appropriate reply URL was registered
After I publish to Azure I get this error:
An unhandled exception occurred while processing the request.
OpenIdConnectProtocolException: Message contains error: 'invalid_client', error_description: 'AADSTS70002: The request body must contain the following parameter: 'client_secret or client_assertion'.
Trace ID: 640186d6-9a50-4fce-ae39-bbfc1caf2400
Correlation ID: 622758b2-ca52-4bb0-9a98-e14d5a45cf80
Timestamp: 2017-04-19 16:36:32Z', error_uri: 'error_uri is null'.
I'm assuming that it's because the Client Secret needs to be stored in Azure somewhere; however, the value in secrets.json did not work when I added it as an App Setting (invalid client secret error) as I saw someone was able to do on another post. Also not sure if putting the value of "Authentication:AzureAd:ClientSecret" in Azure AppSettings is a good idea anyway.
Not sure if this is useful to anyone or not. But i receive a similar error message.
OpenIdConnectProtocolException: Message contains error: 'invalid_client', error_description: 'error_description is null', error_uri: 'error_uri is null'.
Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler+<RedeemAuthorizationCodeAsync>d__22.MoveNext()
The solution for me was to provide a secret in the token service
,new Client
{
ClientId = "Testclient",
ClientName = "client",
ClientSecrets =
{
new Secret("secret".Sha256())
},
//Hybrid is a mix between implicit and authorization flow
AllowedGrantTypes = GrantTypes.Hybrid,
And provide the secret in the client
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
//The name of the authentication configuration.. just incase we have multiple
AuthenticationScheme = "oidc",
//Represents where to store the identity information -> which points to the cookie middleware declared above
SignInScheme = "Cookies",
//where the token service reside -> system will configure itself by invoking the discovery endpoint for the token service
Authority = "http://localhost:5000",
RequireHttpsMetadata = false,
ClientId = "Testclient",
ClientSecret = "secret",
//hybrid flow -grant type
ResponseType = "code id_token",
Hopefully this helps someone
Somehow I the Azure AD IDs needed for the proper Azure Active Directory App Registration were mixed up. There were 2 App Registration entries and the ClientID and TenentID's didn't match up with the local. So I synchronized the Client and Tenent IDs with one of the App Registration entries, and made sure the Client Secret was in App Settings, and it worked properly.
I verified these steps with this fine example Win's GitHub repository and they match now.

Azure delegated mail reading across office365 domain (nodejs)

Trying to read/write/update the emails of each user within the domain on office365. I'm using Azure Active Directory and an Azure app. I'm the account admin. I've turned on a whole load of permissions at this stage as not sure which ones are necessary.
I'm programming in Nodejs. So...
Authenticate my app, using OAuth, against Azure so that I can access my own application. <- WORKS.
Request admin rights against the account at this URL: https://login.microsoftonline.com/common/adminconsent?client_id='+clientID+'&redirect_uri'+uri where clientID and uri are replaced. This redirects me to authentication against Microsoft platform. You can see all the permissions I have requested (while debugging) here:
Once I accept the permissions it returns me to my app, where it requests a token from: https://login.windows.net/[my-app-tenant-id]/oauth2/token. That returns the access token. So far so good
After that, I then try and use this token to read a user of my organisations emails (for instance me, but there are a few users I have tried it with). It goes to: https://graph.microsoft.com/v1.0/[userEmailAddress#domain.com/messages. I pass the token as a bearer.
This is the problem, I get
{
"error": {
"code": "InvalidAuthenticationToken",
"message": "Access token validation failure.",
"innerError": {
"request-id": "[request-id]",
"date": "2017-03-21T17:31:24"
}
}
}
I have tried this with a couple of URLs, for instance the outlook API, with this url https://outlook.office.com/api/v2.0. I think however that is for simple OAuth and wouldn't work this way anyway.
If anyone can explain how to get the access token to be valid, would be great.
FYI, I am also, simultaneously testing out the npm library azure-graphapi and using:
var clientID = '[client id]'
var clientSecret = '[client secret]'
var tenant = '[tenant id]'
var graph = new GraphAPI(tenant, clientID, clientSecret);
graph.get('users/', function(err, user) {
resp.json({users: user});
})
I can get the list of users. So perhaps I am being stupid and somehow I can use this to read a users email?
Thanks
Maybe you have made a mistake in the request header to get access token.
As you can see, I got a token by sending a POST request to the https://login.microsoftonline.com/common/oauth2/v2.0/token endpoint and passed the value mail.read to the scope parameter in this request.
Now, I am able to get emails of the user with that token.

How to configure permissions for the Azure AD authentication v2.0

I have set up a new web app to be able to use the Oauth2 V2 authorization endpoint. I defined the app in https://apps.dev.microsoft.com/
If I want to obtain a new authorization token, following instructions in
https://blogs.msdn.microsoft.com/richard_dizeregas_blog/2015/09/04/working-with-the-converged-azure-ad-v2-app-model/
I get the following error on the login page:
Sorry, but we’re having trouble signing you in.
We received a bad request.
Additional technical information:
Correlation ID: eb9c2331-32bd-45a9-90d1-e9105f0bfa87
Timestamp: 2016-05-22 18:10:48Z
AADSTS70011: The provided value for the input parameter 'scope' is not valid. The scope https://graph.microsoft.com/Calendar.Read is not valid.
The scope is taken from an example in :
https://github.com/Azure/azure-content/blob/master/articles/active-directory/active-directory-v2-scopes.md
So I imagine it is a valid scope.
In v1 of the OAuth2 protocol, it was necessary to configure access to APIs in the Azure AD of my tenant, prior to using them. So I attempted to do so for the new application.
Attempting to do so, the Azure application management reports an error:
{
"message":"This request has a value that is not valid.",
"ErrorMessage":"This request has a value that is not valid.",
"httpStatusCode":"InternalServerError","operationTrackingId":null,"stackTrace":null,"Padding":null
}
What is missing to be able to use the new authorization endpoint ?
The documentation contains a typo if states calendar.read. It must be calendars.read:
private static string[] scopes = {
"https://graph.microsoft.com/calendars.readwrite"};
Uri authUri = await authContext.GetAuthorizationRequestUrlAsync(scopes, additionalScopes, clientId, redirectUri, UserIdentifier.AnyUser, null);

Resources