ApiServiceCollectionExtensions.cs 9.5 KB

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