ApiServiceCollectionExtensions.cs 14 KB

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