Issue generating LiveKit JWT Token in C#

168 views Asked by At

I'm trying to generate a LiveKit Token in C# for a custom implementation where available Node/Go SDKs are not suitable to be used.

I came up with the following code:

using System.Security.Claims;
using System.Text;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;


namespace LiveKitToken
{
    [Serializable]
    class VideoClaim
    {
        public string room { get; set; }
        public bool roomCreate { get; set; }
        public bool roomJoin { get; set; }
    }

    internal class TokenGenerator
    {
        public string CreateToken(string apiKey, string apiSecret, string roomName, string identity, TimeSpan validFor)
        {
            var now = DateTime.UtcNow;

            VideoClaim videoClaim = new VideoClaim()
            {
                room = roomName,
                roomCreate = true,
                roomJoin = true
            };

            var claims = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Iss, apiKey),
                new Claim(JwtRegisteredClaimNames.Sub, identity),
                new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(now).ToUnixTimeSeconds().ToString()),
                new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(now.Add(validFor)).ToUnixTimeSeconds().ToString()),
                new Claim("video", JsonConvert.SerializeObject(videoClaim, Formatting.Indented))
            };

            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(apiSecret));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                claims: claims,
                signingCredentials: credentials
            );

            var tokenHandler = new JwtSecurityTokenHandler();
            return tokenHandler.WriteToken(token);
        }
    }
}

The code works and actually generates a JWT Token, however the Token is invalid (I'm of course using valid apiKey and apiSecret for the corresponding server).

When I decode a valid Token I see this:

enter image description here

We can observe in the previous image that the video claim is an object, but for my code I get this:

enter image description here

In this case the video claim is always included as an string, more over, the constructor for a Claim in C# does not offer any type to add an object among the various types it supports.

I guess this is what causes my Token to be invalid but I haven't been able to generate a Token identical to the valid one.

Any help is much appreciated in advance!

0

There are 0 answers