ApiServiceCollectionExtensions.cs 10 KB

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