jwt-dotnet / jwt

Jwt.Net, a JWT (JSON Web Token) implementation for .NET
Other
2.12k stars 462 forks source link

Sign via RSA256 with only Private Key #393

Closed michaelakin closed 2 years ago

michaelakin commented 2 years ago

I am trying to create a bearer token with an RSA Private key according to NetSuite's documentation:

but I Can't figure out how to construct the api call.

Here is what I have so far.

  var rsaPrivateKey = RSA.Create();
  rsaPrivateKey.ImportFromPem(CertSecret);
  //var x509 = new X509Certificate2();
  //x509.CopyWithPrivateKey(rsaPrivateKey);

  var jwtToken = JwtBuilder.Create()
            .WithAlgorithm(new RS256Algorithm(null, rsaPrivateKey))
            .AddHeader("kid", "wX39xsRJEe9GfI6ro")
            .Issuer("TEST")
            .Audience("https://test.suitetalk.api.netsuite.com/services/rest/auth/oauth2/v1/token")
            .AddClaim("exp", DateTimeOffset.UtcNow.AddHours(1).ToUnixTimeSeconds())
            .AddClaim("scope", "rest_webservices")
            .AddClaim("iat", DateTimeOffset.UtcNow.ToUnixTimeSeconds())
            .Encode();

I get an error that the public key must not be null, but I don't have a public key, but I DO have a Certificate.

Here is the command I was told to use to create the certificate and the private key: openssl req -x509 -newkey rsa:4096 -sha256 -keyout auth-key.pem -out auth-cert.pem -nodes -days 730

How can I get this package to sign with only a Private key?

abatishchev commented 2 years ago

hi! here's the code:

https://github.com/jwt-dotnet/jwt/blob/47cdba3dee007ab8224cf2f6c3e613e3420f9502/src/JWT/Algorithms/RS256Algorithm.cs#L16-L19

which then calls:

https://github.com/jwt-dotnet/jwt/blob/47cdba3dee007ab8224cf2f6c3e613e3420f9502/src/JWT/Algorithms/RSAlgorithm.cs#L20-L24

hence the exception.

Can you try this:

new RS256Algorithm(rsaPrivateKey, rsaPrivateKey)
michaelakin commented 2 years ago

Can you try this:

new RS256Algorithm(rsaPrivateKey, rsaPrivateKey)

Thanks, that did not throw the exception, but I was still not able to connect. Is it using BOTH keys to encrypt, or just 1?

abatishchev commented 2 years ago

It uses the public to validate and the private to encrypt.

michaelakin commented 2 years ago

Ok, so why does it require both if I am just encoding?

abatishchev commented 2 years ago

It just wasn't a scenario so far discussed/supported. Another reason - tecnicaal, there are two ctors:

  1. new RS256Algorithm(RSA, rsaPublicKey)
  2. new RS256Algorithm(rsaPublicKey)

So I can't add a third one:

  1. new RS256Algorithm(rsaPublicKey)

Since they would clash.

abatishchev commented 2 years ago

Btw can you just pass the certificate itself?

michaelakin commented 2 years ago

I haven't tried that option I guess.