How to generate JWT token signed with RS256 algorithm in C#

4.7k views Asked by At

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

There are 0 answers