ApiServiceCollectionExtensions.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using Jellyfin.Api;
  7. using Jellyfin.Api.Auth;
  8. using Jellyfin.Api.Auth.FirstTimeSetupOrElevatedPolicy;
  9. using Jellyfin.Api.Auth.RequiresElevationPolicy;
  10. using Jellyfin.Api.Constants;
  11. using Jellyfin.Api.Controllers;
  12. using Jellyfin.Server.Formatters;
  13. using Jellyfin.Server.Models;
  14. using MediaBrowser.Common.Json;
  15. using MediaBrowser.Model.Entities;
  16. using Microsoft.AspNetCore.Authentication;
  17. using Microsoft.AspNetCore.Authorization;
  18. using Microsoft.Extensions.DependencyInjection;
  19. using Microsoft.OpenApi.Models;
  20. using Swashbuckle.AspNetCore.SwaggerGen;
  21. namespace Jellyfin.Server.Extensions
  22. {
  23. /// <summary>
  24. /// API specific extensions for the service collection.
  25. /// </summary>
  26. public static class ApiServiceCollectionExtensions
  27. {
  28. /// <summary>
  29. /// Adds jellyfin API authorization policies to the DI container.
  30. /// </summary>
  31. /// <param name="serviceCollection">The service collection.</param>
  32. /// <returns>The updated service collection.</returns>
  33. public static IServiceCollection AddJellyfinApiAuthorization(this IServiceCollection serviceCollection)
  34. {
  35. serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeSetupOrElevatedHandler>();
  36. serviceCollection.AddSingleton<IAuthorizationHandler, RequiresElevationHandler>();
  37. return serviceCollection.AddAuthorizationCore(options =>
  38. {
  39. options.AddPolicy(
  40. Policies.RequiresElevation,
  41. policy =>
  42. {
  43. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  44. policy.AddRequirements(new RequiresElevationRequirement());
  45. });
  46. options.AddPolicy(
  47. Policies.FirstTimeSetupOrElevated,
  48. policy =>
  49. {
  50. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  51. policy.AddRequirements(new FirstTimeSetupOrElevatedRequirement());
  52. });
  53. });
  54. }
  55. /// <summary>
  56. /// Adds custom legacy authentication to the service collection.
  57. /// </summary>
  58. /// <param name="serviceCollection">The service collection.</param>
  59. /// <returns>The updated service collection.</returns>
  60. public static AuthenticationBuilder AddCustomAuthentication(this IServiceCollection serviceCollection)
  61. {
  62. return serviceCollection.AddAuthentication(AuthenticationSchemes.CustomAuthentication)
  63. .AddScheme<AuthenticationSchemeOptions, CustomAuthenticationHandler>(AuthenticationSchemes.CustomAuthentication, null);
  64. }
  65. /// <summary>
  66. /// Extension method for adding the jellyfin API to the service collection.
  67. /// </summary>
  68. /// <param name="serviceCollection">The service collection.</param>
  69. /// <param name="baseUrl">The base url for the API.</param>
  70. /// <returns>The MVC builder.</returns>
  71. public static IMvcBuilder AddJellyfinApi(this IServiceCollection serviceCollection, string baseUrl)
  72. {
  73. return serviceCollection
  74. .AddCors(options =>
  75. {
  76. options.AddPolicy(ServerCorsPolicy.DefaultPolicyName, ServerCorsPolicy.DefaultPolicy);
  77. })
  78. .AddMvc(opts =>
  79. {
  80. opts.UseGeneralRoutePrefix(baseUrl);
  81. opts.OutputFormatters.Insert(0, new CamelCaseJsonProfileFormatter());
  82. opts.OutputFormatters.Insert(0, new PascalCaseJsonProfileFormatter());
  83. opts.OutputFormatters.Add(new CssOutputFormatter());
  84. })
  85. // Clear app parts to avoid other assemblies being picked up
  86. .ConfigureApplicationPartManager(a => a.ApplicationParts.Clear())
  87. .AddApplicationPart(typeof(StartupController).Assembly)
  88. .AddJsonOptions(options =>
  89. {
  90. // Update all properties that are set in JsonDefaults
  91. var jsonOptions = JsonDefaults.PascalCase;
  92. // From JsonDefaults
  93. options.JsonSerializerOptions.ReadCommentHandling = jsonOptions.ReadCommentHandling;
  94. options.JsonSerializerOptions.WriteIndented = jsonOptions.WriteIndented;
  95. options.JsonSerializerOptions.Converters.Clear();
  96. foreach (var converter in jsonOptions.Converters)
  97. {
  98. options.JsonSerializerOptions.Converters.Add(converter);
  99. }
  100. // From JsonDefaults.PascalCase
  101. options.JsonSerializerOptions.PropertyNamingPolicy = jsonOptions.PropertyNamingPolicy;
  102. })
  103. .AddControllersAsServices();
  104. }
  105. /// <summary>
  106. /// Adds Swagger to the service collection.
  107. /// </summary>
  108. /// <param name="serviceCollection">The service collection.</param>
  109. /// <returns>The updated service collection.</returns>
  110. public static IServiceCollection AddJellyfinApiSwagger(this IServiceCollection serviceCollection)
  111. {
  112. return serviceCollection.AddSwaggerGen(c =>
  113. {
  114. c.SwaggerDoc("api-docs", new OpenApiInfo { Title = "Jellyfin API", Version = "v1" });
  115. c.AddSecurityDefinition(AuthenticationSchemes.CustomAuthentication, new OpenApiSecurityScheme
  116. {
  117. Type = SecuritySchemeType.ApiKey,
  118. In = ParameterLocation.Header,
  119. Name = "X-Emby-Token",
  120. Description = "API key header parameter"
  121. });
  122. var securitySchemeRef = new OpenApiSecurityScheme
  123. {
  124. Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = AuthenticationSchemes.CustomAuthentication },
  125. };
  126. // TODO: Apply this with an operation filter instead of globally
  127. // https://github.com/domaindrivendev/Swashbuckle.AspNetCore#add-security-definitions-and-requirements
  128. c.AddSecurityRequirement(new OpenApiSecurityRequirement
  129. {
  130. { securitySchemeRef, Array.Empty<string>() }
  131. });
  132. // Add all xml doc files to swagger generator.
  133. var xmlFiles = Directory.GetFiles(
  134. AppContext.BaseDirectory,
  135. "*.xml",
  136. SearchOption.TopDirectoryOnly);
  137. foreach (var xmlFile in xmlFiles)
  138. {
  139. c.IncludeXmlComments(xmlFile);
  140. }
  141. // Order actions by route path, then by http method.
  142. c.OrderActionsBy(description =>
  143. $"{description.ActionDescriptor.RouteValues["controller"]}_{description.HttpMethod}");
  144. // Use method name as operationId
  145. c.CustomOperationIds(description =>
  146. description.TryGetMethodInfo(out MethodInfo methodInfo) ? methodInfo.Name : null);
  147. // TODO - remove when all types are supported in System.Text.Json
  148. c.AddSwaggerTypeMappings();
  149. });
  150. }
  151. private static void AddSwaggerTypeMappings(this SwaggerGenOptions options)
  152. {
  153. /*
  154. * TODO remove when System.Text.Json supports non-string keys.
  155. * Used in Jellyfin.Api.Controller.GetChannels.
  156. */
  157. options.MapType<Dictionary<ImageType, string>>(() =>
  158. new OpenApiSchema
  159. {
  160. Type = "object",
  161. Properties = typeof(ImageType).GetEnumNames().ToDictionary(
  162. name => name,
  163. name => new OpenApiSchema
  164. {
  165. Type = "string",
  166. Format = "string"
  167. })
  168. });
  169. }
  170. }
  171. }