ApiServiceCollectionExtensions.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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.Configuration;
  19. using Jellyfin.Server.Filters;
  20. using Jellyfin.Server.Formatters;
  21. using MediaBrowser.Common.Json;
  22. using MediaBrowser.Model.Entities;
  23. using Microsoft.AspNetCore.Authentication;
  24. using Microsoft.AspNetCore.Authorization;
  25. using Microsoft.AspNetCore.Builder;
  26. using Microsoft.AspNetCore.Cors.Infrastructure;
  27. using Microsoft.AspNetCore.HttpOverrides;
  28. using Microsoft.Extensions.DependencyInjection;
  29. using Microsoft.OpenApi.Models;
  30. using Swashbuckle.AspNetCore.SwaggerGen;
  31. namespace Jellyfin.Server.Extensions
  32. {
  33. /// <summary>
  34. /// API specific extensions for the service collection.
  35. /// </summary>
  36. public static class ApiServiceCollectionExtensions
  37. {
  38. /// <summary>
  39. /// Adds jellyfin API authorization policies to the DI container.
  40. /// </summary>
  41. /// <param name="serviceCollection">The service collection.</param>
  42. /// <returns>The updated service collection.</returns>
  43. public static IServiceCollection AddJellyfinApiAuthorization(this IServiceCollection serviceCollection)
  44. {
  45. serviceCollection.AddSingleton<IAuthorizationHandler, DefaultAuthorizationHandler>();
  46. serviceCollection.AddSingleton<IAuthorizationHandler, DownloadHandler>();
  47. serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeSetupOrDefaultHandler>();
  48. serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeSetupOrElevatedHandler>();
  49. serviceCollection.AddSingleton<IAuthorizationHandler, IgnoreParentalControlHandler>();
  50. serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeOrIgnoreParentalControlSetupHandler>();
  51. serviceCollection.AddSingleton<IAuthorizationHandler, LocalAccessHandler>();
  52. serviceCollection.AddSingleton<IAuthorizationHandler, LocalAccessOrRequiresElevationHandler>();
  53. serviceCollection.AddSingleton<IAuthorizationHandler, RequiresElevationHandler>();
  54. return serviceCollection.AddAuthorizationCore(options =>
  55. {
  56. options.AddPolicy(
  57. Policies.DefaultAuthorization,
  58. policy =>
  59. {
  60. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  61. policy.AddRequirements(new DefaultAuthorizationRequirement());
  62. });
  63. options.AddPolicy(
  64. Policies.Download,
  65. policy =>
  66. {
  67. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  68. policy.AddRequirements(new DownloadRequirement());
  69. });
  70. options.AddPolicy(
  71. Policies.FirstTimeSetupOrDefault,
  72. policy =>
  73. {
  74. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  75. policy.AddRequirements(new FirstTimeSetupOrDefaultRequirement());
  76. });
  77. options.AddPolicy(
  78. Policies.FirstTimeSetupOrElevated,
  79. policy =>
  80. {
  81. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  82. policy.AddRequirements(new FirstTimeSetupOrElevatedRequirement());
  83. });
  84. options.AddPolicy(
  85. Policies.IgnoreParentalControl,
  86. policy =>
  87. {
  88. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  89. policy.AddRequirements(new IgnoreParentalControlRequirement());
  90. });
  91. options.AddPolicy(
  92. Policies.FirstTimeSetupOrIgnoreParentalControl,
  93. policy =>
  94. {
  95. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  96. policy.AddRequirements(new FirstTimeOrIgnoreParentalControlSetupRequirement());
  97. });
  98. options.AddPolicy(
  99. Policies.LocalAccessOnly,
  100. policy =>
  101. {
  102. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  103. policy.AddRequirements(new LocalAccessRequirement());
  104. });
  105. options.AddPolicy(
  106. Policies.LocalAccessOrRequiresElevation,
  107. policy =>
  108. {
  109. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  110. policy.AddRequirements(new LocalAccessOrRequiresElevationRequirement());
  111. });
  112. options.AddPolicy(
  113. Policies.RequiresElevation,
  114. policy =>
  115. {
  116. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  117. policy.AddRequirements(new RequiresElevationRequirement());
  118. });
  119. });
  120. }
  121. /// <summary>
  122. /// Adds custom legacy authentication to the service collection.
  123. /// </summary>
  124. /// <param name="serviceCollection">The service collection.</param>
  125. /// <returns>The updated service collection.</returns>
  126. public static AuthenticationBuilder AddCustomAuthentication(this IServiceCollection serviceCollection)
  127. {
  128. return serviceCollection.AddAuthentication(AuthenticationSchemes.CustomAuthentication)
  129. .AddScheme<AuthenticationSchemeOptions, CustomAuthenticationHandler>(AuthenticationSchemes.CustomAuthentication, null);
  130. }
  131. /// <summary>
  132. /// Extension method for adding the jellyfin API to the service collection.
  133. /// </summary>
  134. /// <param name="serviceCollection">The service collection.</param>
  135. /// <param name="pluginAssemblies">An IEnumerable containing all plugin assemblies with API controllers.</param>
  136. /// <returns>The MVC builder.</returns>
  137. public static IMvcBuilder AddJellyfinApi(this IServiceCollection serviceCollection, IEnumerable<Assembly> pluginAssemblies)
  138. {
  139. IMvcBuilder mvcBuilder = serviceCollection
  140. .AddCors()
  141. .AddTransient<ICorsPolicyProvider, CorsPolicyProvider>()
  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. c.OperationFilter<FileResponseFilter>();
  233. });
  234. }
  235. private static void AddSwaggerTypeMappings(this SwaggerGenOptions options)
  236. {
  237. /*
  238. * TODO remove when System.Text.Json supports non-string keys.
  239. * Used in Jellyfin.Api.Controller.GetChannels.
  240. */
  241. options.MapType<Dictionary<ImageType, string>>(() =>
  242. new OpenApiSchema
  243. {
  244. Type = "object",
  245. Properties = typeof(ImageType).GetEnumNames().ToDictionary(
  246. name => name,
  247. name => new OpenApiSchema
  248. {
  249. Type = "string",
  250. Format = "string"
  251. })
  252. });
  253. /*
  254. * Support BlurHash dictionary
  255. */
  256. options.MapType<Dictionary<ImageType, Dictionary<string, string>>>(() =>
  257. new OpenApiSchema
  258. {
  259. Type = "object",
  260. Properties = typeof(ImageType).GetEnumNames().ToDictionary(
  261. name => name,
  262. name => new OpenApiSchema
  263. {
  264. Type = "object", Properties = new Dictionary<string, OpenApiSchema>
  265. {
  266. {
  267. "string",
  268. new OpenApiSchema
  269. {
  270. Type = "string",
  271. Format = "string"
  272. }
  273. }
  274. }
  275. })
  276. });
  277. }
  278. }
  279. }