Read OpenID configuration and validation token in c#

OpenIdDict

Usually an OpenID identity server has a general endpoint where all configuration values can be found, such as verification keys and available endpoints

E.g. for Azure AD it would be at: "https://login.microsoftonline.com/[TENAT]/.well-known/openid-configuration"

Here is a way to retrieve that information in c#:

Install the following packages:


Microsoft.IdentityModel.Protocols
Microsoft.IdentityModel.Protocols.OpenIdConnect

Then, add this code:

const string TENANT = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
var stsDiscoveryEndpoint = string.Format(CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{0}/.well-known/openid-configuration", TENANT);
var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint, new OpenIdConnectConfigurationRetriever());
var config = await configManager.GetConfigurationAsync();

IdentityModelEventSource.ShowPII = true;
JwtSecurityTokenHandler tokenHandler = new ();

TokenValidationParameters validationParameters = new ()
{
    ValidateAudience = false,
    ValidateIssuer = false,
    IssuerSigningKeys = config.SigningKeys,
    TokenDecryptionKeys = config.TokenDecryptionKeys,
    ValidateLifetime = false,
   
};

string token = ".....";

var result = tokenHandler.ValidateToken(
    token, 
    validationParameters, 
    out SecurityToken jwt);

var jwtSecurityToken = jwt as JwtSecurityToken;

Notice for Azure AD: In order to get verifiable access token, you must configure and use a custom scope, otherwise it returns with a nonce and can be verified only internaly by Microsoft services. The ID token is always verifiable

Post a Comment

Previous Post Next Post