< Summary

Information
Class: Livekit.Server.Sdk.Dotnet.AccessToken
Assembly: LivekitApi
File(s): /home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitApi/AccessToken.cs
Line coverage
89%
Covered lines: 205
Uncovered lines: 25
Coverable lines: 230
Total lines: 575
Line coverage: 89.1%
Branch coverage
87%
Covered branches: 70
Total branches: 80
Branch coverage: 87.5%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%1010100%
WithTtl(...)100%11100%
WithExpiration(...)100%11100%
WithExpiration(...)100%11100%
WithNotBefore(...)100%11100%
WithNotBefore(...)100%11100%
WithGrants(...)100%11100%
WithSipGrants(...)100%11100%
WithInferenceGrants(...)100%11100%
WithObservabilityGrants(...)100%11100%
WithIdentity(...)100%11100%
WithKind(...)100%11100%
WithName(...)100%11100%
WithMetadata(...)100%11100%
WithAttributes(...)100%11100%
WithSha256(...)100%11100%
WithRoomPreset(...)100%11100%
WithRoomConfig(...)100%11100%
ToJwt()84.48%855880%
ConvertClaimsKeysToCamelCase(...)91.66%121288.88%
PascalToCamelCase(...)100%11100%
ToUnixSeconds(...)100%11100%

File(s)

/home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitApi/AccessToken.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Globalization;
 4using System.IdentityModel.Tokens.Jwt;
 5using System.Linq;
 6using System.Security.Claims;
 7using System.Text;
 8using Google.Protobuf;
 9using Microsoft.IdentityModel.Tokens;
 10using Newtonsoft.Json;
 11
 12namespace Livekit.Server.Sdk.Dotnet
 13{
 14    /// <summary>
 15    /// Access tokens are required to connect to the server.
 16    /// Once information is filled out, create the token string with <see cref="ToJwt"/>.
 17    /// See <see href="https://docs.livekit.io/frontends/reference/tokens-grants/">Access tokens and grants</see>.
 18    /// </summary>
 19    /// <example>
 20    /// <code language="csharp">
 21    /// var token = new AccessToken("api-key", "api-secret")
 22    ///     .WithIdentity("participant-identity")
 23    ///     .WithName("Participant name")
 24    ///     .WithGrants(new VideoGrants { RoomJoin = true, Room = "my-room" })
 25    ///     .WithTtl(TimeSpan.FromHours(1));
 26    /// string jwt = token.ToJwt();
 27    /// </code>
 28    /// </example>
 29    public class AccessToken
 30    {
 31        private readonly string apiKey;
 32        private readonly string apiSecret;
 33
 34        /// <summary>
 35        /// The claims of the token (identity, name, metadata, grants...), filled by the <c>With*</c> methods.
 36        /// </summary>
 37        public ClaimsModel Claims { get; private set; }
 33138        private TimeSpan ttl = Constants.DefaultTtl;
 39        private DateTime expiration;
 40        private DateTime notBefore;
 41
 42        /// <summary>
 43        /// Creates a token signed with the given API key and secret.
 44        /// </summary>
 45        /// <param name="apiKey">API key; the <c>LIVEKIT_API_KEY</c> environment variable when omitted.</param>
 46        /// <param name="apiSecret">API secret, at least 32 bytes long; the <c>LIVEKIT_API_SECRET</c> environment variab
 47        /// <exception cref="ArgumentException">The key or the secret is missing, or the secret is shorter than 32 bytes
 33148        public AccessToken(string apiKey = null, string apiSecret = null)
 33149        {
 33150            this.apiKey = apiKey ?? Environment.GetEnvironmentVariable("LIVEKIT_API_KEY");
 33151            this.apiSecret = apiSecret ?? Environment.GetEnvironmentVariable("LIVEKIT_API_SECRET");
 52
 33153            if (string.IsNullOrEmpty(this.apiKey) || string.IsNullOrEmpty(this.apiSecret))
 254            {
 255                throw new ArgumentException("apiKey and apiSecret must be set");
 56            }
 32957            if (Encoding.UTF8.GetBytes(this.apiSecret).Length < 32)
 158            {
 159                throw new ArgumentException(
 160                    "apiSecret must be at least 256 bits long. Currently it is "
 161                        + Encoding.UTF8.GetBytes(this.apiSecret).Length * 8
 162                        + " bits long"
 163                );
 64            }
 65
 32866            Claims = new ClaimsModel();
 32867        }
 68
 69        /// <summary>
 70        /// Amount of time the created token is valid for.
 71        /// Defaults to 6 hours.
 72        /// </summary>
 73        /// <param name="ttl">How long the token stays valid after it is generated.</param>
 74        /// <returns>This token, so calls can be chained.</returns>
 75        public AccessToken WithTtl(TimeSpan ttl)
 30576        {
 30577            this.ttl = ttl;
 30578            return this;
 30579        }
 80
 81        /// <summary>
 82        /// Used to specify an expiration time.
 83        /// If set, takes preference over the value set with <see cref="WithTtl"/>.
 84        /// </summary>
 85        /// <param name="expiration">Absolute expiration time. A value of kind <c>Unspecified</c> is read as local time.
 86        /// <returns>This token, so calls can be chained.</returns>
 87        public AccessToken WithExpiration(DateTime expiration)
 288        {
 289            this.expiration = expiration;
 290            return this;
 291        }
 92
 93        /// <summary>
 94        /// Used to specify an expiration time, with an explicit offset (a <see cref="DateTime"/>
 95        /// of kind <c>Unspecified</c> would be read as local time).
 96        /// If set, takes preference over the value set with <see cref="WithTtl"/>.
 97        /// </summary>
 98        /// <param name="expiration">Absolute expiration time.</param>
 99        /// <returns>This token, so calls can be chained.</returns>
 100        public AccessToken WithExpiration(DateTimeOffset expiration)
 2101        {
 2102            this.expiration = expiration.UtcDateTime;
 2103            return this;
 2104        }
 105
 106        /// <summary>
 107        /// Date specifying the time before which this token is invalid.
 108        /// If not set, the token is valid immediately after creation.
 109        /// See <see href="https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.5">RFC 7519</see>.
 110        /// </summary>
 111        /// <param name="notBefore">Time before which the token is not valid. A value of kind <c>Unspecified</c> is read
 112        /// <returns>This token, so calls can be chained.</returns>
 113        public AccessToken WithNotBefore(DateTime notBefore)
 2114        {
 2115            this.notBefore = notBefore;
 2116            return this;
 2117        }
 118
 119        /// <summary>
 120        /// Date specifying the time before which this token is invalid, with an explicit offset
 121        /// (a <see cref="DateTime"/> of kind <c>Unspecified</c> would be read as local time).
 122        /// </summary>
 123        /// <param name="notBefore">Time before which the token is not valid.</param>
 124        /// <returns>This token, so calls can be chained.</returns>
 125        public AccessToken WithNotBefore(DateTimeOffset notBefore)
 2126        {
 2127            this.notBefore = notBefore.UtcDateTime;
 2128            return this;
 2129        }
 130
 131        /// <summary>
 132        /// Adds <see cref="VideoGrants"/> to this token.
 133        /// </summary>
 134        /// <param name="grants">Room permissions of the token holder: joining, publishing, subscribing, room administra
 135        /// <returns>This token, so calls can be chained.</returns>
 136        public AccessToken WithGrants(VideoGrants grants)
 320137        {
 320138            Claims.Video = grants;
 320139            return this;
 320140        }
 141
 142        /// <summary>
 143        /// Adds <see cref="SIPGrants"/> to this token.
 144        /// </summary>
 145        /// <param name="grants">SIP permissions: administering trunks and dispatch rules (<c>Admin</c>) or making calls
 146        /// <returns>This token, so calls can be chained.</returns>
 147        public AccessToken WithSipGrants(SIPGrants grants)
 50148        {
 50149            Claims.Sip = grants;
 50150            return this;
 50151        }
 152
 153        /// <summary>
 154        /// Adds <see cref="InferenceGrants"/> to this token.
 155        /// </summary>
 156        /// <param name="grants">Inference permissions.</param>
 157        /// <returns>This token, so calls can be chained.</returns>
 158        public AccessToken WithInferenceGrants(InferenceGrants grants)
 1159        {
 1160            Claims.Inference = grants;
 1161            return this;
 1162        }
 163
 164        /// <summary>
 165        /// Adds <see cref="ObservabilityGrants"/> to this token.
 166        /// </summary>
 167        /// <param name="grants">Observability permissions.</param>
 168        /// <returns>This token, so calls can be chained.</returns>
 169        public AccessToken WithObservabilityGrants(ObservabilityGrants grants)
 1170        {
 1171            Claims.Observability = grants;
 1172            return this;
 1173        }
 174
 175        /// <summary>
 176        /// Unique identity of the user, required for room join tokens.
 177        /// </summary>
 178        /// <param name="identity">Identity of the participant, unique within the room.</param>
 179        /// <returns>This token, so calls can be chained.</returns>
 180        public AccessToken WithIdentity(string identity)
 11181        {
 11182            Claims.Identity = identity;
 11183            return this;
 11184        }
 185
 186        /// <summary>
 187        /// Sets the kind of participant, which lets other participants and services tell agents, SIP callers,
 188        /// egress and ingress apart from standard users.
 189        /// </summary>
 190        /// <param name="kind">Kind of participant: standard, egress, ingress, agent or SIP.</param>
 191        /// <returns>This token, so calls can be chained.</returns>
 192        public AccessToken WithKind(ParticipantInfo.Types.Kind kind)
 3193        {
 3194            Claims.Kind = kind.ToString().ToLowerInvariant();
 3195            return this;
 3196        }
 197
 198        /// <summary>
 199        /// Display name of the participant, which the other participants see.
 200        /// </summary>
 201        /// <param name="name">Display name shown to the other participants.</param>
 202        /// <returns>This token, so calls can be chained.</returns>
 203        public AccessToken WithName(string name)
 5204        {
 5205            Claims.Name = name;
 5206            return this;
 5207        }
 208
 209        /// <summary>
 210        /// Custom metadata to be passed to participants.
 211        /// </summary>
 212        /// <param name="metadata">Free-form metadata attached to the participant and visible to the others.</param>
 213        /// <returns>This token, so calls can be chained.</returns>
 214        public AccessToken WithMetadata(string metadata)
 3215        {
 3216            Claims.Metadata = metadata;
 3217            return this;
 3218        }
 219
 220        /// <summary>
 221        /// Key/value attributes to attach to the participant.
 222        /// </summary>
 223        /// <param name="attributes">Key/value attributes attached to the participant.</param>
 224        /// <returns>This token, so calls can be chained.</returns>
 225        public AccessToken WithAttributes(Dictionary<string, string> attributes)
 1226        {
 1227            Claims.Attributes = attributes;
 1228            return this;
 1229        }
 230
 231        /// <summary>
 232        /// For verifying the integrity of the message body.
 233        /// </summary>
 234        /// <param name="sha256">Base64 SHA-256 of the message body the token authenticates (used by webhooks).</param>
 235        /// <returns>This token, so calls can be chained.</returns>
 236        public AccessToken WithSha256(string sha256)
 9237        {
 9238            Claims.Sha256 = sha256;
 9239            return this;
 9240        }
 241
 242        /// <summary>
 243        /// Name of the room configuration preset to apply when this token creates the room.
 244        /// </summary>
 245        /// <param name="roomPreset">Name of the room configuration preset.</param>
 246        /// <returns>This token, so calls can be chained.</returns>
 247        public AccessToken WithRoomPreset(string roomPreset)
 1248        {
 1249            Claims.RoomPreset = roomPreset;
 1250            return this;
 1251        }
 252
 253        /// <summary>
 254        /// Room configuration (agents to dispatch, egress, limits...) applied when this token creates the room.
 255        /// </summary>
 256        /// <param name="roomConfig">Room configuration: agents to dispatch, egress, participant limits...</param>
 257        /// <returns>This token, so calls can be chained.</returns>
 258        public AccessToken WithRoomConfig(RoomConfiguration roomConfig)
 3259        {
 3260            Claims.RoomConfig = roomConfig;
 3261            return this;
 3262        }
 263
 264        /// <summary>
 265        /// Generates the JWT token as a string.
 266        /// </summary>
 267        /// <returns>The signed JWT.</returns>
 268        public string ToJwt()
 328269        {
 328270            var video = Claims.Video;
 328271            if (
 328272                video != null
 328273                && video.RoomJoin
 328274                && (string.IsNullOrEmpty(Claims.Identity) || string.IsNullOrEmpty(video.Room))
 328275            )
 4276            {
 4277                throw new ArgumentException("identity and room must be set when joining a room");
 278            }
 279
 280            // Whole seconds, like the other LiveKit SDKs: the JWT spec defines these claims as
 281            // numeric dates, and a fractional value would be formatted with the current culture.
 324282            var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
 283
 324284            var exp =
 324285                expiration == DateTime.MinValue
 324286                    ? now + (long)ttl.TotalSeconds
 324287                    : ToUnixSeconds(expiration);
 288
 324289            var nbf = notBefore == DateTime.MinValue ? now : ToUnixSeconds(notBefore);
 290
 324291            var jwtClaims = new Dictionary<string, object>
 324292            {
 324293                { "sub", Claims.Identity ?? "" },
 324294                { "jti", Claims.Identity ?? "" },
 324295                { "iss", apiKey },
 324296                { "nbf", nbf },
 324297                { "iat", now },
 324298                { "exp", exp },
 324299            };
 300
 324301            jwtClaims["video"] = ConvertClaimsKeysToCamelCase(Claims.Video ?? new VideoGrants());
 324302            jwtClaims["sip"] = ConvertClaimsKeysToCamelCase(Claims.Sip ?? new SIPGrants());
 324303            if (Claims.Inference != null)
 1304            {
 1305                jwtClaims["inference"] = ConvertClaimsKeysToCamelCase(Claims.Inference);
 1306            }
 324307            if (Claims.Observability != null)
 1308            {
 1309                jwtClaims["observability"] = ConvertClaimsKeysToCamelCase(Claims.Observability);
 1310            }
 311
 312            // Optional claims are only written when set, like the other LiveKit SDKs do (the
 313            // server marks them omitempty). A null value used to throw a NullReferenceException.
 324314            if (!string.IsNullOrEmpty(Claims.Name))
 4315            {
 4316                jwtClaims["name"] = Claims.Name;
 4317            }
 324318            if (!string.IsNullOrEmpty(Claims.Metadata))
 2319            {
 2320                jwtClaims["metadata"] = Claims.Metadata;
 2321            }
 324322            if (!string.IsNullOrEmpty(Claims.Sha256))
 8323            {
 8324                jwtClaims["sha256"] = Claims.Sha256;
 8325            }
 324326            if (!string.IsNullOrEmpty(Claims.Kind))
 3327            {
 3328                jwtClaims["kind"] = Claims.Kind;
 3329            }
 324330            if (Claims.Attributes != null && Claims.Attributes.Count > 0)
 1331            {
 1332                jwtClaims["attributes"] = Claims.Attributes;
 1333            }
 324334            if (!string.IsNullOrEmpty(Claims.RoomPreset))
 1335            {
 1336                jwtClaims["roomPreset"] = Claims.RoomPreset;
 1337            }
 324338            if (Claims.RoomConfig != null && Claims.RoomConfig.CalculateSize() > 0)
 3339            {
 3340                jwtClaims["roomConfig"] = Claims.RoomConfig;
 3341            }
 342
 324343            List<Claim> claims = new List<Claim>();
 6204344            foreach (var kv in jwtClaims)
 2616345            {
 2616346                switch (kv.Value)
 347                {
 348                    case string val:
 990349                        claims.Add(new Claim(kv.Key, val));
 990350                        break;
 351                    case int val:
 0352                        claims.Add(
 0353                            new Claim(
 0354                                kv.Key,
 0355                                val.ToString(CultureInfo.InvariantCulture),
 0356                                ClaimValueTypes.Integer64
 0357                            )
 0358                        );
 0359                        break;
 360                    case long val:
 972361                        claims.Add(
 972362                            new Claim(
 972363                                kv.Key,
 972364                                val.ToString(CultureInfo.InvariantCulture),
 972365                                ClaimValueTypes.Integer64
 972366                            )
 972367                        );
 972368                        break;
 369                    case double val:
 0370                        claims.Add(
 0371                            new Claim(
 0372                                kv.Key,
 0373                                val.ToString(CultureInfo.InvariantCulture),
 0374                                ClaimValueTypes.Double
 0375                            )
 0376                        );
 0377                        break;
 378                    case bool val:
 0379                        claims.Add(new Claim(kv.Key, val.ToString(), ClaimValueTypes.Boolean));
 0380                        break;
 381                    case Dictionary<string, object> val:
 650382                        var jsonString = JsonConvert.SerializeObject(kv.Value);
 650383                        claims.Add(new Claim(kv.Key, jsonString, JsonClaimValueTypes.Json));
 650384                        break;
 385                    case Dictionary<string, string> val:
 1386                        var jsonString2 = JsonConvert.SerializeObject(kv.Value);
 1387                        claims.Add(new Claim(kv.Key, jsonString2, JsonClaimValueTypes.Json));
 1388                        break;
 389                    default:
 390                        try
 3391                        {
 392                            // Try protobuf formatter
 3393                            var jsonString3 = JsonFormatter.Default.Format(kv.Value as IMessage);
 3394                            claims.Add(new Claim(kv.Key, jsonString3, JsonClaimValueTypes.Json));
 3395                            break;
 396                        }
 0397                        catch (Exception)
 0398                        {
 0399                            throw new ArgumentException(
 0400                                $"unsupported claim type {kv.Value.GetType()}"
 0401                            );
 402                        }
 403                }
 2616404            }
 405
 324406            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(apiSecret));
 324407            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
 324408            var token = new JwtSecurityToken(claims: claims, signingCredentials: credentials);
 409
 324410            return new JwtSecurityTokenHandler().WriteToken(token);
 324411        }
 412
 413        // Empty strings and lists are omitted, like the other LiveKit SDKs do (the server treats
 414        // them as unset anyway)
 415        private static Dictionary<string, object> ConvertClaimsKeysToCamelCase(object obj)
 650416        {
 650417            var result = new Dictionary<string, object>();
 14914418            foreach (var prop in obj.GetType().GetProperties())
 6482419            {
 6482420                var value = prop.GetValue(obj);
 6482421                if (value == null)
 0422                {
 0423                    continue;
 424                }
 6482425                if (value is string s && s.Length == 0)
 602426                {
 602427                    continue;
 428                }
 5880429                if (value is System.Collections.ICollection c && c.Count == 0)
 323430                {
 323431                    continue;
 432                }
 5557433                result[PascalToCamelCase(prop.Name)] = value;
 5557434            }
 650435            return result;
 650436        }
 437
 438        private static string PascalToCamelCase(string str)
 5557439        {
 5557440            return char.ToLowerInvariant(str[0]) + str.Substring(1);
 5557441        }
 442
 443        private static long ToUnixSeconds(DateTime dateTime)
 8444        {
 8445            return (long)
 8446                Math.Floor(
 8447                    dateTime
 8448                        .ToUniversalTime()
 8449                        .Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
 8450                        .TotalSeconds
 8451                );
 8452        }
 453    }
 454
 455    /// <summary>
 456    /// Helper to verify the integrity of a token.
 457    /// </summary>
 458    public class TokenVerifier
 459    {
 460        private readonly string apiKey;
 461        private readonly string apiSecret;
 462        private readonly TimeSpan leeway;
 463
 464        /// <summary>
 465        /// Creates a verifier for tokens signed with the given API key and secret.
 466        /// </summary>
 467        /// <param name="apiKey">API key the tokens must be issued by; the <c>LIVEKIT_API_KEY</c> environment variable w
 468        /// <param name="apiSecret">API secret the tokens must be signed with; the <c>LIVEKIT_API_SECRET</c> environment
 469        /// <param name="leeway">Clock tolerance applied to the token lifetime; <see cref="Constants.DefaultLeeway"/> wh
 470        /// <exception cref="ArgumentException">The key or the secret is missing, or the secret is shorter than 32 bytes
 471        public TokenVerifier(string apiKey = null, string apiSecret = null, TimeSpan? leeway = null)
 472        {
 473            this.apiKey = apiKey ?? Environment.GetEnvironmentVariable("LIVEKIT_API_KEY");
 474            this.apiSecret = apiSecret ?? Environment.GetEnvironmentVariable("LIVEKIT_API_SECRET");
 475            this.leeway = leeway ?? Constants.DefaultLeeway;
 476
 477            if (string.IsNullOrEmpty(this.apiKey) || string.IsNullOrEmpty(this.apiSecret))
 478            {
 479                throw new ArgumentException("apiKey and apiSecret must be set");
 480            }
 481            if (Encoding.UTF8.GetBytes(this.apiSecret).Length < 32)
 482            {
 483                throw new ArgumentException(
 484                    "apiSecret must be at least 256 bits long. Currently it is "
 485                        + Encoding.UTF8.GetBytes(this.apiSecret).Length * 8
 486                        + " bits long"
 487                );
 488            }
 489        }
 490
 491        /// <summary>
 492        /// Validates the signature, the issuer and the lifetime of a token and returns its claims.
 493        /// </summary>
 494        /// <param name="token">The JWT to verify.</param>
 495        /// <returns>The claims of the token.</returns>
 496        /// <exception cref="Microsoft.IdentityModel.Tokens.SecurityTokenException">The token has a wrong signature or i
 497        /// <exception cref="ArgumentException">The token is not a well-formed JWT (<c>SecurityTokenMalformedException</
 498        public ClaimsModel Verify(string token)
 499        {
 500            var validationParameters = new TokenValidationParameters
 501            {
 502                ValidateIssuer = true,
 503                ValidateIssuerSigningKey = true,
 504                ValidIssuer = apiKey,
 505                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(apiSecret)),
 506                ValidateLifetime = true,
 507                ValidateAudience = false,
 508                ClockSkew = leeway,
 509                // LiveKit tokens are always HS256 (the Python SDK pins the algorithm too)
 510                ValidAlgorithms = new[] { SecurityAlgorithms.HmacSha256 },
 511            };
 512
 513            var tokenHandler = new JwtSecurityTokenHandler();
 514            var principal = tokenHandler.ValidateToken(
 515                token,
 516                validationParameters,
 517                out var securityToken
 518            );
 519            // A JSON array claim yields one Claim per element: keep the first instead of throwing
 520            var claims = principal
 521                .Claims.GroupBy(claim => claim.Type)
 522                .ToDictionary(group => group.Key, group => group.First().Value);
 523            var decodedSecurityToken = (JwtSecurityToken)securityToken;
 524
 525            var video = new VideoGrants();
 526            var exists = claims.TryGetValue("video", out var videoClaim);
 527            if (exists && videoClaim != null)
 528            {
 529                video = JsonConvert.DeserializeObject<VideoGrants>(videoClaim);
 530            }
 531
 532            var sip = claims.TryGetValue("sip", out var sipClaim)
 533                ? JsonConvert.DeserializeObject<SIPGrants>(sipClaim)
 534                : new SIPGrants();
 535
 536            var inference = claims.TryGetValue("inference", out var inferenceClaim)
 537                ? JsonConvert.DeserializeObject<InferenceGrants>(inferenceClaim)
 538                : null;
 539            var observability = claims.TryGetValue("observability", out var observabilityClaim)
 540                ? JsonConvert.DeserializeObject<ObservabilityGrants>(observabilityClaim)
 541                : null;
 542
 543            var claimsModel = new ClaimsModel
 544            {
 545                Identity = decodedSecurityToken.Subject != null ? decodedSecurityToken.Subject : "",
 546                Name = claims.TryGetValue("name", out var name) ? name : "",
 547                Video = video,
 548                Sip = sip,
 549                Inference = inference,
 550                Observability = observability,
 551                Metadata = claims.TryGetValue("metadata", out var metadata) ? metadata : "",
 552                Sha256 = claims.TryGetValue("sha256", out var sha256) ? sha256 : "",
 553                Kind = claims.TryGetValue("kind", out var kind) ? kind : "",
 554                Attributes = JsonConvert.DeserializeObject<Dictionary<string, string>>(
 555                    claims.TryGetValue("attributes", out var attributes) ? attributes : "{}"
 556                ),
 557            };
 558
 559            if (claims.TryGetValue("roomPreset", out var roomPreset))
 560            {
 561                claimsModel.RoomPreset = roomPreset;
 562            }
 563            if (claims.TryGetValue("roomConfig", out var roomConfig))
 564            {
 565                // Written with the protobuf JSON formatter (enum names, oneofs...): read it back
 566                // with the protobuf JSON parser, not with Newtonsoft
 567                claimsModel.RoomConfig = new JsonParser(
 568                    JsonParser.Settings.Default.WithIgnoreUnknownFields(true)
 569                ).Parse<RoomConfiguration>(roomConfig);
 570            }
 571
 572            return claimsModel;
 573        }
 574    }
 575}