我可以通过设置validate-jwt
属性,使用Azure API管理中的<issuer-signing-keys>
策略成功验证使用HS256签名的JWT。但是如何验证使用RS256签名的JWT?我尝试将公钥或证书放在<issuer-signing-keys>
中,但它不起作用。
答案 0 :(得分:3)
目前验证rsa签名令牌的唯一方法是使用openid url。
答案 1 :(得分:0)
我能够使用以下策略验证这样的令牌
<issuer-signing-keys>
<key certificate-id="my-rsa-cert" />
</issuer-signing-keys>
您可以通过以下步骤做到这一点:
使用以下命令创建证书
openssl.exe req -x509 -nodes -sha256 -days 3650 -subj "/CN=Local" -newkey rsa:2048 -keyout Local.key -out Local.crt
openssl.exe pkcs12 -export -in Local.crt -inkey Local.key -CSP "Microsoft Enhanced RSA and AES Cryptographic Provider" -out Local.pfx
在 API 管理中加载证书“Local.pfx”,ID 为“my-rsa-cert”。
使用以下代码从证书生成令牌
/////////////////////////////////////////////
// Token Generation
var CLIENT_ID = "Local";
var ISSUER_GUID = "b0123cec-86bb-4eb2-8704-dcf7cb2cc279";
var filePath = @"..\..\..\Cert\Local.pfx";
var x509Certificate2 = new X509Certificate2(filePath, "<certpwd>");
var signingCredentials = new X509SigningCredentials(x509Certificate2, SecurityAlgorithms.RsaSha256Signature); //, SecurityAlgorithms.Sha256Digest
var tokenHandler = new JwtSecurityTokenHandler();
var originalIssuer = $"{CLIENT_ID}";
var issuer = originalIssuer;
DateTime utcNow = DateTime.UtcNow;
DateTime expired = utcNow + TimeSpan.FromHours(1);
var claims = new List<Claim> {
new Claim("aud", "https://login.microsoftonline.com/{YOUR_TENENT_ID}/oauth2/token", ClaimValueTypes.String, issuer, originalIssuer),
new Claim("exp", "1460534173", ClaimValueTypes.DateTime, issuer, originalIssuer),
new Claim("jti", $"{ISSUER_GUID}", ClaimValueTypes.String, issuer, originalIssuer),
new Claim("nbf", "1460533573", ClaimValueTypes.String, issuer, originalIssuer),
new Claim("sub", $"{CLIENT_ID}", ClaimValueTypes.String, issuer, originalIssuer)
};
ClaimsIdentity subject = new ClaimsIdentity(claims: claims);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = subject,
Issuer = issuer,
Expires = expired,
//TokenIssuerName = "self",
//AppliesToAddress = "https://www.mywebsite.com",
//Lifetime = new Lifetime(now, now.AddMinutes(60)),
SigningCredentials = signingCredentials,
};
JwtSecurityToken jwtToken = tokenHandler.CreateToken(tokenDescriptor) as JwtSecurityToken;
jwtToken.Header.Remove("typ");
var token = tokenHandler.WriteToken(jwtToken);
this.Output = jwtToken.ToString();
this.Output += "\r\n" + token.ToString();
JwtSecurityToken jwtToken = tokenHandler.CreateToken(tokenDescriptor) as JwtSecurityToken;
jwtToken.Header.Remove("typ");
var token = tokenHandler.WriteToken(jwtToken);
使用生成的不记名令牌向 API 发送请求