I'm working on an ASP.NET Core 8 API called ApiApp
secured with Azure AD B2C and an ASP.NET Core MVC application called WebApp
. Everything works fine, and I can call ApiApp
from WebApp
.
I want to enrich the user's claims using IClaimsTransformation
upon login. My goal is to implement IClaimsTransformation
, make a call to ApiApp
to query the database, retrieve the necessary data, and enrich the user's claims.
To achieve this, I need a token to call ApiApp
. I tried generating the token with the following method:
private async Task<string> GetApplicationTokenAsync()
{
try
{
var clientId = _configuration["AzureAdB2C:ClientId"]; // ClientId of the WebApp
var clientSecret = _configuration["AzureAdB2C:ClientSecret"]; // ClientId of the WebApp
var scope = _configuration["MyApp:MyAppScope"]; // exposed API scope access_as_user
var tenant = _configuration["AzureAdB2C:Domain"];
var policy = _configuration["AzureAdB2C:SignUpSignInPolicyId"];
var tenantName = "mytenant";
var authority = $"https://{tenantName}.b2clogin.com/{tenantName}.onmicrosoft.com/{policy}/v2.0";
var app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(new Uri(authority))
.Build();
var authResult = await app.AcquireTokenForClient(new[] { scope }).ExecuteAsync();
return authResult.AccessToken;
}
catch (Exception ex)
{
throw;
}
}
However, I receive the error:
AADSTS50049: "Unknown or invalid instance".
- What should I do to correctly obtain the token?
- Is there something wrong in my Azure AD B2C configuration or code?
REPO:
I have created this repository to facilitate clear visibility and analysis of the issue I am encountering, allowing for a deeper understanding of the error.
Azure ApiApp
Config:
- API permissions
- Expose an API
- I have 1 Certificate & secret
- Authentication
Azure WebApp
Config:
- Authentication
- I have 1 Certificate & secret
- API permissions
- In the Expose an API section I have nothing
api://{clientId}/access_as_user
) in the Azure portal. Make sure the WebApp has permission to request this scope.{ "AzureAdB2C": { "Instance": "https://your-tenant-name.b2clogin.com/", "ClientId": "your-client-id", "Domain": "your-tenant-name.onmicrosoft.com", "SignUpSignInPolicyId": "your-policy-name", "ClientSecret": "your-client-secret" }, "MyApp": { "MyAppScope": "api://your-api-app-client-id/access_as_user" } }
api://{clientId}/access_as_user
)appsettings.json
file as you suggested, but I get always the same error. At his point maybe the problem isauthority
. This is how thevar authority
it looks like : `$"https://myapp.b2clogin.com/myapp.onmicrosoft.com/B2C_1_SignUpSignIn/oauth2/v2.0/token"
appsettings.json
are correct. try to use the postman to get the token using same configuration to troubleshoot the issue