| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Globalization; |
| | | 4 | | using System.IdentityModel.Tokens.Jwt; |
| | | 5 | | using System.Linq; |
| | | 6 | | using System.Security.Claims; |
| | | 7 | | using System.Text; |
| | | 8 | | using Google.Protobuf; |
| | | 9 | | using Microsoft.IdentityModel.Tokens; |
| | | 10 | | using Newtonsoft.Json; |
| | | 11 | | |
| | | 12 | | namespace 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; } |
| | | 38 | | 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 |
| | | 48 | | public AccessToken(string apiKey = null, string apiSecret = null) |
| | | 49 | | { |
| | | 50 | | this.apiKey = apiKey ?? Environment.GetEnvironmentVariable("LIVEKIT_API_KEY"); |
| | | 51 | | this.apiSecret = apiSecret ?? Environment.GetEnvironmentVariable("LIVEKIT_API_SECRET"); |
| | | 52 | | |
| | | 53 | | if (string.IsNullOrEmpty(this.apiKey) || string.IsNullOrEmpty(this.apiSecret)) |
| | | 54 | | { |
| | | 55 | | throw new ArgumentException("apiKey and apiSecret must be set"); |
| | | 56 | | } |
| | | 57 | | if (Encoding.UTF8.GetBytes(this.apiSecret).Length < 32) |
| | | 58 | | { |
| | | 59 | | throw new ArgumentException( |
| | | 60 | | "apiSecret must be at least 256 bits long. Currently it is " |
| | | 61 | | + Encoding.UTF8.GetBytes(this.apiSecret).Length * 8 |
| | | 62 | | + " bits long" |
| | | 63 | | ); |
| | | 64 | | } |
| | | 65 | | |
| | | 66 | | Claims = new ClaimsModel(); |
| | | 67 | | } |
| | | 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) |
| | | 76 | | { |
| | | 77 | | this.ttl = ttl; |
| | | 78 | | return this; |
| | | 79 | | } |
| | | 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) |
| | | 88 | | { |
| | | 89 | | this.expiration = expiration; |
| | | 90 | | return this; |
| | | 91 | | } |
| | | 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) |
| | | 101 | | { |
| | | 102 | | this.expiration = expiration.UtcDateTime; |
| | | 103 | | return this; |
| | | 104 | | } |
| | | 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) |
| | | 114 | | { |
| | | 115 | | this.notBefore = notBefore; |
| | | 116 | | return this; |
| | | 117 | | } |
| | | 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) |
| | | 126 | | { |
| | | 127 | | this.notBefore = notBefore.UtcDateTime; |
| | | 128 | | return this; |
| | | 129 | | } |
| | | 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) |
| | | 137 | | { |
| | | 138 | | Claims.Video = grants; |
| | | 139 | | return this; |
| | | 140 | | } |
| | | 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) |
| | | 148 | | { |
| | | 149 | | Claims.Sip = grants; |
| | | 150 | | return this; |
| | | 151 | | } |
| | | 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) |
| | | 159 | | { |
| | | 160 | | Claims.Inference = grants; |
| | | 161 | | return this; |
| | | 162 | | } |
| | | 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) |
| | | 170 | | { |
| | | 171 | | Claims.Observability = grants; |
| | | 172 | | return this; |
| | | 173 | | } |
| | | 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) |
| | | 181 | | { |
| | | 182 | | Claims.Identity = identity; |
| | | 183 | | return this; |
| | | 184 | | } |
| | | 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) |
| | | 193 | | { |
| | | 194 | | Claims.Kind = kind.ToString().ToLowerInvariant(); |
| | | 195 | | return this; |
| | | 196 | | } |
| | | 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) |
| | | 204 | | { |
| | | 205 | | Claims.Name = name; |
| | | 206 | | return this; |
| | | 207 | | } |
| | | 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) |
| | | 215 | | { |
| | | 216 | | Claims.Metadata = metadata; |
| | | 217 | | return this; |
| | | 218 | | } |
| | | 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) |
| | | 226 | | { |
| | | 227 | | Claims.Attributes = attributes; |
| | | 228 | | return this; |
| | | 229 | | } |
| | | 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) |
| | | 237 | | { |
| | | 238 | | Claims.Sha256 = sha256; |
| | | 239 | | return this; |
| | | 240 | | } |
| | | 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) |
| | | 248 | | { |
| | | 249 | | Claims.RoomPreset = roomPreset; |
| | | 250 | | return this; |
| | | 251 | | } |
| | | 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) |
| | | 259 | | { |
| | | 260 | | Claims.RoomConfig = roomConfig; |
| | | 261 | | return this; |
| | | 262 | | } |
| | | 263 | | |
| | | 264 | | /// <summary> |
| | | 265 | | /// Generates the JWT token as a string. |
| | | 266 | | /// </summary> |
| | | 267 | | /// <returns>The signed JWT.</returns> |
| | | 268 | | public string ToJwt() |
| | | 269 | | { |
| | | 270 | | var video = Claims.Video; |
| | | 271 | | if ( |
| | | 272 | | video != null |
| | | 273 | | && video.RoomJoin |
| | | 274 | | && (string.IsNullOrEmpty(Claims.Identity) || string.IsNullOrEmpty(video.Room)) |
| | | 275 | | ) |
| | | 276 | | { |
| | | 277 | | 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. |
| | | 282 | | var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); |
| | | 283 | | |
| | | 284 | | var exp = |
| | | 285 | | expiration == DateTime.MinValue |
| | | 286 | | ? now + (long)ttl.TotalSeconds |
| | | 287 | | : ToUnixSeconds(expiration); |
| | | 288 | | |
| | | 289 | | var nbf = notBefore == DateTime.MinValue ? now : ToUnixSeconds(notBefore); |
| | | 290 | | |
| | | 291 | | var jwtClaims = new Dictionary<string, object> |
| | | 292 | | { |
| | | 293 | | { "sub", Claims.Identity ?? "" }, |
| | | 294 | | { "jti", Claims.Identity ?? "" }, |
| | | 295 | | { "iss", apiKey }, |
| | | 296 | | { "nbf", nbf }, |
| | | 297 | | { "iat", now }, |
| | | 298 | | { "exp", exp }, |
| | | 299 | | }; |
| | | 300 | | |
| | | 301 | | jwtClaims["video"] = ConvertClaimsKeysToCamelCase(Claims.Video ?? new VideoGrants()); |
| | | 302 | | jwtClaims["sip"] = ConvertClaimsKeysToCamelCase(Claims.Sip ?? new SIPGrants()); |
| | | 303 | | if (Claims.Inference != null) |
| | | 304 | | { |
| | | 305 | | jwtClaims["inference"] = ConvertClaimsKeysToCamelCase(Claims.Inference); |
| | | 306 | | } |
| | | 307 | | if (Claims.Observability != null) |
| | | 308 | | { |
| | | 309 | | jwtClaims["observability"] = ConvertClaimsKeysToCamelCase(Claims.Observability); |
| | | 310 | | } |
| | | 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. |
| | | 314 | | if (!string.IsNullOrEmpty(Claims.Name)) |
| | | 315 | | { |
| | | 316 | | jwtClaims["name"] = Claims.Name; |
| | | 317 | | } |
| | | 318 | | if (!string.IsNullOrEmpty(Claims.Metadata)) |
| | | 319 | | { |
| | | 320 | | jwtClaims["metadata"] = Claims.Metadata; |
| | | 321 | | } |
| | | 322 | | if (!string.IsNullOrEmpty(Claims.Sha256)) |
| | | 323 | | { |
| | | 324 | | jwtClaims["sha256"] = Claims.Sha256; |
| | | 325 | | } |
| | | 326 | | if (!string.IsNullOrEmpty(Claims.Kind)) |
| | | 327 | | { |
| | | 328 | | jwtClaims["kind"] = Claims.Kind; |
| | | 329 | | } |
| | | 330 | | if (Claims.Attributes != null && Claims.Attributes.Count > 0) |
| | | 331 | | { |
| | | 332 | | jwtClaims["attributes"] = Claims.Attributes; |
| | | 333 | | } |
| | | 334 | | if (!string.IsNullOrEmpty(Claims.RoomPreset)) |
| | | 335 | | { |
| | | 336 | | jwtClaims["roomPreset"] = Claims.RoomPreset; |
| | | 337 | | } |
| | | 338 | | if (Claims.RoomConfig != null && Claims.RoomConfig.CalculateSize() > 0) |
| | | 339 | | { |
| | | 340 | | jwtClaims["roomConfig"] = Claims.RoomConfig; |
| | | 341 | | } |
| | | 342 | | |
| | | 343 | | List<Claim> claims = new List<Claim>(); |
| | | 344 | | foreach (var kv in jwtClaims) |
| | | 345 | | { |
| | | 346 | | switch (kv.Value) |
| | | 347 | | { |
| | | 348 | | case string val: |
| | | 349 | | claims.Add(new Claim(kv.Key, val)); |
| | | 350 | | break; |
| | | 351 | | case int val: |
| | | 352 | | claims.Add( |
| | | 353 | | new Claim( |
| | | 354 | | kv.Key, |
| | | 355 | | val.ToString(CultureInfo.InvariantCulture), |
| | | 356 | | ClaimValueTypes.Integer64 |
| | | 357 | | ) |
| | | 358 | | ); |
| | | 359 | | break; |
| | | 360 | | case long val: |
| | | 361 | | claims.Add( |
| | | 362 | | new Claim( |
| | | 363 | | kv.Key, |
| | | 364 | | val.ToString(CultureInfo.InvariantCulture), |
| | | 365 | | ClaimValueTypes.Integer64 |
| | | 366 | | ) |
| | | 367 | | ); |
| | | 368 | | break; |
| | | 369 | | case double val: |
| | | 370 | | claims.Add( |
| | | 371 | | new Claim( |
| | | 372 | | kv.Key, |
| | | 373 | | val.ToString(CultureInfo.InvariantCulture), |
| | | 374 | | ClaimValueTypes.Double |
| | | 375 | | ) |
| | | 376 | | ); |
| | | 377 | | break; |
| | | 378 | | case bool val: |
| | | 379 | | claims.Add(new Claim(kv.Key, val.ToString(), ClaimValueTypes.Boolean)); |
| | | 380 | | break; |
| | | 381 | | case Dictionary<string, object> val: |
| | | 382 | | var jsonString = JsonConvert.SerializeObject(kv.Value); |
| | | 383 | | claims.Add(new Claim(kv.Key, jsonString, JsonClaimValueTypes.Json)); |
| | | 384 | | break; |
| | | 385 | | case Dictionary<string, string> val: |
| | | 386 | | var jsonString2 = JsonConvert.SerializeObject(kv.Value); |
| | | 387 | | claims.Add(new Claim(kv.Key, jsonString2, JsonClaimValueTypes.Json)); |
| | | 388 | | break; |
| | | 389 | | default: |
| | | 390 | | try |
| | | 391 | | { |
| | | 392 | | // Try protobuf formatter |
| | | 393 | | var jsonString3 = JsonFormatter.Default.Format(kv.Value as IMessage); |
| | | 394 | | claims.Add(new Claim(kv.Key, jsonString3, JsonClaimValueTypes.Json)); |
| | | 395 | | break; |
| | | 396 | | } |
| | | 397 | | catch (Exception) |
| | | 398 | | { |
| | | 399 | | throw new ArgumentException( |
| | | 400 | | $"unsupported claim type {kv.Value.GetType()}" |
| | | 401 | | ); |
| | | 402 | | } |
| | | 403 | | } |
| | | 404 | | } |
| | | 405 | | |
| | | 406 | | var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(apiSecret)); |
| | | 407 | | var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); |
| | | 408 | | var token = new JwtSecurityToken(claims: claims, signingCredentials: credentials); |
| | | 409 | | |
| | | 410 | | return new JwtSecurityTokenHandler().WriteToken(token); |
| | | 411 | | } |
| | | 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) |
| | | 416 | | { |
| | | 417 | | var result = new Dictionary<string, object>(); |
| | | 418 | | foreach (var prop in obj.GetType().GetProperties()) |
| | | 419 | | { |
| | | 420 | | var value = prop.GetValue(obj); |
| | | 421 | | if (value == null) |
| | | 422 | | { |
| | | 423 | | continue; |
| | | 424 | | } |
| | | 425 | | if (value is string s && s.Length == 0) |
| | | 426 | | { |
| | | 427 | | continue; |
| | | 428 | | } |
| | | 429 | | if (value is System.Collections.ICollection c && c.Count == 0) |
| | | 430 | | { |
| | | 431 | | continue; |
| | | 432 | | } |
| | | 433 | | result[PascalToCamelCase(prop.Name)] = value; |
| | | 434 | | } |
| | | 435 | | return result; |
| | | 436 | | } |
| | | 437 | | |
| | | 438 | | private static string PascalToCamelCase(string str) |
| | | 439 | | { |
| | | 440 | | return char.ToLowerInvariant(str[0]) + str.Substring(1); |
| | | 441 | | } |
| | | 442 | | |
| | | 443 | | private static long ToUnixSeconds(DateTime dateTime) |
| | | 444 | | { |
| | | 445 | | return (long) |
| | | 446 | | Math.Floor( |
| | | 447 | | dateTime |
| | | 448 | | .ToUniversalTime() |
| | | 449 | | .Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)) |
| | | 450 | | .TotalSeconds |
| | | 451 | | ); |
| | | 452 | | } |
| | | 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 |
| | 29 | 471 | | public TokenVerifier(string apiKey = null, string apiSecret = null, TimeSpan? leeway = null) |
| | 29 | 472 | | { |
| | 29 | 473 | | this.apiKey = apiKey ?? Environment.GetEnvironmentVariable("LIVEKIT_API_KEY"); |
| | 29 | 474 | | this.apiSecret = apiSecret ?? Environment.GetEnvironmentVariable("LIVEKIT_API_SECRET"); |
| | 29 | 475 | | this.leeway = leeway ?? Constants.DefaultLeeway; |
| | | 476 | | |
| | 29 | 477 | | if (string.IsNullOrEmpty(this.apiKey) || string.IsNullOrEmpty(this.apiSecret)) |
| | 1 | 478 | | { |
| | 1 | 479 | | throw new ArgumentException("apiKey and apiSecret must be set"); |
| | | 480 | | } |
| | 28 | 481 | | if (Encoding.UTF8.GetBytes(this.apiSecret).Length < 32) |
| | 2 | 482 | | { |
| | 2 | 483 | | throw new ArgumentException( |
| | 2 | 484 | | "apiSecret must be at least 256 bits long. Currently it is " |
| | 2 | 485 | | + Encoding.UTF8.GetBytes(this.apiSecret).Length * 8 |
| | 2 | 486 | | + " bits long" |
| | 2 | 487 | | ); |
| | | 488 | | } |
| | 26 | 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) |
| | 25 | 499 | | { |
| | 25 | 500 | | var validationParameters = new TokenValidationParameters |
| | 25 | 501 | | { |
| | 25 | 502 | | ValidateIssuer = true, |
| | 25 | 503 | | ValidateIssuerSigningKey = true, |
| | 25 | 504 | | ValidIssuer = apiKey, |
| | 25 | 505 | | IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(apiSecret)), |
| | 25 | 506 | | ValidateLifetime = true, |
| | 25 | 507 | | ValidateAudience = false, |
| | 25 | 508 | | ClockSkew = leeway, |
| | 25 | 509 | | // LiveKit tokens are always HS256 (the Python SDK pins the algorithm too) |
| | 25 | 510 | | ValidAlgorithms = new[] { SecurityAlgorithms.HmacSha256 }, |
| | 25 | 511 | | }; |
| | | 512 | | |
| | 25 | 513 | | var tokenHandler = new JwtSecurityTokenHandler(); |
| | 25 | 514 | | var principal = tokenHandler.ValidateToken( |
| | 25 | 515 | | token, |
| | 25 | 516 | | validationParameters, |
| | 25 | 517 | | out var securityToken |
| | 25 | 518 | | ); |
| | | 519 | | // A JSON array claim yields one Claim per element: keep the first instead of throwing |
| | 20 | 520 | | var claims = principal |
| | 179 | 521 | | .Claims.GroupBy(claim => claim.Type) |
| | 376 | 522 | | .ToDictionary(group => group.Key, group => group.First().Value); |
| | 20 | 523 | | var decodedSecurityToken = (JwtSecurityToken)securityToken; |
| | | 524 | | |
| | 20 | 525 | | var video = new VideoGrants(); |
| | 20 | 526 | | var exists = claims.TryGetValue("video", out var videoClaim); |
| | 20 | 527 | | if (exists && videoClaim != null) |
| | 18 | 528 | | { |
| | 18 | 529 | | video = JsonConvert.DeserializeObject<VideoGrants>(videoClaim); |
| | 18 | 530 | | } |
| | | 531 | | |
| | 20 | 532 | | var sip = claims.TryGetValue("sip", out var sipClaim) |
| | 20 | 533 | | ? JsonConvert.DeserializeObject<SIPGrants>(sipClaim) |
| | 20 | 534 | | : new SIPGrants(); |
| | | 535 | | |
| | 20 | 536 | | var inference = claims.TryGetValue("inference", out var inferenceClaim) |
| | 20 | 537 | | ? JsonConvert.DeserializeObject<InferenceGrants>(inferenceClaim) |
| | 20 | 538 | | : null; |
| | 20 | 539 | | var observability = claims.TryGetValue("observability", out var observabilityClaim) |
| | 20 | 540 | | ? JsonConvert.DeserializeObject<ObservabilityGrants>(observabilityClaim) |
| | 20 | 541 | | : null; |
| | | 542 | | |
| | 20 | 543 | | var claimsModel = new ClaimsModel |
| | 20 | 544 | | { |
| | 20 | 545 | | Identity = decodedSecurityToken.Subject != null ? decodedSecurityToken.Subject : "", |
| | 20 | 546 | | Name = claims.TryGetValue("name", out var name) ? name : "", |
| | 20 | 547 | | Video = video, |
| | 20 | 548 | | Sip = sip, |
| | 20 | 549 | | Inference = inference, |
| | 20 | 550 | | Observability = observability, |
| | 20 | 551 | | Metadata = claims.TryGetValue("metadata", out var metadata) ? metadata : "", |
| | 20 | 552 | | Sha256 = claims.TryGetValue("sha256", out var sha256) ? sha256 : "", |
| | 20 | 553 | | Kind = claims.TryGetValue("kind", out var kind) ? kind : "", |
| | 20 | 554 | | Attributes = JsonConvert.DeserializeObject<Dictionary<string, string>>( |
| | 20 | 555 | | claims.TryGetValue("attributes", out var attributes) ? attributes : "{}" |
| | 20 | 556 | | ), |
| | 20 | 557 | | }; |
| | | 558 | | |
| | 20 | 559 | | if (claims.TryGetValue("roomPreset", out var roomPreset)) |
| | 1 | 560 | | { |
| | 1 | 561 | | claimsModel.RoomPreset = roomPreset; |
| | 1 | 562 | | } |
| | 20 | 563 | | if (claims.TryGetValue("roomConfig", out var roomConfig)) |
| | 3 | 564 | | { |
| | | 565 | | // Written with the protobuf JSON formatter (enum names, oneofs...): read it back |
| | | 566 | | // with the protobuf JSON parser, not with Newtonsoft |
| | 3 | 567 | | claimsModel.RoomConfig = new JsonParser( |
| | 3 | 568 | | JsonParser.Settings.Default.WithIgnoreUnknownFields(true) |
| | 3 | 569 | | ).Parse<RoomConfiguration>(roomConfig); |
| | 3 | 570 | | } |
| | | 571 | | |
| | 20 | 572 | | return claimsModel; |
| | 20 | 573 | | } |
| | | 574 | | } |
| | | 575 | | } |