ApiServiceCollectionExtensions.cs 15 KB

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