ApiServiceCollectionExtensions.cs 15 KB

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