ApiServiceCollectionExtensions.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using Jellyfin.Api.Auth;
  7. using Jellyfin.Api.Auth.DefaultAuthorizationPolicy;
  8. using Jellyfin.Api.Auth.DownloadPolicy;
  9. using Jellyfin.Api.Auth.FirstTimeOrIgnoreParentalControlSetupPolicy;
  10. using Jellyfin.Api.Auth.FirstTimeSetupOrDefaultPolicy;
  11. using Jellyfin.Api.Auth.FirstTimeSetupOrElevatedPolicy;
  12. using Jellyfin.Api.Auth.IgnoreParentalControlPolicy;
  13. using Jellyfin.Api.Auth.LocalAccessOrRequiresElevationPolicy;
  14. using Jellyfin.Api.Auth.LocalAccessPolicy;
  15. using Jellyfin.Api.Auth.RequiresElevationPolicy;
  16. using Jellyfin.Api.Constants;
  17. using Jellyfin.Api.Controllers;
  18. using Jellyfin.Server.Formatters;
  19. using Jellyfin.Server.Models;
  20. using MediaBrowser.Common.Json;
  21. using MediaBrowser.Model.Entities;
  22. using Microsoft.AspNetCore.Authentication;
  23. using Microsoft.AspNetCore.Authorization;
  24. using Microsoft.AspNetCore.Builder;
  25. using Microsoft.AspNetCore.HttpOverrides;
  26. using Microsoft.Extensions.DependencyInjection;
  27. using Microsoft.OpenApi.Models;
  28. using Swashbuckle.AspNetCore.SwaggerGen;
  29. namespace Jellyfin.Server.Extensions
  30. {
  31. /// <summary>
  32. /// API specific extensions for the service collection.
  33. /// </summary>
  34. public static class ApiServiceCollectionExtensions
  35. {
  36. /// <summary>
  37. /// Adds jellyfin API authorization policies to the DI container.
  38. /// </summary>
  39. /// <param name="serviceCollection">The service collection.</param>
  40. /// <returns>The updated service collection.</returns>
  41. public static IServiceCollection AddJellyfinApiAuthorization(this IServiceCollection serviceCollection)
  42. {
  43. serviceCollection.AddSingleton<IAuthorizationHandler, DefaultAuthorizationHandler>();
  44. serviceCollection.AddSingleton<IAuthorizationHandler, DownloadHandler>();
  45. serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeSetupOrDefaultHandler>();
  46. serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeSetupOrElevatedHandler>();
  47. serviceCollection.AddSingleton<IAuthorizationHandler, IgnoreParentalControlHandler>();
  48. serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeOrIgnoreParentalControlSetupHandler>();
  49. serviceCollection.AddSingleton<IAuthorizationHandler, LocalAccessHandler>();
  50. serviceCollection.AddSingleton<IAuthorizationHandler, LocalAccessOrRequiresElevationHandler>();
  51. serviceCollection.AddSingleton<IAuthorizationHandler, RequiresElevationHandler>();
  52. return serviceCollection.AddAuthorizationCore(options =>
  53. {
  54. options.AddPolicy(
  55. Policies.DefaultAuthorization,
  56. policy =>
  57. {
  58. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  59. policy.AddRequirements(new DefaultAuthorizationRequirement());
  60. });
  61. options.AddPolicy(
  62. Policies.Download,
  63. policy =>
  64. {
  65. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  66. policy.AddRequirements(new DownloadRequirement());
  67. });
  68. options.AddPolicy(
  69. Policies.FirstTimeSetupOrDefault,
  70. policy =>
  71. {
  72. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  73. policy.AddRequirements(new FirstTimeSetupOrDefaultRequirement());
  74. });
  75. options.AddPolicy(
  76. Policies.FirstTimeSetupOrElevated,
  77. policy =>
  78. {
  79. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  80. policy.AddRequirements(new FirstTimeSetupOrElevatedRequirement());
  81. });
  82. options.AddPolicy(
  83. Policies.IgnoreParentalControl,
  84. policy =>
  85. {
  86. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  87. policy.AddRequirements(new IgnoreParentalControlRequirement());
  88. });
  89. options.AddPolicy(
  90. Policies.FirstTimeSetupOrIgnoreParentalControl,
  91. policy =>
  92. {
  93. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  94. policy.AddRequirements(new FirstTimeOrIgnoreParentalControlSetupRequirement());
  95. });
  96. options.AddPolicy(
  97. Policies.LocalAccessOnly,
  98. policy =>
  99. {
  100. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  101. policy.AddRequirements(new LocalAccessRequirement());
  102. });
  103. options.AddPolicy(
  104. Policies.LocalAccessOrRequiresElevation,
  105. policy =>
  106. {
  107. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  108. policy.AddRequirements(new LocalAccessOrRequiresElevationRequirement());
  109. });
  110. options.AddPolicy(
  111. Policies.RequiresElevation,
  112. policy =>
  113. {
  114. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  115. policy.AddRequirements(new RequiresElevationRequirement());
  116. });
  117. });
  118. }
  119. /// <summary>
  120. /// Adds custom legacy authentication to the service collection.
  121. /// </summary>
  122. /// <param name="serviceCollection">The service collection.</param>
  123. /// <returns>The updated service collection.</returns>
  124. public static AuthenticationBuilder AddCustomAuthentication(this IServiceCollection serviceCollection)
  125. {
  126. return serviceCollection.AddAuthentication(AuthenticationSchemes.CustomAuthentication)
  127. .AddScheme<AuthenticationSchemeOptions, CustomAuthenticationHandler>(AuthenticationSchemes.CustomAuthentication, null);
  128. }
  129. /// <summary>
  130. /// Extension method for adding the jellyfin API to the service collection.
  131. /// </summary>
  132. /// <param name="serviceCollection">The service collection.</param>
  133. /// <param name="pluginAssemblies">An IEnumerable containing all plugin assemblies with API controllers.</param>
  134. /// <returns>The MVC builder.</returns>
  135. public static IMvcBuilder AddJellyfinApi(this IServiceCollection serviceCollection, IEnumerable<Assembly> pluginAssemblies)
  136. {
  137. IMvcBuilder mvcBuilder = serviceCollection
  138. .AddCors(options =>
  139. {
  140. options.AddPolicy(ServerCorsPolicy.DefaultPolicyName, ServerCorsPolicy.DefaultPolicy);
  141. })
  142. .Configure<ForwardedHeadersOptions>(options =>
  143. {
  144. options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
  145. })
  146. .AddMvc(opts =>
  147. {
  148. // Allow requester to change between camelCase and PascalCase
  149. opts.RespectBrowserAcceptHeader = true;
  150. opts.OutputFormatters.Insert(0, new CamelCaseJsonProfileFormatter());
  151. opts.OutputFormatters.Insert(0, new PascalCaseJsonProfileFormatter());
  152. opts.OutputFormatters.Add(new CssOutputFormatter());
  153. opts.OutputFormatters.Add(new XmlOutputFormatter());
  154. })
  155. // Clear app parts to avoid other assemblies being picked up
  156. .ConfigureApplicationPartManager(a => a.ApplicationParts.Clear())
  157. .AddApplicationPart(typeof(StartupController).Assembly)
  158. .AddJsonOptions(options =>
  159. {
  160. // Update all properties that are set in JsonDefaults
  161. var jsonOptions = JsonDefaults.GetPascalCaseOptions();
  162. // From JsonDefaults
  163. options.JsonSerializerOptions.ReadCommentHandling = jsonOptions.ReadCommentHandling;
  164. options.JsonSerializerOptions.WriteIndented = jsonOptions.WriteIndented;
  165. options.JsonSerializerOptions.DefaultIgnoreCondition = jsonOptions.DefaultIgnoreCondition;
  166. options.JsonSerializerOptions.NumberHandling = jsonOptions.NumberHandling;
  167. options.JsonSerializerOptions.Converters.Clear();
  168. foreach (var converter in jsonOptions.Converters)
  169. {
  170. options.JsonSerializerOptions.Converters.Add(converter);
  171. }
  172. // From JsonDefaults.PascalCase
  173. options.JsonSerializerOptions.PropertyNamingPolicy = jsonOptions.PropertyNamingPolicy;
  174. });
  175. foreach (Assembly pluginAssembly in pluginAssemblies)
  176. {
  177. mvcBuilder.AddApplicationPart(pluginAssembly);
  178. }
  179. return mvcBuilder.AddControllersAsServices();
  180. }
  181. /// <summary>
  182. /// Adds Swagger to the service collection.
  183. /// </summary>
  184. /// <param name="serviceCollection">The service collection.</param>
  185. /// <returns>The updated service collection.</returns>
  186. public static IServiceCollection AddJellyfinApiSwagger(this IServiceCollection serviceCollection)
  187. {
  188. return serviceCollection.AddSwaggerGen(c =>
  189. {
  190. c.SwaggerDoc("api-docs", new OpenApiInfo { Title = "Jellyfin API", Version = "v1" });
  191. c.AddSecurityDefinition(AuthenticationSchemes.CustomAuthentication, new OpenApiSecurityScheme
  192. {
  193. Type = SecuritySchemeType.ApiKey,
  194. In = ParameterLocation.Header,
  195. Name = "X-Emby-Authorization",
  196. Description = "API key header parameter"
  197. });
  198. var securitySchemeRef = new OpenApiSecurityScheme
  199. {
  200. Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = AuthenticationSchemes.CustomAuthentication },
  201. };
  202. // TODO: Apply this with an operation filter instead of globally
  203. // https://github.com/domaindrivendev/Swashbuckle.AspNetCore#add-security-definitions-and-requirements
  204. c.AddSecurityRequirement(new OpenApiSecurityRequirement
  205. {
  206. { securitySchemeRef, Array.Empty<string>() }
  207. });
  208. // Add all xml doc files to swagger generator.
  209. var xmlFiles = Directory.GetFiles(
  210. AppContext.BaseDirectory,
  211. "*.xml",
  212. SearchOption.TopDirectoryOnly);
  213. foreach (var xmlFile in xmlFiles)
  214. {
  215. c.IncludeXmlComments(xmlFile);
  216. }
  217. // Order actions by route path, then by http method.
  218. c.OrderActionsBy(description =>
  219. $"{description.ActionDescriptor.RouteValues["controller"]}_{description.RelativePath}");
  220. // Use method name as operationId
  221. c.CustomOperationIds(
  222. description =>
  223. {
  224. description.TryGetMethodInfo(out MethodInfo methodInfo);
  225. // Attribute name, method name, none.
  226. return description?.ActionDescriptor?.AttributeRouteInfo?.Name
  227. ?? methodInfo?.Name
  228. ?? null;
  229. });
  230. // TODO - remove when all types are supported in System.Text.Json
  231. c.AddSwaggerTypeMappings();
  232. });
  233. }
  234. private static void AddSwaggerTypeMappings(this SwaggerGenOptions options)
  235. {
  236. /*
  237. * TODO remove when System.Text.Json supports non-string keys.
  238. * Used in Jellyfin.Api.Controller.GetChannels.
  239. */
  240. options.MapType<Dictionary<ImageType, string>>(() =>
  241. new OpenApiSchema
  242. {
  243. Type = "object",
  244. Properties = typeof(ImageType).GetEnumNames().ToDictionary(
  245. name => name,
  246. name => new OpenApiSchema
  247. {
  248. Type = "string",
  249. Format = "string"
  250. })
  251. });
  252. /*
  253. * Support BlurHash dictionary
  254. */
  255. options.MapType<Dictionary<ImageType, Dictionary<string, string>>>(() =>
  256. new OpenApiSchema
  257. {
  258. Type = "object",
  259. Properties = typeof(ImageType).GetEnumNames().ToDictionary(
  260. name => name,
  261. name => new OpenApiSchema
  262. {
  263. Type = "object", Properties = new Dictionary<string, OpenApiSchema>
  264. {
  265. {
  266. "string",
  267. new OpenApiSchema
  268. {
  269. Type = "string",
  270. Format = "string"
  271. }
  272. }
  273. }
  274. })
  275. });
  276. }
  277. }
  278. }