c# - 如何为我的 JWT 创建签名?

标签 c# encryption jwt box

根据 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指向 Box .NET SDK by Box Mobile Team在 GitHub 上有一个 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;
}

希望这对您有所帮助。

关于c# - 如何为我的 JWT 创建签名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36020376/

相关文章:

c# - Sharepoint - 通过 CAML 按用户 ID 过滤列表

javascript - Node .js/SAML : How to decrypt contents of RequestedSecurityToken

java - 如何以编程方式发送加密电子邮件(从自动化过程)

authentication - 如何在 flutter 应用程序的入口点检查身份验证 token

c# - 属性 C# 上的几个 XmlElement 属性

c# - 可视化 WPF 控件中的对象属性

c# - 从字符串中选择精确匹配的数字

java - RSA Ruby 和 Android 填充问题

go - 如何检查 JWT token 剩余有效期 golang

angular - JWT 和防伪 token