Register Application in Azure AD - node.js passport-azure-ad example - node.js

I am trying to setup a authentification for POST requests on my Node.js server hosted # Azure.
I am using this example:
passport.use(new OIDCStrategy({
callbackURL: config.creds.returnURL,
realm: config.creds.realm,
clientID: config.creds.clientID,
clientSecret: config.creds.clientSecret,
oidcIssuer: config.creds.issuer,
identityMetadata: 'https://login.microsoftonline.com/TenantGuidOrTheWordCOMMON/v2.0/.well-known/openid-configuration',
skipUserProfile: config.creds.skipUserProfile,
responseType: config.creds.responseType,
responseMode: config.creds.responseMode,
(tenant: "Guid from AzureAD-Endpoints-Button"),
(validateIssuer: false/true)
}, (...)
Although my code redirects me to a "https://login.microsoftonline.com" page (which is nice), after entering my email-address it immediately redirects me somewhere else.
There I get an error in the browserUrl: "the client does not exist"...
and it says I should create an application # "https://apps.dev.microsoft.com".
WHY? I have a AppService "MyService", an Azure AD within the same subscription and within the Azure AD an "App registration" for "MyApp".
What is now this cruel apps.dev.microsoft site? Why is there not my registered "MyApp" shown and Vice versa?
What do I have to enter within "oidcIssuer"? the MyApp.ApplicationId? The (apps.dev.microsoft.com)-Application.ApplicationId? The AzureAD-ClientId? The AzureAD-IssuerUrl?
The same question for the clientSecret
Whats the difference between using identityMetadata with an ID instead of "common" + validateIssuer:true against using identityMetadata with "common", validateIssuer:false + tenant:"myTenant(Guid?)"
When I Use "ExpressSettings" within Authentication/Authorization-->AzureAD why can I not find the Application I defined in Azure AD?
Do I have to activate the Graph API (I dont know anything about it yet)
Are there good alternatives protecting my express.post endpoint with authentification in Azure AD? (ADAL seems to be for resources)
I dont get all this settings, properties and portals of Microsoft I am just overhelmed by all this... (not to mention there is also an "OLD" portal)
The next days I will try this Azure Step-By-Step Guide maybe It will help me somehow...

For this example you are using, you don't need to modify the params in OIDCStrategy object. Instead, you need to config your AAD settings in client_config_*.js. files. Just like the document describes at https://github.com/AzureAD/passport-azure-ad/tree/master/examples/login-oidc.
And BTW, we manage our AAD applications on the Classic Portal.

Like my answer to "Has anyone successfully used Azure AD to authenticate users for a Node.js web application?"
I setup my authentification like this instead (without code) in the new Azure Portal:
host my Node.js Server
add an AD to the subscription
Register new application within the AD
Add "https://YourNodeJS.azurewebsites.net/.auth/login/aad/callback" as Reply URL
In AppServices, pick your Node.js Server
In Settings go to Authentication/Authorization
Activate AAD
Use Advanced Mode of AAD
Enter the ClientID (GUID) of the application registered above in AD
As issuerURL enter this link: https://sts.windows.net/YourADGuid/ (you can see the GUID within "Endpoints" if you look back at your application registered in AD above)

Related

Cant Authenticate Single Tenant Angular Application

I'm creating an angular application that should authenticate with MS Azure AD single Tenant App which should be used only in one organization. Below are the configs which I have tried
auth: {
clientId: 'MY_CLIENT_ID',
// authority: 'https://login.microsoftonline.com/MY_TENANT_ID',
//authority: 'https://login.microsoftonline.com/MY_ORGANIZATION_DOMAIN',
authority: 'https://login.microsoftonline.com/organizations',
redirectUri: 'http://localhost:6735'
},
All thes above ways of authority I have tried. It goes to the login page of Microsoft but after giving correct credentials it redirects with some code in the URL and login doesn't happen.
http://localhost:6735/#code=0.ASgAmOTRM_cEXkaKjvmSz2YuZyqUYHleyNlFoNYtQ5kOUEUAAAA.AQABAAIAAAD--DLA3VO7QrddgJg7WevrHDMc_BSj9GrzkrZl2zT2QVp1Hml8h7qs1PSWM_umvMyKRk5U0C7IbDSpdEpL9SGjWzBFHBXBXh10eLEioVh1N8-hXeNyfLJFSqXShYPooCX8UnlUnIQqgFhULy_o1f7ybLLbMELBomOnJZQKZuJoxj6UJgtERnAE1TZ5-nx4YkPHSrlOD5aYSF6Pziu2Xfh8UOMArIUMAoXe_RUoqULKSIHFsxXypPpCNDo1ddWsxId96BbDdPhHix2IWCuz3SNtKC6i_22qiQSxHJnT3NlcoxyMS0-9f9tSMSEOmrzCU0y5mbuw7-OGYPO8Na3juGParCuPQhE7ZJyXcwFkKodEdGs-C1U-f5Bc_imtik4B8x6sRB2pa-DOAueRQHsLdUUBQn6w5xRmZ97KKXxuL0A59EHbNhNu59EFoVJB6zTTT3hBHLFg7qL9g2nkfZLAlfpp9IfqnsoZVl9xT0CIbl7NvsRFnjpsyp6Sw4oFvyEHiXuRvKLkl3Jz8O56PJody2hHEeqXuQvnWbZ9nk00MPOvArQ7bKyoCusCPQQp64uoPSLW9G389a3ihHLiiNlzJik2dHWjez2wBpSPwZCOingPRi3Mtkh5pIbxfijejQmWZlXB_wf_GaNPYPGNRXYygeo-2OZ9koWDKhQ5S6GP5ktjGPfDtlh6EJNCHAIuuHbK2IN2vjbxdO4_YVLX1NKq0Hh51B4-zNdsiFlZuVsy5RyA3ZQZGsnR1NIKV_wm5jMmdDsgAA&client_info=eyJ1aWQiOiJlYzczZDQ5OS1iYzFiLTRhZWUtYjMyZi0xYjlmOTMyODRiNjAiLCJ1dGlkIjoiMzNkMWU0OTgtMDRmNy00NjVlLThhOGUtZjk5MmNmNjYyZTY3In0&state=eyJpZCI6IjY3YWVjYjVkLWE5YjUtNDBhMy1iZDE5LWRmYmNmNjcxNTkwZiIsIm1ldGEiOnsiaW50ZXJhY3Rpb25UeXBlIjoicmVkaXJlY3QifX0=&session_state=9e6ae9e7-45ae-4fee-b4b2-921f628093ec
Please check if any of the below is your workaround
If your application audience is a single tenant, you must provide an authority with your tenant id as you tried first:
auth: {
clientId: 'your_client_id',
authority: 'https://login.microsoftonline.com/{your_tenant_id}'
}
};
By default, MSAL is configured to set the redirect URI to the current page that it is running on. If you would like to receive the authorization code on a different page than the one running MSAL, you can set this in the configuration. Any redirect URI used must be configured in the portal registration
If it is SPA, please check if you have selected platfom as SPA in app registration in portal and check the URIs type in the manifest file to be Spa . Make sure you do not have multiple platforms configured in azure (for eg both SPA & Web App for same localhost uri).
Try to give the redirect uri like this with ‘/’ at the end :http://localhost:4200/ or http://localhost:6735/ or redirecturi:'/' and make sure you configured the same uri in the application code and try again .
Make sure your client id and tenant id are given correctly. Local host is probably used while in development.If it still doesn’t work configure with https scheme in redirect uri in both app and in portal.
Reference:
AzureAD/microsoft-authentication-library-for-js (github.com)
Quickstart: | Microsoft Docs

Unable to get access token. 'AADSTS500011: The resource principal named 'xxx' was not found in the tenant -tenantid

I am trying to get the access token for the Azure function app. I have enabled managed identity for the function app(system assigned). but while fetching the token using the nuget Azure.Identity.
var tokenCredential = new DefaultAzureCredential();
var accessToken = await tokenCredential.GetTokenAsync(
new TokenRequestContext(scopes: new string[] { "https://xxx.azure-api.net/" + "/.default" }) { }
);
I am getting the error.
The resource principal named 'xxx.azure-api.net' was not found in
the tenant 123
but when run az cli to check the subscription details, the subscription indeed part of the tenant 123 only.
Here is what I have finally done.
I have registered an App in AD. and Exposed the API of that App.
I have assigned System Assigned Managed Identity to the Function.
In the local I am not able to request token because Azure CLI is not given consent.
After deploying the application in Function my Function app can request a token using its identity.
You need to register the application in azure ad and enable the access token. Once that is done the you need to provide RBAC access to your xxx.azurewebsites.net
Follow this article for the step by step documentation Microsoft Document Reference
Unfortunately, the error message is not really helpful. But adding a scope to the app registration solved the problem for me:
In Azure Portal navigate to App Registrations
Find your app, in the left side menu select Manage => Expose an API
Add a scope. I named mine api_access as this was where this error occurred.
In my case I then got an API URI (like api://client-id/scope_name) which I used in my Angular app. Error message was gone.
Also, make sure that in the Enterprise Application you have created, under Manage => Properties, "Assignment required" and "Visible to users" is turned on.

MS Identity Azure app registered but sends unauthorized_client in implicit flow

I have registered an app in Azure for Microsoft Identity platform. I configured it to allow MS Accounts (e.g. outlook.com) and have basically done everything in a few of the quickstarts online here and here (except for "add credentials to your web app"). I have also checked the boxes that enable implicit flow.
I redirect my React application to the URL to sign in (using implicit flow), I get to enter my username but then I see
unauthorized_client: The client does not exist or is not enabled for consumers. If you are the application developer, configure a new application through the App Registrations in the Azure Portal at https://go.microsoft.com/fwlink/?linkid=2083908
Like I mentioned above, I've gone through several quick starts and read about implicit flow here and followed their examples for my code.
I also tried just deleting the app registration and starting over. No luck.
JS Code attempting to implement Implicit Flow
JS code that redirects the browser to a Url that looks like Microsoft's first example on their implicit flow page
goSignIn() {
const tenant = 'common'; // (for us with MS accounts)
const clientId = '*****';
const redir = encodeURIComponent('http://localhost:3000/signin');
const nonce = Math.round(Math.random() * 10000, 0);
const uriTemplate = 'https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?client_id={clientId}&response_type=id_token+token&redirect_uri={redirect}&scope=openid&response_mode=fragment&state={state}&nonce={nonce}';
const filledTemplate = uriTemplate
.replace('{tenant}', tenant)
.replace('{clientId', clientId)
.replace('{redirect}', redir)
.replace('{nonce}', nonce)
.replace('{state}', nonce);
console.log(filledTemplate);
window.location = filledTemplate;
}
App Configuration in Azure:
Azure -> Identity -> App Registrations -> MyApp -> Authentication
Redirect Uri: http://localhost:3000/signin (React app runs on 3000 and I have a route configured for /signin)
Not using any suggested Redirects.
Checked Implicit checkboxes for ID Token and Access Token
Live SDK support enabled
Supported account types is set to "Accounts in any organizational directory and personal Microsoft accounts (e.g. Skype, Xbox, Outlook.com)"
Azure -> Identity -> App Registrations -> MyApp -> API Permissions
MS Graph
User.Read
Email
Profile
openid
From the docs I read, I thought I had done enough to the id token. I'm not sure what tweak must be made in order to get it to work.
I experienced an issue like this one. The mistake I made has to do with the App ID: when you create the client secret the Azure UI will present the secret and the secret ID. This secret ID is not the one to use in your app's configuration. Rather, you need the Application ID found on the Overview page.
I imagine that there are many configuration problems which can produce this error message. In general: pay close attention to the App ID, if the error is that the app is not found.
It seems that you have done enough to get the token. I have tested this on my side, it works well. Here I provide you with my screenshot for you to check again.
Also, here is my working request url, you can login with your msa to have a test.
https://login.microsoftonline.com/common/oauth2/v2.0/authorize?
client_id=5fd66168-7ba3-4bbc-a155-bff662eed9f7
&response_type=id_token+token
&redirect_uri=http://localhost:3000/signin
&scope=openid
&response_mode=fragment
&state=12345
&nonce=678910

AADSTS70005: response_type 'id_token' is not enabled for the application

AADSTS70005: response_type 'id_token' is not enabled for the
application
I am getting above error even after setting "oauth2AllowImplicitFlow": true, in manifest.
try this:
go to portal.azure.com
select your directory, and go to Azure AD
then select App registration (preview)
select the app you are trying to authenticate (you should already have registered it)
go to the authentication tab
check "ID tokens" in the Advanced Settings section (see the bottom of the attached image)
this have worked for me
I got the error:
AADSTS700054: response_type 'id_token' is not enabled for the application.
And the resolution was setting:
{
"oauth2AllowIdTokenImplicitFlow" : true
}
in Azure Active Directory App Manifest
Make sure you have selected ID tokens (used for implicit and hybrid flows)
You can do from Authentication blade in your app in Azure AD. See screenshot below
Or go to the Manifest blade and make oauth2AllowIdTokenImplicitFlow to true. See screenshot below
Error : OpenIdConnectMessage.Error was not null, indicating an error. Error: 'unsupported_response_type'.
This error occurred because Azure AD not return any Access tokens or ID tokens.
Azure AD need to enabled check box to return tokens, after authentication is done.
How to Solve : goto Azure AD => App registration => click tab Authentication =>
enabled Access tokens and ID tokens check-boxes.
Make sure you don't have two instances of the key oauth2AllowImplicitFlow in your manifest - in my case I had added the key but it was present already with the value set to false. Hopefully this solves the issue:)
I was facing similar issue and when visited the page of ActiveDirectory -> App registrations, it wasnt showing new UI.
Also it doesnt allow me to set the flag in the metadata, Found the workaround for this.
https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/Authentication/quickStartType//sourceType/Microsoft_AAD_IAM/appId/9bab1d75-34b8-475b-abfe-5a62c6f01234/objectId/a4b459c1-7753-400c-8f8f-46fb5451234/isMSAApp//defaultBlade/Overview/servicePrincipalCreated/true
First login to your instance, modify the above URL to paste object id and application id of your application.
Then it should show the screen #Mosè Bottacini posted.
It is true like a lot of you are saying that you need to enable ID tokens (used for implicit and hybrid flows) if you really need the ID Token.
'AADSTS700054: response_type 'id_token' is not enabled for the
application.
However if you use a Authorization Code Flow you don't really need it. Microsoft OpenID Connect authentication (Microsoft.AspNetCore.Authentication.OpenIdConnect) uses id_token as default ResponseType for OpenIdConnect and JwtSecurityTokenHandler.
Using AddOpenIdConnect you can set ResponseType to OpenIdConnectResponseType.Code or simply "code" and then you don't need the id_token at all.
Working example with Azure Ad and IdentityServer:
services.AddAuthentication()
.AddOpenIdConnect("aad", "Azure AD", options =>
{
options.ClientSecret = "<ClientSecret>";
options.ResponseType = OpenIdConnectResponseType.Code;
options.ClientId ="<ClientId>";
options.Authority = "https://login.microsoftonline.com/<TenantId>/";
options.CallbackPath = "/signin-oidc";
})
.AddIdentityServerJwt();
http://docs.identityserver.io/en/latest/topics/signin_external_providers.html
I stumbled across this post since I was having the exact same issue with my Azure App Service. I fixed it by using the exact redirect URL in the error message and adding that to the list of URLs in the app registration.

Azure Graph API: authorize application on multiple tenants

I am trying to create an application to browse my contacts directory on Exchange.
I have set up everything and I am able request the authorization from my app.
I can present the modal view, enter the login information, retrieve the token, but when I try to authorize the app with the same account I have created it I get this message:
The client <my app id> and resource <my app URI> identify the same application.
If I try to authorize another account, I receive this message instead:
User account <an email> from external identity provider <a url> is not
supported for application <my app id>
If I try to login on the Graph Explorer Console or on the Office 365 OAuth Sandbox, they work fine with the second address, but not with the first one.
I am really confuse. I feel like I have mess up some configuration option, but I don't really understand which one.
Regarding #1, please do not pass App ID of your application for resource querystring parameter when authenticating against your tenant URL. I ran into the exact same problem.
Then I ran WebApp-MultiTenant-OpenIdConnect-DotNet from Github and noted down the sign-in URL it created and I used the following:
var signInUrl = String.Format(
"https://login.windows.net/{0}/oauth2/authorize?response_mode=form_post&response_type=code+id_token&scope=openid+profile&client_id={1}&resource={2}&redirect_uri={3}&state={4}&nonce={5}",
Uri.EscapeDataString(tenantId),
Uri.EscapeDataString(clientId),
Uri.EscapeDataString("https://graph.windows.net"),
Uri.EscapeDataString(redirectUri),
Uri.EscapeDataString(state),
string.Format("{0}{1}", DateTime.UtcNow.Ticks, Guid.NewGuid().Stringify())
);
Basically I used https://graph.windows.net instead of App ID and magically things started to work :).
Another thing you could try (and I have not tried it) is authenticating against common endpoint https://login.windows.net/common/oauth2/authorize and provide your App ID for the resource querystring.

Resources