Azure AD Identity authentication error : IDX10214: Audience validation failed - azure

I have an .net core 5 api that I want to protect using Azure AD, and then call it from a console app. So my case is only service-to-service authentication. I registered both the apps to Azure AD an then gave the permission to the console app on the api using App roles.
I succeeded to retrieve a token for the console app passing the right scope :
static async Task Main(string[] args)
{
var app = ConfidentialClientApplicationBuilder
.Create(<MY_CONSOLE_APP_ID>)
.WithClientSecret(<MY_CONSOLE_APP_CLIENT_SECRET>)
.WithAuthority(new Uri($"https://login.microsoftonline.com/<MY_TENANT_ID>"))
.Build();
var result = await app.AcquireTokenForClient(new String[]
{
"api://<MY_API_APP_ID>/.default"
})
.ExecuteAsync();
}
Then in the Startup class of the API, I added the following code :
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(Configuration, "AzureAd");
and in the appsettings.json I defined the required settings:
"AzureAd": {
"ClientId": "<MY_API_APP_ID>",
"Instance": "https://login.microsoftonline.com/",
"TenantId": "<MY_TENANT_ID>"
}
Then I marked a controller as [Authorize] but when I call one of its endpoint I get the following error :
{
"code": 401,
"message": "IDX10214: Audience validation failed. Audiences: '[PII is hidden]'. Did not match: validationParameters.ValidAudience: '[PII is hidden]' or validationParameters.ValidAudiences: '[PII is hidden]'."
}
I also tried to prefix the clientId by api:// but got the same error. I decoded the token to ensure the audience was correct and it seems ok since I have "aud": "api://<MY_API_APP_ID>"
Do you have an idea of what I am missing ?

Whatever code provided looks good.
Make sure the Audience config matches the "aud" claim in the access token.
As that part of code is not provided here,
you may be missing an entry of audience in code configuration under services.AddAuthentication(…
Please check if you have given audience entry in any of these ways .
1
.AddJwtBearer(options =>
{
options.Authority = "";
//options.Audience = Configuration["Audience"];
};
(or)
2
.AddJwtBearer(options =>
{
options.Audience = clientId;
options.Authority = authority;
})
(or)
3)
.AddJwtBearer(options =>
{
options.Authority = "";
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
//here you give required valid audiences
ValidateIssuer = true,
ValidAudiences = new List<string>
{
"AUDIENCE1",
"AUDIENCE2"
}
or valid audiences can be like below in place of AUDIENCE1 or 2.
ValidAudiences = new List<string>
{
Configuration["Authentication:ClientId"]
}
The aud (audience) should match your API's id, and make sure required scopes are present .If these are fine , then check if the token you are trying to validate is ID token or Access token .It differs for API and graph api.

Related

Microsoft.IdentityModel.LoggingExtensions.IdentityLoggerAdapter Error Logs in AzureAD Auth Implementation

We have integrated AzureAD for our API Authorization and API Auth is working fine but seeing error logs for Microsoft.IdentityModel.LoggingExtensions.IdentityLoggerAdapter with below messages,
IDX40003: Neither tid nor tenantId claim is present in the token obtained from Microsoft identity platform.
IDX10516: Signature validation failed. Unable to match key: kid: '*'. Number of keys in TokenValidationParameters: '16'. Number of keys in Configuration: '0'. Exceptions caught: '[PII of type 'System.Text.StringBuilder' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'. token: '[PII of type 'System.IdentityModel.Tokens.Jwt.JwtSecurityToken' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'. Valid Lifetime: 'False'. Valid Issuer: 'False'**
Our APIs are being consumed by UI APP as well as via Swagger/Postman.
What should be root cause to it?
The error IDX10516: Signature validation failed. Unable to match key: kid occurs when the Kid in your decoded token which validates token signature is not valid.
So one needs to load keys from the openid provider.
code:
var openidConfiguration = new ConfigurationManager<OpenIdConnectConfiguration>(
$"https://login.microsoftonline.com/{tenantid}/v2.0/.well-known/openid-configuration",
new OpenIdConnectConfigurationRetriever(),
new HttpDocumentRetriever());
var config = await openidConfiguration.GetConfigurationAsync();
var parameteres = new TokenValidationParameters()
{
RequireAudience = true,
RequireExpirationTime = true,
ValidateAudience = true,
ValidateIssuer = true,
ValidateLifetime = true,
ValidAudiences = new[] { "<my client id or appId uri or resource identitifer>" },
ValidIssuers = new[] { $"https://sts.windows.net/{tenantid}/" },
IssuerSigningKeys = config.SigningKeys
};
AppId Uri , you can check from the portal : api://
Add the following to check for more clear descriptive exception in ConfigureServices method in Startup.cs :IdentityModelEventSource.ShowPII = true
Example:
public void ConfigureServices(IServiceCollection services)
{
...
IdentityModelEventSource.ShowPII = true;
...
}
Reference : Azure AD - Why can't I validate JWT token issued by Azure AD for my Web API? Getting "IDX10516: Signature validation failed" error - Stack Overflow

Owin not authenticated when requesting access token

I'm using implicit grant type, and when I request "id_token token" as response type my HttpContext.Current.User is null after logging in leading me to believe something has gone wrong inside owin. If I just have "id_token" as response type its fine. Do I need to tell owin somewhere to get the access token?
For reference I'm using .Net Framework as my client and identityserver4.
To be able to get the token via browser you need to set AllowAccessTokensViaBrowser = true on client's config within IdentityServer:
new Client
{
...
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
...
},
and on MVC client's Startup, to you can add the access_token as a claim to user:
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
...
ResponseType = "id_token token",
Notifications = new OpenIdConnectAuthenticationNotifications
{
SecurityTokenValidated = n =>
{
n.AuthenticationTicket.Identity.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken));
return Task.FromResult(0);
}
}
});
I have the full working sample here

azure acive directory validation error

Im having an issue with a web app in azure. I use active directory to control access which works well, but one of my users gets this error message when they login in
idx10214 audience validation failed did not match validationparameters.validaudience or validationparameters null
does anyone know what this means ? Is there a workaround ?
heres how I setup openid to authorize users, how would i include the audience settings here ? What should the audience value be ?
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = AuthorityCHP,
PostLogoutRedirectUri = postLogoutRedirectUri,
RedirectUri = loURL,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
// If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
AuthorizationCodeReceived = (context) =>
{
var code = context.Code;
Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientId, appKey);
string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(AuthorityCHP, new ADALTokenCache(signedInUserID));
var newuri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code, newuri, credential, graphResourceId);
return Task.FromResult(0);
}
}
});
Ive added some additional code in the hope it might work, but after i deployed it, i got the user affecetd to try logging in again and its still the same. Im not consuming a webapi its just a straightforwrsd webapp with a standard login page, Im really stumped, why is it only one particular user thats affecetd by this ? Can anynoe help ?
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
TokenValidationParameters = new TokenValidationParameters
{
ValidAudience = clientId
},
Tenant = tenantId,
AuthenticationType = "OAuth2Bearer"
});
That's mean you were calling the API using the incorrect token. When we call a web API which protected by Azure AD, it will verify the signature of the token and claims in the token.
The audience is used to which resource the token is able to access. We should acquire the token based on the resource. For example, if we protect the web API with code below, we should use the audience config in the below to acquire the token.
public void ConfigureAuth(IAppBuilder app)
{
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Audience = ConfigurationManager.AppSettings["ida:Audience"],
Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
});
//app.UsePasswordAuthentication();
}
update
TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
// In a real application you would use IssuerValidator for additional checks, like making sure the user's organization has signed up for your app.
// IssuerValidator = (issuer, token, tvp) =>
// {
// //if(MyCustomTenantValidation(issuer))
// return issuer;
// //else
// // throw new SecurityTokenInvalidIssuerException("Invalid issuer");
// },
},

Failed to get AccessToken via authorization code using MSAL 1.1.0-preview in asp.net core

I followed official steps as below to try the scenario "web app calling a Web API in Azure Ad B2C", the only difference is I am using Asp.Net core. I am using AuthorizationCode to get the access token, but it always returns with id token and NULL access token.
Create an Azure AD B2C tenant.
Register a web api.
Register a web app.
Set up policies.
Grant the web app permissions to use the web api.
My code:
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
AuthenticationScheme = OpenIdConnectDefaults.AuthenticationScheme,
AutomaticChallenge = true,
ClientId = aadB2cSettings.ClientId,
MetadataAddress = $"{aadB2cSettings.Instance}{aadB2cSettings.Tenant}/v2.0/.well-known/openid-configuration?p={aadB2cSettings.B2cSignUpOrSignInPolicy}",
PostLogoutRedirectUri = aadB2cSettings.RedirectUrl,
ResponseType = OpenIdConnectResponseType.CodeIdToken,
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name"
},
Events = new OpenIdConnectEvents
{
OnAuthorizationCodeReceived = async context =>
{
var authCode = context.TokenEndpointRequest.Code;
var b2cAuthority = $"{aadB2cSettings.Instance}tfp/{aadB2cSettings.Tenant}/{aadB2cSettings.B2cSignUpOrSignInPolicy}/v2.0/.well-known/openid-configuration";
var cca = new ConfidentialClientApplication(
aadB2cSettings.ClientId,
b2cAuthority,
aadB2cSettings.RedirectUrl,
new ClientCredential(aadB2cSettings.ClientSecret),
new TokenCache(),
null);
try
{
var authResult = await cca.AcquireTokenByAuthorizationCodeAsync(authCode, new[] { "https://hulab2c.onmicrosoft.com/b2cdemo/all" });
context.HandleCodeRedemption(authResult.AccessToken, authResult.IdToken);
}
catch (Exception ex)
{
throw ex;
}
}
},
Used fiddler to capture the request, it is:
POST
https://login.microsoftonline.com/hulab2c.onmicrosoft.com/oauth2/v2.0/token?p=b2c_1_signuporsignin
HTTP/1.1
Request Body:
client_id=1ff91f47-08ee-4973-83f4-379ad7e0679c&client_info=1&client_secret=......&scope=https%3A%2F%2Fhulab2c.onmicrosoft.com%2Fb2cdemo%2Fall+offline_access+openid+profile&grant_type=authorization_code&code=......&redirect_uri=https%3A%2F%2Flocalhost%3A44383%2F
Return:
{"id_token":"......","token_type":"Bearer","not_before":1494494423,"client_info":"......","scope":""}
So only id token, no access token. But we should get access token here, right?
Finally found out my failure reason: the request to get AuthorizationCode doesn't contain the target scope. Reflect in code, for OpenIdConnectOption in aspnetcore, the Scope parameter is readonly and its default value is "opened profile".
Scope is readonly in OpenIdConnectOption
So the default authorization code request sent is:
GET
https://login.microsoftonline.com/hulab2c.onmicrosoft.com/oauth2/v2.0/authorize?p=b2c_1_signuporsignin&client_id=7f865ca0-271e-4f27-be21-6f0072fe3ad7&redirect_uri=https%3A%2F%2Flocalhost%3A44355%2Fsignin-oidc&response_type=code%20id_token&scope=openid%20profile&response_mode=form_post&nonce=......
HTTP/1.1
Thus, using this authorization code in response to get token, even we set right scope in the token request, we still can't get the access code but only id token, because the provide authorization code is only for "openid profile".
To fix this, we need to add target web api scope into the authorization code as well. Here is the how-to-fix code:
Events = new OpenIdConnectEvents
{
OnRedirectToIdentityProvider = context =>
{
context.ProtocolMessage.Scope += $" offline_access {myapiscope}";
return Task.FromResult(0);
},
......
}
In AspNet, we don't need to do this because its scope is not readonly as aspnetcore and can be set directly:
new OpenIdConnectAuthenticationOptions
{
......
Scope = $"openid profile offline_access {ReadTasksScope} {WriteTasksScope}"
}
https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi/issues/4 Microsoft have reproduced the issue and working on fix

MVC 5 OWIN External Login with Mobile Services

I am doing external login (Facebook, Twitter, Microsoft) using MVC 5 OWIN Identity 2, which works great, but I need to access a mobile services with this credential, I have read that to this I need a access token, so I get the access token and try to pass it to the mobile services, but always has this error:
Facebook: Error:
The Facebook Graph API access token authorization request failed with HTTP status code 400
Microsoft: Error:
Invalid token format. Expected Envelope.Claims.Signature.
The method that I am trying to use with mobile services is:
await mobileservi.LoginAsync(MobileServiceAuthenticationProvider.[ProviderName], token);
I read on this link:
http://msdn.microsoft.com/en-us/library/dn296411.aspx
So I am using a JObject() to pass the access token
The format of the token that I most pass:
For Microsoft is:
token.Add("authenticationToken", _accessToken);
{"authenticationToken":"<authentication_token>"}
For Facebook is:
token.Add("access_token", _accessToken);
{"access_token":"<access_token>"}
But I do not have the format for Twitter.
Now according to Azure Mobile Services documentation, I most use the azure mobile services URL on my apps for any of this providers, but if I do this, I receive an error of incorrect URL when redirecting to the provider log in page.
I read this post with OAuth:
http://blogs.msdn.com/b/carlosfigueira/archive/2013/06/25/exposing-authenticated-data-from-azure-mobile-services-via-an-asp-net-mvc-application.aspx
It has to be something like this for MVC 5 OWIN Identity 2.
On the Startuo.Auth.cs file, I have this configure to get the access token for each provider:
Microsoft:
var MicrosoftOption = new MicrosoftAccountAuthenticationOptions()
{
ClientId = "0000000048124A22",
ClientSecret = "c-gTye48WE2ozcfN-bFMVlL3y3bVY8g0",
Provider = new MicrosoftAccountAuthenticationProvider()
{
OnAuthenticated = (context) =>
{
context.Identity.AddClaim(new Claim(("urn:microsoftaccount:access_token", context.AccessToken, XmlSchemaString, "Microsoft"));
return Task.FromResult(0);
}
}
};
Twitter:
var twitterOption = new TwitterAuthenticationOptions()
{
ConsumerKey = "ConsumerKey",
ConsumerSecret = "ConsumerSecret",
Provider = new TwitterAuthenticationProvider()
{
OnAuthenticated = (context) =>
{
context.Identity.AddClaim(new Claim("urn:tokens:twitter:accesstoken", context.AccessToken));
context.Identity.AddClaim(new Claim("urn:tokens:twitter:accesstokensecret", context.AccessTokenSecret));
return Task.FromResult(0);
}
}
};
Facebook:
var facebookOption = new FacebookAuthenticationOptions()
{
AppId = "AppId",
AppSecret = "AppSecret",
Provider = new FacebookAuthenticationProvider()
{
OnAuthenticated = (context) =>
{
context.Identity.AddClaim(new Claim("urn:facebook:access_token", context.AccessToken, XmlSchemaString, "Facebook"));
return Task.FromResult(0);
}
}
};
On the externalLoginCallback, this is how a retrieve the access token
string email = null;
string accessToken = null;
ClaimsIdentity ext = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
switch (login.LoginProvider)
{
case "Facebook":
accessToken = ext.Claims.First(x => x.Type.Contains("access_token")).Value;
break;
case "Twitter":
accessToken = ext.Claims.First(x => x.Type.Contains("accesstoken")).Value;
break;
case "Microsoft":
accessToken = ext.Claims.First(x => x.Type.Contains("access_token")).Value;
break;
}
Later I store this value on a session variable, this value is the one that I use to pass as the access token.
So I have no idea what to do, can anyone please help me?
OK, I found what I was doing wrong, in order to respect the authorization flow, I must have APP ID and APP Secret that I register on my app (Google, Facebook, Microsoft, Twitter), on my mobile service. This is the important part, the register URL in the app must be the URL of the web site, after doing this, everything work fine

Resources