I am trying to validate an azure ad access token like here: https://www.c-sharpcorner.com/article/how-to-validate-azure-ad-token-using-console-application/
I keep getting the error 'Object reference not set to an instance of an object' inside the tokenHandler.ValidateToken(...)
My code:
string myTenant = "TENANT ID";
var myAudience = "CLIENT ID";
var myIssuer = String.Format(CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{0}/v2.0", myTenant);
var mySecret = "SECRET";
var mySecurityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(mySecret));
var stsDiscoveryEndpoint = String.Format(CultureInfo.InvariantCulture, "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration", myTenant);
var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint, new OpenIdConnectConfigurationRetriever());
var config = await configManager.GetConfigurationAsync();
var tokenHandler = new JwtSecurityTokenHandler();
var validationParameters = new TokenValidationParameters
{
ValidAudience = myAudience,
ValidIssuer = myIssuer,
IssuerSigningKeys = config.SigningKeys,
ValidateLifetime = false,
IssuerSigningKey = mySecurityKey
};
var validatedToken = (SecurityToken)new JwtSecurityToken();
// Throws an Exception as the token is invalid (expired, invalid-formatted, etc.)
tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
instead of TENANT ID I have the tenant ID from azure. Instead of CLIENT ID I have the client ID from azure and instead of SECRET I have the value of the client secret made in azure.
CodePudding user response:
I really didn’t changed the code but it works now. :)