How do I check to see if my AzureAD version is V1 or V2? with middle ware - azure-active-directory

AZURE AD V1 V2
above all agree but v1.0 tokens contain both the x5t and kid claims, v2.0 tokens contain only the kid claim. and i m using ISecurityTokenValidator custom token validator
public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
var principal = _tokenHandler.ValidateToken(securityToken, validationParameters, out validatedToken);
will this be going to be impacted ?? after i will start using V2 end point and token ??

Token validation will keep working fine. You might need to change JWT claim type mapping though.

Related

AddMicrosoftIdentityWebApi .net core 5 web api ? will this support version V1 and V2 Api ? MSAL

i m using react my front end using ADAL.js and my back end using
MSAL ### below is code
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAd"))
as my front app use ADAL.js its create V1 token and in back end i have MSAL ?
how i can support this situation ?
as i want to impose my back end to understand V1 token which is created by front app ADAL.js
Yes, it is possible to request an V1 access token and even V2 depending on the requirement. .
But please check which token the API needs as:
Idtoken: If you ask for an ID token from the V1 endpoint, you get a V1 ID token. If you ask for an ID token from the V2
endpoint you get a V2 ID token.
Accesstoken: Access Tokens versions are determined by the configuration of your application/API in the manifest.
The access token type (v1 or v2) which is issued to your app is determined by the application registration of the resource API.
You can determine which type of tokens your API is configured to accept making small change or seeing what is present in app registration. In portal,when you go to the "Manifest" section, and check for "accessTokenAcceptedVersion". If it is set to null or 1, then all client applications requesting access tokens to call this resource will get a v1 access token (Regardless if they use MSAL or ADAL to request the access token).
And you may need to request a scope with /.default for example: https://database.windows.net//.default
According to Scopes for v1.0 apps (MSAL) | Microsoft Docs
NOTE:
For ADAL with a v1.0 access token , aud=resource
For MSAL accepting v2.0 tokens, aud=resource.AppId
For MSAL v2.0 endpoint getting an access token for a resource that accepts a v1.0 access token (which is the case above), Azure AD
parses the desired audience from the requested scope by taking
everything before the last slash and using it as the resource
identifier. Therefore, if https://database.windows.net expects an
audience of https://example.com/, you'll need to request a
scope of https://example.com/.default
Reference : authentication - Is it possible to obtain an Azure AD V1 token using MSAL? - Stack Overflow

How to obtain an Azure B2C bearer token for a non-interactive/daemon application and get it validated in an Azure HTTP-triggered function

There is a C# application under development that is supposed to be a part of a bigger backend application to process some data. This application is supposed to obtain a token from Azure AD B2C and send it to an HTTP-triggered function where it is supposed to be validated by the following code:
var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(
$"{_authenticationSettings.Authority}/.well-known/openid-configuration",
new OpenIdConnectConfigurationRetriever());
var config = await configManager.GetConfigurationAsync();
_validationParameters = new TokenValidationParameters
{
IssuerSigningKeys = config.SigningKeys,
ValidateAudience = true,
// Audience MUST be the app ID aka clientId
ValidAudience = _authenticationSettings.ClientId,
ValidateIssuer = true,
ValidIssuer = config.Issuer,
ValidateLifetime = true
};
var tokenHandler = new JwtSecurityTokenHandler();
var result = tokenHandler.ValidateToken(authHeader.Parameter, _validationParameters, out var jwtToken);
First, we thought that obtaining an access token from Microsoft Graph API using MSAL would help us but the C# code above threw an invalid signature exception which we discovered makes sense due to this GitHub post. Apparently, we need to obtain an id_token instead in the application and send it to the HTTP-triggered function for validation by the code snippet above.
The application cannot obtain the id_token because it's not supposed to launch Azure AD B2C's login UI to have a user sign-in and redirect it through a URL. What is the solution to this problem so that the application would obtain a token without a UI and send that to the http-triggered function for validation?
Obtaining a token for the AAD B2C tenant without UI is possible in two ways and you should probably pick one depending on what exactly you want to achieve:
user token - by using Resource Owner Password Credentials flow - https://learn.microsoft.com/en-us/azure/active-directory-b2c/add-ropc-policy. This flow is deprecated though and mentioned usually in legacy application context
server-side application token - by using Client Cretendial flow - this on the other hand requires using requests specific for AAD but with AAD B2C tenant - https://learn.microsoft.com/en-us/azure/active-directory-b2c/application-types#daemonsserver-side-applications
I'm also not quite sure why should you use id_token for that. If the application needs to authorize the request to the function with the token then it should be an access token regardless of how the token is retrieved (interactive UI or not).

How to add a claim in the bearer send by httpinterceptor of adal-angular

In a angularjs application, i use adal and adal-angular libraries to authentify user on Azure AD. On backend I use OWIN middleware in my webAPI to add custom claims with :
app.UseWindowsAzureActiveDirectoryBearerAuthentication(new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Audience = ConfigurationManager.AppSettings["ida:Audience"],
Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
Provider = new OAuthBearerAuthenticationProvider()
{
OnValidateIdentity = async context =>
{
if(!context.IsValidated)
return;
var userManager = context.OwinContext.Get<UserManager>();
string email = context.Ticket.Identity.GetClaimValue(System.Security.Claims.ClaimTypes.Email);
User user = userManager.GetByEmail(email);
context.Ticket.Identity.AddClaim(new Claim(ClaimTypes.UserId, user.Id.ToString(CultureInfo.InvariantCulture));
}
}
});
It's work for the current request, but how to add the claim in the bearer send by httpinterceptor of adal-angular for the next requests?
To answer your direct question: you cannot modify the access token, period.
It has a digital signature which will no longer be valid if you change anything in the token.
It's a security measure that prevents tampering.
Your OWIN middleware downloads the public keys of the signing key pairs from Azure AD on startup, and uses those to validate tokens.
Now if you stored your internal ids as extension attributes,
it would actually be possible to tell Azure AD to include that in the tokens.
This feature is in preview though, and not recommended for production use: https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-optional-claims#configuring-custom-claims-via-directory-extensions.
Here you would set the internal id as an extension on the User entity, and have it included for access tokens to your API.
A pragmatic solution to your issue might be an in-memory cache.
How often do emails change?

Identity Server 3 AzureAd Claims not returning

I have a working Identity Server application, and I'm setting it up to work with Azure AD. I've got my Azure Ad App registration and I can authenticate with it properly.
Looking at this and trying to do something similar to store the 3rd party user IDs associated with a user, but I'm not getting the sub or nameIdentifier claims back from AAD.
Do I need to request these from AzureAD somehow? - Their docs seem to be to be saying that the "sub" claim is (or at least can be) returned: https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-token-and-claims#_subject. This article seems to say that sub isn't returned, but it's for multitenant applications, so I'm not too sure if that's relevant.
I'm sure I'm missing something simple, but can't find anything relevant on Google.
Cheers,
Alex
The article Work with claims-based identities is too old and this Azure AD token reference article should be right about the token claims in the token issued by Azure AD.
Based on the test, I could get the sub claim from Azure AD and it also issued by the IdentityServer3 like figure below:
Here is the code I configed for the IdentityServer3 for your reference:
var webApp = WebApp.Start("https://localhost:44333", app =>
{
app.UseIdentityServer(new IdentityServerOptions
{
SiteName = "NDC Demo",
SigningCertificate = cert,
Factory = factory,
AuthenticationOptions = new AuthenticationOptions
{
IdentityProviders = ConfigureAdditionalIdentityProviders,
EnableAutoCallbackForFederatedSignout = true
}
});
});
public static void ConfigureAdditionalIdentityProviders(IAppBuilder app, string signInAsType)
{
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
AuthenticationType = "aad",
Caption = "Azure AD",
SignInAsAuthenticationType = signInAsType,
Authority = "https://login.microsoftonline.com/{tenantId}",
ClientId = "{clientIdFromAzurePortal}",
RedirectUri = "{redirectUri}",
});
}
If you still have the problem, would you mind sharing the request to Azure AD which you can capture it using Fiddler.

How do you authenticate AAD B2C using MSAL?

I have a working version of a Client/Server authentication using ADAL. However, it appears that the B2C AAD doesn't work well with ADAL when you want to use Local Accounts (that is, just a username or just an email address with no backing authenticator other than AAD). It appears the API we should be using for Local Accounts is the alpha release of MSAL. So far, so good. I'm able to create a local user using the Graph API and using the following code, I appear to be authenticating the local user 'joeconsumer#mycompany.com':
this.pca = new PublicClientApplication("a4828eaa-42f6-418a-8062-f857130b69ce");
AuthenticationResult result = await this.pca.AcquireTokenAsync(
new string[] { "a4828eaa-42f6-418a-8062-f857130b69ce" },
string.Empty,
UiOptions.ForceLogin,
null,
null,
"https://login.microsoftonline.com/" + "darkbondpublic.onmicrosoft.com",
"B2C_1_sign-in");
The problem is that I pass the security token from 'result.Token' back to the server using a custom security token mechanism in WCF. The code on the server, which used to work with ADAL, no longer seems to accept the security token from the above call:
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
Microsoft.IdentityModel.Tokens.SecurityToken securityToken = null;
ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(userName, this.GetTokenValidationParameters(MetadataAddress), out securityToken);
Thread.CurrentPrincipal = claimsPrincipal;
The error message is:
Can anyone tell me what is going on here? Do I need a different method of authenticating on the server?
The metadata endpoint you config for Azure AD B2C tenant is incorrect. Here is the correct one for your reference:
https://login.microsoftonline.com/{tenantId}/v2.0/.well-known/openid-configuration?p=B2C_1_Sign_In
We can find the metadata for the specific policy from the new Azure portal like figure below.
And in the metadata should able to see the keys endpoint like below:
https://login.microsoftonline.com/{tenant}/discovery/v2.0/keys?p={policy}
We can find the key with kid gfIKIH-yZ3phRHRyjnsHIqZMaePLGAELzPat0CNY4sA like below figure:
I think the problem is: you are sending request to V1 endpoint but AAD B2C uses V2 endpoint with the authority: https://login.microsoftonline.com/tfp/{tenantId}/{policyName}/v2.0/
Metadata for v2 endpoint is available at https://login.microsoftonline.com/tfp/{tenantId}/{policyName}/.well-known/openid-configuration
Can you update your Urls and make one more attempt?
To see an authority in Azure Portal select your policy, then:
Locate your Policy
Click "Edit"
Click "Token, session & SSO config"
Expand "Issuer (iss) claim"
Azure (uses V1 endpoint) and Azure AD B2C (uses V2 endpoint) use different set of keys to sign tokens, therefore it is important to download public keys from the right location - originally you downloaded it from V1 but instead need to use V2.
For me this endpoint worked:
https://{Azure domain}/{Azure tenant}/v2.0/.well-known/openid-configuration?p={Azure policy}

Resources