简体   繁体   中英

How to create signature for my JWT?

According to JWT (specifically, using the Box.com api), you need to

  1. create your header and claims, base 64 url encode them, join them with a dot.

  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 . For Box.com, it would be using RS256.

  3. You then send that to the provider (again, in this case Box.com) and everything should be fine and dandy.

I have step 1 no problem.

Step 2 is a bit of a problem for me.

  1. I assume I use my ... private key? Edit: Nope, private key is to decrypt.

  2. Although far too many examples exist of doing this with HSA, I need to use RSA and the System.IdentityModel.Tokens.JWT_stuff process has not been very forthcoming with helping. There are a couple other packages and libraries I could use that would be so easy if Box.com allowed for HSA256.

I've taken a look at this question and it hasn't been incredibly helpful.

So what do I need to do to complete step 2? In other words: How can I encrypt using RSA256 in C#?

A quick look at Box.com's developer page points to Box .NET SDK by Box Mobile Team on GitHub where there is a BoxJWTAuth.cs with some code you can look at where they use RSA.

There is even a Box.V2.Samples.JWTAuth/Program.cs where they show how to use it.

On inspecting BoxJWTAuth I saw this snippet of code

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;
}

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM