我在Net Core WebApi应用程序中使用下面的代码,并且运行良好。
我可以解码它产生的JWT,但我也想验证它的签名。但是,我从哪里获得验证密钥?
tenant = Configuration.GetSection("AzureAD:Tenant").Value;
Logger.AppLogDebug("tenat value found: [{0}]", tenant);
azureAdInstance = Configuration.GetSection("AzureAD:AzureADInstance").Value;
Logger.AppLogDebug("azureAdInstance value found: [{0}]", azureAdInstance);
audience = Configuration.GetSection("AzureAD:Audience").Value;
Logger.AppLogDebug("Audience value found: [{0}]", audience);
var authority = $"{azureAdInstance}{tenant}";
Logger.AppLogDebug("authority value set to: [{0}]", authority);
var authContext = new AuthenticationContext(authority);
var clientCredential = new ClientCredential(key, secret);
var token = authContext.AcquireTokenAsync(audience, clientCredential).Result.AccessToken;
return new ObjectResult($"Bearer {token}");
答案 0 :(得分:0)
您可以使用JwtBearer
或AddAzureADBearer
中间件来验证访问令牌。这样,当接收到来自客户端的请求时,您的Web api将自动解码令牌并验证签名。您可以参考以下链接,了解如何使用两种中间件:
https://stackoverflow.com/a/57619013/5751404
如果要手动验证jwt令牌,则在验证访问令牌的签名时,应该获取公共密钥,因为Azure AD可以使用一组特定的公共-私有密钥对中的任何一个对令牌进行签名,因此这些密钥可以在以下位置找到:
https://login.microsoftonline.com/{tenant}/.well-known/openid-configuration
在JSON响应中,您将看到属性jwks_uri
,该属性是URI,其中包含Azure AD的JSON Web密钥集。匹配jwt令牌中的kid声明,您可以找到AAD用于通过非对称加密算法(默认情况下为RSA 256
)对令牌进行签名的密钥。
然后您可以使用:
来验证令牌。public JwtSecurityToken validate(string token,string key){
var rsa = new RSACryptoServiceProvider();
string exponentvalue = "AQAB";
var e = Base64UrlEncoder.DecodeBytes(exponentvalue);
var N = key;
var modulus = Base64UrlEncoder.DecodeBytes(N);
rsa.ImportParameters(
new RSAParameters()
{
Modulus = modulus,
Exponent = e
});
var signingKey = new RsaSecurityKey(rsa);
TokenValidationParameters validationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateLifetime = false
};
JwtSecurityTokenHandler tokendHandler = new JwtSecurityTokenHandler();
SecurityToken jwt;
var result = tokendHandler.ValidateToken(token, validationParameters, out jwt);
return jwt as JwtSecurityToken;
}
我还没有测试以上代码,但是您可以尝试从上面开始。
此外,您正在使用客户端凭证流来获取特定资源的令牌。如果资源是Microsoft hosted apis
,例如Microsoft Graph API
,Azure Management API
等。您不需要在应用程序中验证访问令牌。将带有令牌的请求发送到Microsoft托管的api时,它将为您验证令牌。