0

I try to create a JWT in C# with the Libary Microsoft.IdentityModel.Tokens but the https://jwt.io/ always says that my signature is wrong. This is my following Code. My IJsonWebTokenModel just got a List of Claim. What is wrong with my Code and another question what is my private und my secret key and where do I get it from?

public string GenerateToken(IJsonWebTokenModel model)
{
    if (model == null || model.Claims == null || !model.Claims.Any())
        throw new ArgumentException("Arguments to create token are not valid.");

    IdentityModelEventSource.ShowPII = true;

    SecurityTokenDescriptor securityTokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(model.Claims),
        Expires = model.ExpiresAt,
        SigningCredentials = new SigningCredentials(GetPublicKey(), SecurityAlgorithms.RsaSha256Signature),
        //EncryptingCredentials = new EncryptingCredentials(GetPublicKey(), SecurityAlgorithms.RsaOAEP, SecurityAlgorithms.Aes128CbcHmacSha256)
    };

    JwtSecurityTokenHandler jwtSecurityTokenHandler = new JwtSecurityTokenHandler();

    var jweAymmetric = jwtSecurityTokenHandler.CreateToken(securityTokenDescriptor);

    string token = jwtSecurityTokenHandler.WriteToken(jweAymmetric);

    return token;
}

private SecurityKey GetPublicKey()
{
    using (var rsa = new RSACryptoServiceProvider(2048))
    {
        try
        {
            RSAParameters rsaKeyInfo = rsa.ExportParameters(true);
            var key = new RsaSecurityKey(rsaKeyInfo);
            return key;
        }
        finally
        {
            rsa.PersistKeyInCsp = false;
        }
    }
}
Lorenzo Isidori
  • 1,809
  • 2
  • 20
  • 31
Homer Tw
  • 85
  • 9
  • 1
    did you paste the public key into the key field in the right column at jwt.io? – jps Jul 26 '19 at 13:19
  • no because I don't know where I got my public key from and don't know where to paste it – Homer Tw Jul 26 '19 at 13:22
  • But when jwt.io doesn't know your key, how could it verify the signature? The key has to be pasted into the key field in the right column under `Verify Signature`. Maybe you should first start with HS256 signatures instead of RS256. – jps Jul 26 '19 at 13:31
  • I create my Key in the GetPublicKey Method so where can find the key actually? – Homer Tw Jul 26 '19 at 13:42
  • I think this might help: https://stackoverflow.com/questions/28406888/c-sharp-rsa-public-key-output-not-correct/28407693#28407693 because on jwt.io you need the public key in PEM format. – jps Jul 26 '19 at 13:54
  • and you need the public key to verify but with ExportParameters(true) as in you code above, you get the private key (which you need for signing the token) – jps Jul 26 '19 at 13:57

0 Answers0