© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
8 replies
chimera

❔ 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();

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);
}
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);
}
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ Calling an Azure AD protected Web API endpoint from an Azure AD protected Web App [.NET 7]
C#CC# / help
3y ago
trying to plan validating azure ad token and calling graph api in azure function
C#CC# / help
2y ago
Azure AD sign out.
C#CC# / help
3y ago
❔ .NET 7 in Cpanel
C#CC# / help
3y ago