ApiServiceCollectionExtensions.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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. // Add all xml doc files to swagger generator.
  116. var xmlFiles = Directory.GetFiles(
  117. AppContext.BaseDirectory,
  118. "*.xml",
  119. SearchOption.TopDirectoryOnly);
  120. foreach (var xmlFile in xmlFiles)
  121. {
  122. c.IncludeXmlComments(xmlFile);
  123. }
  124. // Order actions by route path, then by http method.
  125. c.OrderActionsBy(description =>
  126. $"{description.ActionDescriptor.RouteValues["controller"]}_{description.HttpMethod}");
  127. // Use method name as operationId
  128. c.CustomOperationIds(description =>
  129. description.TryGetMethodInfo(out MethodInfo methodInfo) ? methodInfo.Name : null);
  130. // TODO - remove when all types are supported in System.Text.Json
  131. c.AddSwaggerTypeMappings();
  132. });
  133. }
  134. private static void AddSwaggerTypeMappings(this SwaggerGenOptions options)
  135. {
  136. /*
  137. * TODO remove when System.Text.Json supports non-string keys.
  138. * Used in Jellyfin.Api.Controller.GetChannels.
  139. */
  140. options.MapType<Dictionary<ImageType, string>>(() =>
  141. new OpenApiSchema
  142. {
  143. Type = "object",
  144. Properties = typeof(ImageType).GetEnumNames().ToDictionary(
  145. name => name,
  146. name => new OpenApiSchema
  147. {
  148. Type = "string",
  149. Format = "string"
  150. })
  151. });
  152. }
  153. }
  154. }