ApiServiceCollectionExtensions.cs 15 KB

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