1

I have a RSA Private key with me and I have to generate a JWT token using RS256 algorithm. I started with the below code which was working for "HmacSha256" algorithm but when i change it to RS256 it throws errors like " IDX10634: Unable to create the SignatureProvider.Algorithm: 'System.String',SecurityKey:'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey'"

After that I modified the code with RSACryptoServiceProvider() class. But i didnt get a solution. Please anyone can help with a sample code using RSACryptoServiceProvider class with a private key.

public static string CreateToken()//Dictionary<string, object> payload
{
    string key = GetConfiguration["privateKey"].Tostring();

    var securityKey = 
        new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(
            Encoding.UTF8.GetBytes(key));

    var credentials = 
        new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, "RS256");

    var header = new JwtHeader(credentials);

    JwtPayload payload = new JwtPayload();

    payload.AddClaim(
        new System.Security.Claims.Claim(
            "context", "{'user': { 'name': 'username', 'email': 'email' }}", 
            JsonClaimValueTypes.Json));
    payload.AddClaim(new System.Security.Claims.Claim("iss", @"app-key"));
    payload.AddClaim(new System.Security.Claims.Claim("aud", "meet.jitsi.com"));
    payload.AddClaim(new System.Security.Claims.Claim("sub", "meet.jitsi.com"));
    payload.AddClaim(new System.Security.Claims.Claim("room", "TestRoom"));

    var secToken = new JwtSecurityToken(header, payload);
    var handler = new JwtSecurityTokenHandler();

    var tokenString = handler.WriteToken(secToken);
    return tokenString;
}
Akber Iqbal
  • 14,487
  • 12
  • 48
  • 70
Shibin
  • 13
  • 1
  • 5
  • Does this answer your question? [JWT error IDX10634: Unable to create the SignatureProvider C#](https://stackoverflow.com/questions/49875167/jwt-error-idx10634-unable-to-create-the-signatureprovider-c-sharp) – Yong Shun May 24 '21 at 06:02
  • I am not clear with answer given. Where should i give my private key when i use RSACryptoServiceProvider class? can you please explain with a sample code? – Shibin May 24 '21 at 07:12
  • I am trying to use this code for RSA 256 jwt token generation.. please share your comments https://github.com/shibingit/jwttoken/blob/main/tokenmanager.cs – Shibin May 24 '21 at 10:24
  • @Shibin ... Have patience and read the article.. RS256 is an asymmetric algorithm, but you are trying to use SymmetricSecurityKey with it. – Akshay G May 24 '21 at 12:03
  • First, understand what's the difference between RS256 vs HS256. https://stackoverflow.com/questions/39239051/rs256-vs-hs256-whats-the-difference – Akshay G May 24 '21 at 12:13

0 Answers0