ApiServiceCollectionExtensions.cs 14 KB

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