ApiServiceCollectionExtensions.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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. opts.OutputFormatters.Add(new CssOutputFormatter());
  78. })
  79. // Clear app parts to avoid other assemblies being picked up
  80. .ConfigureApplicationPartManager(a => a.ApplicationParts.Clear())
  81. .AddApplicationPart(typeof(StartupController).Assembly)
  82. .AddJsonOptions(options =>
  83. {
  84. // Update all properties that are set in JsonDefaults
  85. var jsonOptions = JsonDefaults.PascalCase;
  86. // From JsonDefaults
  87. options.JsonSerializerOptions.ReadCommentHandling = jsonOptions.ReadCommentHandling;
  88. options.JsonSerializerOptions.WriteIndented = jsonOptions.WriteIndented;
  89. options.JsonSerializerOptions.Converters.Clear();
  90. foreach (var converter in jsonOptions.Converters)
  91. {
  92. options.JsonSerializerOptions.Converters.Add(converter);
  93. }
  94. // From JsonDefaults.PascalCase
  95. options.JsonSerializerOptions.PropertyNamingPolicy = jsonOptions.PropertyNamingPolicy;
  96. })
  97. .AddControllersAsServices();
  98. }
  99. /// <summary>
  100. /// Adds Swagger to the service collection.
  101. /// </summary>
  102. /// <param name="serviceCollection">The service collection.</param>
  103. /// <returns>The updated service collection.</returns>
  104. public static IServiceCollection AddJellyfinApiSwagger(this IServiceCollection serviceCollection)
  105. {
  106. return serviceCollection.AddSwaggerGen(c =>
  107. {
  108. c.SwaggerDoc("api-docs", new OpenApiInfo { Title = "Jellyfin API", Version = "v1" });
  109. // Add all xml doc files to swagger generator.
  110. var xmlFiles = Directory.GetFiles(
  111. AppContext.BaseDirectory,
  112. "*.xml",
  113. SearchOption.TopDirectoryOnly);
  114. foreach (var xmlFile in xmlFiles)
  115. {
  116. c.IncludeXmlComments(xmlFile);
  117. }
  118. // Order actions by route path, then by http method.
  119. c.OrderActionsBy(description =>
  120. $"{description.ActionDescriptor.RouteValues["controller"]}_{description.HttpMethod}");
  121. // Use method name as operationId
  122. c.CustomOperationIds(description =>
  123. description.TryGetMethodInfo(out MethodInfo methodInfo) ? methodInfo.Name : null);
  124. // TODO - remove when all types are supported in System.Text.Json
  125. c.AddSwaggerTypeMappings();
  126. });
  127. }
  128. private static void AddSwaggerTypeMappings(this SwaggerGenOptions options)
  129. {
  130. /*
  131. * TODO remove when System.Text.Json supports non-string keys.
  132. * Used in Jellyfin.Api.Controller.GetChannels.
  133. */
  134. options.MapType<Dictionary<ImageType, string>>(() =>
  135. new OpenApiSchema
  136. {
  137. Type = "object",
  138. Properties = typeof(ImageType).GetEnumNames().ToDictionary(
  139. name => name,
  140. name => new OpenApiSchema
  141. {
  142. Type = "string",
  143. Format = "string"
  144. })
  145. });
  146. }
  147. }
  148. }