如何为我的 JWT 创建签名?

How to create signature for my JWT?

根据 JWT(具体来说,使用 Box.com api),你需要

  1. 创建你的 header 和声明,base 64 url 编码它们,用点连接它们。

  2. You then need to take that and the secret key (a little confusion here, more on that in a second) and then encrypt them。对于 Box.com,它将使用 RS256。

  3. 然后您将其发送给提供商(同样,在本例中 Box.com),一切都应该很好。

我第 1 步没问题。

第 2 步对我来说有点问题。

  1. 我假设我使用我的...私钥?编辑:不,私钥是解密。

  2. 虽然存在太多使用 HSA 执行此操作的示例,但我需要使用 RSA,并且 System.IdentityModel.Tokens.JWT_stuff 过程并没有提供很好的帮助。如果 Box.com 允许 HSA256,我可以使用其他几个包和库,它们会非常简单。

我已经看了一下 this question,但并没有太大帮助。

那么我需要做什么才能完成第 2 步?换句话说:如何在 C# 中使用 RSA256 进行加密?

通过一些代码快速浏览 Box.com's developer page points to Box .NET SDK by Box Mobile Team on GitHub where there is a BoxJWTAuth.cs,您可以查看他们在哪里使用 RSA。

甚至还有一个 Box.V2.Samples.JWTAuth/Program.cs 展示了如何使用它。

在检查 BoxJWTAuth 时,我看到了这段代码

private string ConstructJWTAssertion(string sub, string boxSubType)
{
    byte[] randomNumber = new byte[64];
    using (var rng = new RNGCryptoServiceProvider())
    {
        rng.GetBytes(randomNumber);
    }

    var claims = new List<Claim>{
        new Claim("sub", sub),
        new Claim("box_sub_type", boxSubType),
        new Claim("jti", Convert.ToBase64String(randomNumber)),
    };

    var payload = new JwtPayload(this.boxConfig.ClientId, AUTH_URL, claims, null, DateTime.UtcNow.AddSeconds(30));

    var header = new JwtHeader(signingCredentials: this.credentials);
    if (this.boxConfig.JWTPublicKeyId != null)
        header.Add("kid", this.boxConfig.JWTPublicKeyId);

    var token = new JwtSecurityToken(header, payload);
    var tokenHandler = new JwtSecurityTokenHandler();
    string assertion = tokenHandler.WriteToken(token);
    return assertion;
}

希望对您有所帮助。