【Azure API 管理】APIM 配置Validate-JWT策略,验证RS256非对称(公钥/私钥)加密的Token

本文涉及的产品
密钥管理服务KMS,1000个密钥,100个凭据,1个月
简介: 【Azure API 管理】APIM 配置Validate-JWT策略,验证RS256非对称(公钥/私钥)加密的Token

问题描述

在APIM中配置对传入的Token进行预验证,确保传入后端被保护的API的Authorization信息正确有效,可以使用validate-jwt策略。validate-jwt 策略强制要求从指定 HTTP 标头或指定查询参数提取的 JSON Web 令牌 (JWT) 必须存在且有效。validate-jwt 策略支持 HS256 和 RS256 签名算法。

  • 对于 HS256,必须在策略中以 base64 编码形式提供内联方式的密钥。
  • 对于 RS256,密钥可以通过 Open ID 配置终结点来提供,或者通过提供包含公钥或公钥的模数指数对的已上传证书的 ID 来提供。

在最开始使用HS256签名算法的Token时,在validate-jwt策略中配置 issuer-signing-keys就能成功验证JWT,但是当使用RS256签名算法适合,这样就不行。会抛出 'System.NotSupportedException: IDX10634: Unable to create the SignatureProvider.\nAlgorithm: 'RS256', SecurityKey: 'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey... 错误。

 

HS256配置

<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unvalid authorization" require-expiration-time="true" require-signed-tokens="true">
            <issuer-signing-keys>
                <key>在HS256算法中使用的密钥,进行base64编码后的值</key>
            </issuer-signing-keys>
            <audiences>
                <audience>在生成JWT Token时设置的aud值</audience>
            </audiences>
   </validate-jwt>

RS256配置(附带错误消息)

<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unvalid authorization" require-expiration-time="true" require-signed-tokens="true">
            <issuer-signing-keys>
            <key><RS256 公钥内容通过base64编码后的值></key>
            </issuer-signing-keys>
            <audiences>
                <audience>在生成JWT Token时设置的aud值</audience>
            </audiences>
</validate-jwt>

在进行验证时错误消息(文末附录中包含如何在APIM门户中通过Test功能检测策略的执行结果及错误

validate-jwt (-0.132 ms)
    {
"message": "JWT Validation Failed: IDX10503: Signature validation failed. 
Keys tried: 'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey, KeyId: '', InternalId: 'HuvkEY3HBhujvk2qeDfgPFD2iYc-GYrnlDX6Yd1LsYQ'. ,
 KeyId: \r\n'.\nExceptions caught:\n 'System.NotSupportedException: IDX10634: Unable to create the SignatureProvider.\nAlgorithm: 'RS256',
SecurityKey: 'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey, KeyId: '', 
InternalId: 'HuvkEY3HBhujvk2qeDfgPFD2iYc-GYrnlDX6Yd1LsYQ'.'\n is not supported. 
The list of supported algorithms is available here: https://aka.ms/IdentityModel/supported-algorithms\r\n   
at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateSignatureProvider(SecurityKey key, String algorithm, Boolean willCreateSignatures, Boolean cacheProvider)\r\n   
at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForVerifying(SecurityKey key, String algorithm, Boolean cacheProvider)\r\n   
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(Byte[] encodedBytes, Byte[] signature, SecurityKey key, String algorithm, SecurityToken securityToken, TokenValidationParameters validationParameters)\r\n   
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(String token, 
TokenValidationParameters validationParameters)\r\n'.
\ntoken: '{\"typ\":\"jwt\",\"alg\":\"RS256\"}.{\"aud\":\"xxxxx.azure-api.cn\",\"user_id\":123456,\"username\":\"lutpython\",\"exp\":1631786725}'.."
}

那么, 如何来解决RS256 JWT的验证问题呢?

 

解决方案

正如APIM官网中特别提醒的一句话“对于 RS256,密钥可以通过 Open ID 配置终结点来提供,或者通过提供包含公钥或公钥的模数指数对的已上传证书的 ID 来提供 (英文原文:For RS256 the key may be provided either via an Open ID configuration endpoint, or by providing the ID of an uploaded certificate that contains the public key or modulus-exponent pair of the public key.)” , 所以APIM 中的validate-jwt是不支持使用直接配置公钥(Public Key)。 目前的方案有两种:

1) 使用openid configuration, OpenID Configuration中包含了公钥的内容,是有提供Token的权限服务器管理提供(如 Azure AD中就自动包含OpenID Configuration Endpoint).  注:这部分的详细介绍可以参考官网:https://docs.azure.cn/zh-cn/api-management/api-management-access-restriction-policies#azure-active-directory-token-validation

2) 把有证书机构(CA)颁发的包含公钥(Publick Key)的 .pfx证书上传到APIM中,然后配置 key certificate-id="<上传在APIM证书中的ID值>"  

<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unvalid authorization" require-expiration-time="true" require-signed-tokens="true">
            <issuer-signing-keys>
                <key certificate-id="<上传在APIM证书中的ID值>" />
            </issuer-signing-keys>
            <audiences>
                <audience>在生成JWT Token时设置的aud值</audience>
            </audiences>
        </validate-jwt>

 

方案步骤

可以使用以下的步骤来验证RS256 JWT:

1) 使用 openssl 指令创建 证书 (Local.pfx)

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

openssl.exe 下载地址:https://slproweb.com/products/Win32OpenSSL.html, 使用时需要 cd到 openssl.exe所在的bin目录中

 

2)上传 Local.pfx 文件到APIM,并自定义证书ID, 如:apim-rs256-01

 

3)在APIM的策略中(API级,单个操作级别,或者一组API[产品], 或者全部的APIs)。validate-jwt 内容如下:

<policies>
    <inbound>
        <base />
        <validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="401 unauthorized">
            <issuer-signing-keys>
                <key certificate-id="apim-rs256-01" />
            </issuer-signing-keys>
        </validate-jwt>
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

4) 使用以下的C#代码生成 Token

using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleAppjwt
{
    class Program
    {
        static void Main(string[] args)
        {            // Token Generation
            var CLIENT_ID = "Local";
            var ISSUER_GUID = "b0123cec-86bb-4eb2-8704-dcf7cb2cc279";
            var filePath = @"C:\Users\xxxx\source\repos\ConsoleAppjwt\ConsoleAppjwt\Cert\Local.pfx";
            var x509Certificate2 = new X509Certificate2(filePath, "123456789");
            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,
                SigningCredentials = signingCredentials,
            };
            JwtSecurityToken jwtToken = tokenHandler.CreateToken(tokenDescriptor) as JwtSecurityToken;
            jwtToken.Header.Remove("typ");
            var token = tokenHandler.WriteToken(jwtToken);
            Console.WriteLine(token);
            //Start to Verify Token
            Console.WriteLine("Start to Verify Token");
            ValidationToken(token);
            Console.ReadLine();
        }
        static void ValidationToken(string token)
        {
            try
            {
                JwtSecurityTokenHandler jwtHandler = new JwtSecurityTokenHandler();
                var filePath = @"C:\Users\xxxx\source\repos\ConsoleAppjwt\ConsoleAppjwt\Cert\Local.pfx";
                TokenValidationParameters tvParameter = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new X509SecurityKey(new X509Certificate2(filePath, "123456789")),
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    // set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
                    ClockSkew = TimeSpan.Zero
                };
                SecurityToken stoken;
                jwtHandler.ValidateToken(token, tvParameter, out stoken);
                Console.WriteLine(stoken);
                Console.WriteLine("Validate Token Success");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }
}

 

5) 调用APIM接口对Authorization验证

当然,也可以直接在调用APIM的客户端中进行验证。

 

附录一:在APIM的接口配置页中,Test页面点击Send按钮,发送API的请求,通过页面中的Trace部分查看每一部分的耗时,处理结果,或错误详情。

 

 

参考资料

验证 JWT:https://docs.azure.cn/zh-cn/api-management/api-management-access-restriction-policies#validate-jwt

How to validate JWT signed with RS256 Algorithm with validate-jwt policy in Azure API management :https://stackoverflow.com/questions/37050233/how-to-validate-jwt-signed-with-rs256-algorithm-with-validate-jwt-policy-in-azur

 

目录
打赏
0
0
0
0
201
分享
相关文章
如何对 API 进行安全加密?
对API进行安全加密是保障数据安全和系统稳定的重要措施
310 56
【Azure Redis 缓存】关于Azure Cache for Redis 服务在传输和存储键值对(Key/Value)的加密问题
【Azure Redis 缓存】关于Azure Cache for Redis 服务在传输和存储键值对(Key/Value)的加密问题
【Azure 环境】从网络包中分析出TLS加密套件信息
An TLS 1.2 connection request was received from a remote client application, but non of the cipher suites supported by the client application are supported by the server. The connection request has failed. 从远程客户端应用程序收到 TLS 1.2 连接请求,但服务器不支持客户端应用程序支持的任何密码套件。连接请求失败。
120 2
|
4月前
|
Go语言中使用JWT鉴权、Token刷新完整示例,拿去直接用!
本文介绍了如何在 Go 语言中使用 Gin 框架实现 JWT 用户认证和安全保护。JWT(JSON Web Token)是一种轻量、高效的认证与授权解决方案,特别适合微服务架构。文章详细讲解了 JWT 的基本概念、结构以及如何在 Gin 中生成、解析和刷新 JWT。通过示例代码,展示了如何在实际项目中应用 JWT,确保用户身份验证和数据安全。完整代码可在 GitHub 仓库中查看。
651 1
ThinkPHP 集成 jwt 技术 token 验证
本文介绍了在ThinkPHP框架中集成JWT技术进行token验证的流程,包括安装JWT扩展、创建Token服务类、编写中间件进行Token校验、配置路由中间件以及测试Token验证的步骤和代码示例。
ThinkPHP 集成 jwt 技术 token 验证
从0到1搭建权限管理系统系列三 .net8 JWT创建Token并使用
【9月更文挑战第22天】在.NET 8中,从零开始搭建权限管理系统并使用JWT(JSON Web Tokens)创建Token是关键步骤。JWT是一种开放标准(RFC 7519),用于安全传输信息,由头部、载荷和签名三部分组成。首先需安装`Microsoft.AspNetCore.Authentication.JwtBearer`包,并在`Program.cs`中配置JWT服务。接着,创建一个静态方法`GenerateToken`生成包含用户名和角色的Token。最后,在控制器中使用`[Authorize]`属性验证和解析Token,从而实现身份验证和授权功能。
503 3
数字堡垒之下:网络安全漏洞、加密技术与安全意识的博弈探索RESTful API设计的最佳实践
【8月更文挑战第27天】在数字化浪潮中,网络安全成为守护个人隐私与企业资产的关键防线。本文深入探讨了网络漏洞的成因与影响,分析了加密技术如何为数据保驾护航,并强调了提升公众的安全意识对于构建坚固的信息防御系统的重要性。文章旨在为读者提供一场思维的盛宴,启发更多关于如何在日益复杂的网络世界中保护自己的思考。
|
7月前
|
API
【Azure Developer】记录一段验证AAD JWT Token时需要设置代理获取openid-configuration内容
【Azure Developer】记录一段验证AAD JWT Token时需要设置代理获取openid-configuration内容
以项目登录接口为例-大前端之开发postman请求接口带token的请求测试-前端开发必学之一-如果要学会联调接口而不是纯写静态前端页面-这个是必学-本文以优雅草蜻蜓Q系统API为实践来演示我们如何带token请求接口-优雅草卓伊凡
以项目登录接口为例-大前端之开发postman请求接口带token的请求测试-前端开发必学之一-如果要学会联调接口而不是纯写静态前端页面-这个是必学-本文以优雅草蜻蜓Q系统API为实践来演示我们如何带token请求接口-优雅草卓伊凡
61 5
以项目登录接口为例-大前端之开发postman请求接口带token的请求测试-前端开发必学之一-如果要学会联调接口而不是纯写静态前端页面-这个是必学-本文以优雅草蜻蜓Q系统API为实践来演示我们如何带token请求接口-优雅草卓伊凡

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等