ApiServiceCollectionExtensions.cs 15 KB

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