❔ Validate an Azure ad token in .net 7
Hi, so i am trying to validate an Azure Ad token coming from an SPA. My thinking is that I would want to validate the token and then issue my own token.
The reason I am not using the the Middleware AddMicrosoftIdentityWebApi is that it seems to break my normal username/password JWT validator, and I have some claims from our own database, that is required to be in the JWT token as a claim, and it doesn't seem to be possible to do that with a Azure Ad token.
I have tried this, but it just throws an "Object reference not set to an instance of an object." even though all the parameters is not null
string token = "";
string myTenant = "<>";
var myAudience = "api://<>";
var myIssuer = "https://login.microsoftonline.com/<>/wsfed";
var mySecret = "<SECRET>";
var mySecurityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(mySecret));
var stsDiscoveryEndpoint = String.Format(CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{ 0 }/.well-known/openid-configuration", myTenant);
var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint, new OpenIdConnectConfigurationRetriever());
var config = configManager.GetConfigurationAsync().Result;
var tokenHandler = new JwtSecurityTokenHandler();
The reason I am not using the the Middleware AddMicrosoftIdentityWebApi is that it seems to break my normal username/password JWT validator, and I have some claims from our own database, that is required to be in the JWT token as a claim, and it doesn't seem to be possible to do that with a Azure Ad token.
I have tried this, but it just throws an "Object reference not set to an instance of an object." even though all the parameters is not null
string token = "";
string myTenant = "<>";
var myAudience = "api://<>";
var myIssuer = "https://login.microsoftonline.com/<>/wsfed";
var mySecret = "<SECRET>";
var mySecurityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(mySecret));
var stsDiscoveryEndpoint = String.Format(CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{ 0 }/.well-known/openid-configuration", myTenant);
var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint, new OpenIdConnectConfigurationRetriever());
var config = configManager.GetConfigurationAsync().Result;
var tokenHandler = new JwtSecurityTokenHandler();
var validationParameters = new TokenValidationParameters
{
ValidAudience = myAudience,
ValidIssuer = myIssuer,
IssuerSigningKeys = config.SigningKeys,
ValidateLifetime = false,
IssuerSigningKey = mySecurityKey
};
SecurityToken validatedToken;
// Throws an Exception as the token is invalid (expired, invalid-formatted, etc.)
try
{
tokenHandler.ValidateToken(token, validationParameters, out validatedToken).Dump();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}