通过从令牌中提取appid / clientid,从C#代码验证azure AD jwt。下面提到的代码将令牌作为字符串,并使用从令牌中提取的clientid / appid验证您的客户端ID
public bool Validate(string token)
{
string clientId = "Your appid/clientid";
string stsDiscoveryEndpoint = "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration";
ConfigurationManager<OpenIdConnectConfiguration> configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint, new OpenIdConnectConfigurationRetriever());
OpenIdConnectConfiguration config = configManager.GetConfigurationAsync().Result;
TokenValidationParameters validationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = false,
IssuerSigningKey = config.SigningKeys.FirstOrDefault(),
ValidateLifetime = false
};
System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler tokendHandler = new JwtSecurityTokenHandler();
SecurityToken jwt;
var result = tokendHandler.ValidateToken(token, validationParameters, out jwt);
ClaimsPrincipal claims = result;
var claimValue = claims.Claims.GetEnumerator();
string appId = "";
if (claimValue != null)
{
while (claimValue.MoveNext())
{
if (claimValue.Current.Type == "appid")
{
appId = claimValue.Current.Value;
break;
}
}
}
if (appId == clientId)
{
return true;
}
else
{
return false;
}
}