The given URL is not allowed by Client_id - azure

I have implemented Google authentication with web API 2 and getting following error:
The given URL is not allowed by Client_id 'ngAuthApp' configuration.
This works when I change AllowedOrigin to (localhost) but not working in api.mytouchstones-uat.net in Client table after azure release.
My code is the following:
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
//Configure Google External Login
googleAuthOptions = new GoogleOAuth2AuthenticationOptions()
{
ClientId = Common.Constant.GoogleClientId,
ClientSecret = Common.Constant.GoogleClientSecret,
Provider = new GoogleAuthProvider()
};
app.UseGoogleAuthentication(googleAuthOptions);

I had the same issue and this was the first google result for me. So I thought I might answer if someone else stumbles upon this question.
I guess you followed this guide, or similar.
Check that your redirect_uri that you send to Facebook/Google etc is the same as the one you have as AllowedOrigin in dbo.Clients.
And make sure that the same uri are allowed in your Facebook/Google appsettings.

Related

msal-node error trying to resolve endpoints

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.

Dynamics 365 Business Central Token

I'm attempting to gain access to Business Central Admin Center API, but I'm having some difficulties.
I'm having the idea that it has something to do with the app registration that I have made in the Azure Portal.
I have (as an admin user of the tenant) registered and app and given it "delegated permissions" to "Dynamics 365 Business Central" with access to "Financials.ReadWrite.All".
I have also created a secret for the app.
My problem is that when I try to access the Admin Center API, I get a "403 Forbidden" response, so I assume that I have either forgotten something, I have created my app registration wrong somehow or that my attempt to access the API, is performed in an inaccurate manor.
If I try to examine the token I get, it doesn't show the permissions that I would expect and have seen in other cases (like with MS Graph API), so I'm thinking maybe it's the token that is the problem.
Here is the code that I use to retrieve a token and my attempt to use it afterwards - maybe someone can spot what I'm doing wrong.
Getting the token
var client_id = "removed_for_security_reasons";
var client_secret = "removed_for_security_reasons";
var tenant_id = "removed_for_security_reasons";
var token_url = "https://login.microsoftonline.com/" + tenant_id + "/oauth2/v2.0/token";
var client = new HttpClient();
var content = new StringContent(
"grant_type=client_credentials"+
"&scope=https://api.businesscentral.dynamics.com/.default"+
"&client_id="+ HttpUtility.UrlEncode(client_id) +
"&client_secret="+ HttpUtility.UrlEncode(client_secret));
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = await client.PostAsync(token_url, content);
// here i print the token so I can check it with jwt.io.
Attempting to use the token
var client = new HttpClient();
HttpRequestMessage req = new HttpRequestMessage();
req.Method = HttpMethod.Get;
req.RequestUri = new Uri("https://api.businesscentral.dynamics.com/admin/v2.11/applications/businesscentral/environments");
req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
"Bearer", access_token);
var res = await client.SendAsync(req);
// this results in "403 Forbidden"
There is no further information given as to why this is forbidden, so I'm having a hard time pin pointing what the problem is.
Does anyone have suggestions?
UPDATE 1
OK, so I have tried to follow the description linked. It doesn't describe which permissions box to check though and it's also using PowerShell which I'm not - I'm using C# with HttpClient.
So, to not circle around this any further, please try to explain which to select here (see images) and/or what is wrong/missing.
Image 1 (the app), what is wrong/missing:
Image 2 (permissions 1), what is wrong/missing:
Image 3 (permissions 2), what is wrong/missing: (admin grant doesn't seem to change anything)
After this, I create a client secret and use the code posted initially.
Of cause this isn't working as expected. If the code is wrong, then please point out what the problem is - referring to the description on the web doesn't help me, as it is vague at best.
I think the issue is your combination of delegated permissions and trying to use the client credential flow.
Client credential flow requires application permissions which is also why your delegated permissions are not shown in your token. The client credential flow does not grant you the delegated permissions.
Even though it doesn't seem to be stated directly anywhere that Admin Center API doesn't support client credential flow, I think it is implied in the documentation.
In Using Service-to-Service (S2S) Authentication the Admin Center API is not mentioned in the Feature availability matrix and The Business Central Admin Center API does not mention client credential flow at all and all the example are using user impersonation.
Your App Registration looks okay to me. You will however need to provide the admin consent.
As described in the article I linked above you need to use MSAL (Microsoft Authentication Library). Since you are using C# you need to use MSAL.NET.
I am not an expert on C#, but maybe this quickstart guide could lead you in the right direction.

How to consume Graph API with a ADAL token?

in my Xamarin.forms project, I use ADAL (Microsoft.IdentityModel.Clients.ActiveDirectory) to authenticate on the Azure portal (Auth 1.0 endpoint). That part work great, but I need to get the security group of the user. So I use this code and passing the token received with ADAL:
HttpClient client = new HttpClient();
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me/memberOf");
message.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", token);
HttpResponseMessage response = await client.SendAsync(message);
string responseString = await response.Content.ReadAsStringAsync();
I always got StatusCode: 401, ReasonPhrase: 'Unauthorized'.
In my azure AD app registration, I add the Graph API and these permissions:
I think I miss something. Any idea?
----- EDIT 1 ---
Here my payload. I changed it for a picture for lisibility. I don't know how to post json here
----- EDIT 2 ---
OH! I see. I think I need to understand more the Azure Login process. For now I follow an example of ADAL and Azure that let my log and use some function in my backend. So the login process use:
var authContext = new AuthenticationContext(authority); var authResult = await authContext.AcquireTokenAsync(resource, clientId, uri, platformParams);
Where authority = https://login.microsoftonline.com/mysite.com, ResourceID is my backend app ID and clientID is my native app ID. So Shawn is correct, I do not use the Graph.microsoft.com to get the token. Do we have another way to achieve all that? The need of using Graph is only to get the AD group the user has to adjust permission inside the app.
You are correct in your comment. If you add a new permission to your application, you must ask the user to re-consent to the app.
You can force re-consent through ADAL by setting the PromptBehavior to Always:
platformParams.PromptBehavior = PromptBehavior.Always
Or you can simply modify your Login URL to force it, by adding the query string:
&prompt=consent
In terms of building an app to help overcome this problem, if you think your app will be changing permissions after release, you can integrate logic which detects Unauthorized, and then sends the user to re-consent.
Another option is for your app to track changes which may require a new consent prompt, and detect when the user uses this new version of your application the first time, and asks them to consent.
In our new App Model V2, we support the concept of Incremental and Dynamic Consent, which should get rid of this problem all together for you.

Oauth2 flow without redirect_uri

I am creating an Android/iOS app which communicates with a Node.js server and would like to identify them securely on my server using Google (and/or Facebook) and OAuth2. I've looked at the following documentation: https://developers.google.com/+/web/signin/server-side-flow
I do not need authorization, I only need authentication (I only want to make sure that the person calling my Node.js service is the person they say they are). To achieve this, if I understand properly, I have to let the user log in using Google on the client side, this will give them an authorization_code which they can then give to my server. My server can then exchange that code for an access_token, and therefore retrieve information about the user. I am then guaranteed that the user is the person they say they are.
The Google documentations (link above) says: "In the Authorized redirect URI field, delete the default value. It is not used for this case.", however, for my server to exchange the authorization_code for an access_token, it needs to provide a redirect_uri, am I missing something?
The redirect_uri is useless for Unity games, for instance (since logging in with Google simply opens a new "window", which is closed when logged in, no redirection involved).
TL;DR
How do you use OAuth2 to authenticate users between my client and my server without redirection?
TL;DR How do you use OAuth2 to authenticate users between my client and my server without redirection?
You can't. OAuth requires that the user is directed to an authorization (and possibly login) screen, and then redirected back to your app.
EDIT 20/12/22. See comment below regarding latest status
Have you looked at this documentation? https://developers.google.com/accounts/docs/OAuth2InstalledApp#choosingredirecturi
Choosing a redirect URI
When you create a client ID in the Google Developers Console, two
redirect_uris are created for you: urn:ietf:wg:oauth:2.0:oob and
http://localhost. The value your application uses determines how the
authorization code is returned to your application.
http://localhost
This value signals to the Google Authorization Server that the
authorization code should be returned as a query string parameter to
the web server on the client. You may specify a port number without
changing the Google Developers Console configuration. To receive the
authorization code using this URL, your application must be listening
on the local web server. This is possible on many, but not all,
platforms. If your platform supports it, this is the recommended
mechanism for obtaining the authorization code.
I had this problem and it took me ages to find the "postmessage" solution that Nepoxx mentions in the comments of the accepted answer here.
For clarification, here's what worked for me.
Follow steps 1-6 here: https://developers.google.com/identity/sign-in/web/server-side-flow
Install googleapis library npm install --save googleapis
For the server-side token exchange do this:
var googleapis = require('googleapis');
var OAuth2 = googleapis.auth.OAuth2;
var oauth2Client = new OAuth2(
GOOGLE_SSO_CLIENT_ID,
GOOGLE_SSO_CLIENT_SECRET,
'postmessage' // this is where you might otherwise specifiy a redirect_uri
);
oauth2Client.getToken(CODE_FROM_STEP_5_OF_INSTRUCTIONS, function(err, tokens) {
// Now tokens contains an access_token and an optional refresh_token. Save them.
});
The redirect_uri can be a URL with a custom URL scheme for which the client registered a handler. This is described here: What's a redirect URI? how does it apply to iOS app for OAuth2.0?. It is not so much about "redirecting" it is about a callback endpoint to your app.
And it become really easy if you use VueJS with https://github.com/guruahn/vue-google-oauth2
Client side
import GAuth from 'vue-google-oauth2'
Vue.use(GAuth, {
clientId: 'xxxxxxx.apps.googleusercontent.com',
scope: 'profile',
})
async signWithGoogle() {
const code = await this.$gAuth.getAuthCode() //
console.log(code ) // { code: 'x/xxxxxxxxxx' }
// send the code to your auth server
// and retrieve a JWT or something to keep in localstorage
// to send on every request and compare with database
}
Server side
import { google } from 'googleapis'
const oauth2Client = new google.auth.OAuth2(GOOGLE_ID, GOOGLE_SECRET, 'postmessage')
google.options({ auth: oauth2Client })
async function getAccount(code) {
// the code you sent with the client
const { tokens } = await oauth2Client.getToken(code)
oauth2Client.setCredentials(tokens)
const oauth2 = google.oauth2({ version: 'v2' })
const { data: { id } } = await oauth2.userinfo.get()
// there you have the id of the user to store it in the database
// and send it back in a JWT
}

Why does AcquireToken with ClientCredential fail with invalid_client (ACS50012)?

Why won't my Azure AD application allow an oauth client_credentials grant?
I want to use the Azure Graph API, but first I need an oauth token. To get the token, I am trying to use Microsoft.IdentityModel.Clients.ActiveDirectory aka ADAL version 1.0.3 (from NuGet).
I'm using the overload of AuthenticationContext.AcquireToken that takes a ClientCredential object. (I can't use the overload that prompts the user to login because I'm writing a service, not an app.)
I configured my Azure AD web application as described in various tutorials/samples (e.g. ADAL - Server to Server Authentication).
My code looks like:
AuthenticationContext ac = new AuthenticationContext("https://login.windows.net/thommmondago.onmicrosoft.com");
ClientCredential cc = new ClientCredential("41151135-61b8-40f4-aff7-8627e9eaf853", clientSecretKey);
AuthenticationResult result = ac.AcquireToken("https://graph.windows.net", cc);
The AcquireToken line throws an exception:
sts_token_request_failed: Token request to security token service failed. Check InnerException for more details
The inner exception is a WebException, and the response received looks like an oauth error:
{ "error":"invalid_client",
"error_description":"ACS50012: Authentication failed."
"error_codes":[50012],
"timestamp":"2014-03-17 12:26:19Z",
"trace_id":"a4ee6702-e07b-40f7-8248-589e49e96a8d",
"correlation_id":"b304af2e-2748-4067-99d0-2d7e55b121cd" }
Bypassing ADAL and using curl with the oauth endpoint also gives the same error.
My code works if I use the details of the Azure application that I found here:
AuthenticationContext ac = new AuthenticationContext("https://login.windows.net/graphDir1.onmicrosoft.com");
ClientCredential cc = new ClientCredential("b3b1fc59-84b8-4400-a715-ea8a7e40f4fe", "FStnXT1QON84B5o38aEmFdlNhEnYtzJ91Gg/JH/Jxiw=");
AuthenticationResult result = ac.AcquireToken("https://graph.windows.net", cc);
So it's not an error with my code. I think it's either an error with my Azure AD, or I've got the ClientCredential parameters wrong.
This turned out to be an error in Windows Azure, there was nothing wrong with my code or config.
After Microsoft fixed the problem in Azure, I had to create a new application and it started working.
Forum answer from Microsoft:
Hi,
We are seeing some errors with applications created in a several day time range, ending yesterday. We are continuing to fix up these applications but I don't have a good eta when this will be done. I'm apologize for the impact here.
Can you try creating a new application and retying the operation with the new client id?
thanks
Have a look at this link: https://azure.microsoft.com/en-gb/documentation/articles/resource-manager-net-sdk/
The latest version of Active Directory Authentication Library does not support AcquireToken method, instead you have to use AcquireTokenAsync method.
var result = await authenticationContext.AcquireTokenAsync(resource: "https://{domain}.onmicrosoft.com/{site-if applicable}", clientCredential: credential);
I was having the same issue but only running the code directly from Azure (inside an Azure Website).
I solved upgrading 'Microsoft.IdentityModel.Clients.ActiveDirectory' package to '2.6.1-alpha'
The azure version of the translator has changed things once more- the Oauth token request uses a new url and only needs your secret key, instead of all the other baggage. This page discusses it (but using PHP code): http://www.bradymoritz.com/php-code-for-bingmicrosoftazure-translator/
The key items are:
Post an empty request to https://api.cognitive.microsoft.com/sts/v1.0/issueToken
Pass it your secret key using the header "Ocp-Apim-Subscription-Key: "
Or, just use the querystring parameter: "Subscription-Key="
Then get the body of the return as the actual token- it's the whole body, not in json format.
This is a lot simpler than the method used before, but it'd definitely a pain that things have yet again changed.

Resources