ApiServiceCollectionExtensions.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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 MediaBrowser.Common.Json;
  14. using MediaBrowser.Model.Entities;
  15. using Microsoft.AspNetCore.Authentication;
  16. using Microsoft.AspNetCore.Authorization;
  17. using Microsoft.Extensions.DependencyInjection;
  18. using Microsoft.OpenApi.Models;
  19. using Swashbuckle.AspNetCore.SwaggerGen;
  20. namespace Jellyfin.Server.Extensions
  21. {
  22. /// <summary>
  23. /// API specific extensions for the service collection.
  24. /// </summary>
  25. public static class ApiServiceCollectionExtensions
  26. {
  27. /// <summary>
  28. /// Adds jellyfin API authorization policies to the DI container.
  29. /// </summary>
  30. /// <param name="serviceCollection">The service collection.</param>
  31. /// <returns>The updated service collection.</returns>
  32. public static IServiceCollection AddJellyfinApiAuthorization(this IServiceCollection serviceCollection)
  33. {
  34. serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeSetupOrElevatedHandler>();
  35. serviceCollection.AddSingleton<IAuthorizationHandler, RequiresElevationHandler>();
  36. return serviceCollection.AddAuthorizationCore(options =>
  37. {
  38. options.AddPolicy(
  39. Policies.RequiresElevation,
  40. policy =>
  41. {
  42. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  43. policy.AddRequirements(new RequiresElevationRequirement());
  44. });
  45. options.AddPolicy(
  46. Policies.FirstTimeSetupOrElevated,
  47. policy =>
  48. {
  49. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  50. policy.AddRequirements(new FirstTimeSetupOrElevatedRequirement());
  51. });
  52. });
  53. }
  54. /// <summary>
  55. /// Adds custom legacy authentication to the service collection.
  56. /// </summary>
  57. /// <param name="serviceCollection">The service collection.</param>
  58. /// <returns>The updated service collection.</returns>
  59. public static AuthenticationBuilder AddCustomAuthentication(this IServiceCollection serviceCollection)
  60. {
  61. return serviceCollection.AddAuthentication(AuthenticationSchemes.CustomAuthentication)
  62. .AddScheme<AuthenticationSchemeOptions, CustomAuthenticationHandler>(AuthenticationSchemes.CustomAuthentication, null);
  63. }
  64. /// <summary>
  65. /// Extension method for adding the jellyfin API to the service collection.
  66. /// </summary>
  67. /// <param name="serviceCollection">The service collection.</param>
  68. /// <param name="baseUrl">The base url for the API.</param>
  69. /// <returns>The MVC builder.</returns>
  70. public static IMvcBuilder AddJellyfinApi(this IServiceCollection serviceCollection, string baseUrl)
  71. {
  72. return serviceCollection.AddMvc(opts =>
  73. {
  74. opts.UseGeneralRoutePrefix(baseUrl);
  75. opts.OutputFormatters.Insert(0, new CamelCaseJsonProfileFormatter());
  76. opts.OutputFormatters.Insert(0, new PascalCaseJsonProfileFormatter());
  77. })
  78. // Clear app parts to avoid other assemblies being picked up
  79. .ConfigureApplicationPartManager(a => a.ApplicationParts.Clear())
  80. .AddApplicationPart(typeof(StartupController).Assembly)
  81. .AddJsonOptions(options =>
  82. {
  83. // Update all properties that are set in JsonDefaults
  84. var jsonOptions = JsonDefaults.PascalCase;
  85. // From JsonDefaults
  86. options.JsonSerializerOptions.ReadCommentHandling = jsonOptions.ReadCommentHandling;
  87. options.JsonSerializerOptions.WriteIndented = jsonOptions.WriteIndented;
  88. options.JsonSerializerOptions.Converters.Clear();
  89. foreach (var converter in jsonOptions.Converters)
  90. {
  91. options.JsonSerializerOptions.Converters.Add(converter);
  92. }
  93. // From JsonDefaults.PascalCase
  94. options.JsonSerializerOptions.PropertyNamingPolicy = jsonOptions.PropertyNamingPolicy;
  95. })
  96. .AddControllersAsServices();
  97. }
  98. /// <summary>
  99. /// Adds Swagger to the service collection.
  100. /// </summary>
  101. /// <param name="serviceCollection">The service collection.</param>
  102. /// <returns>The updated service collection.</returns>
  103. public static IServiceCollection AddJellyfinApiSwagger(this IServiceCollection serviceCollection)
  104. {
  105. return serviceCollection.AddSwaggerGen(c =>
  106. {
  107. c.SwaggerDoc("api-docs", new OpenApiInfo { Title = "Jellyfin API", Version = "v1" });
  108. // Add all xml doc files to swagger generator.
  109. var xmlFiles = Directory.GetFiles(
  110. AppContext.BaseDirectory,
  111. "*.xml",
  112. SearchOption.TopDirectoryOnly);
  113. foreach (var xmlFile in xmlFiles)
  114. {
  115. c.IncludeXmlComments(xmlFile);
  116. }
  117. // Order actions by route path, then by http method.
  118. c.OrderActionsBy(description =>
  119. $"{description.ActionDescriptor.RouteValues["controller"]}_{description.HttpMethod}");
  120. // Use method name as operationId
  121. c.CustomOperationIds(description =>
  122. description.TryGetMethodInfo(out MethodInfo methodInfo) ? methodInfo.Name : null);
  123. // TODO - remove when all types are supported in System.Text.Json
  124. c.AddSwaggerTypeMappings();
  125. });
  126. }
  127. private static void AddSwaggerTypeMappings(this SwaggerGenOptions options)
  128. {
  129. /*
  130. * TODO remove when System.Text.Json supports non-string keys.
  131. * Used in Jellyfin.Api.Controller.GetChannels.
  132. */
  133. options.MapType<Dictionary<ImageType, string>>(() =>
  134. new OpenApiSchema
  135. {
  136. Type = "object",
  137. Properties = typeof(ImageType).GetEnumNames().ToDictionary(
  138. name => name,
  139. name => new OpenApiSchema
  140. {
  141. Type = "string",
  142. Format = "string"
  143. })
  144. });
  145. }
  146. }
  147. }