ApiServiceCollectionExtensions.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using Jellyfin.Api;
  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.Filters;
  20. using Jellyfin.Server.Formatters;
  21. using Jellyfin.Server.Models;
  22. using MediaBrowser.Common;
  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.HttpOverrides;
  29. using Microsoft.Extensions.DependencyInjection;
  30. using Microsoft.OpenApi.Models;
  31. using Swashbuckle.AspNetCore.SwaggerGen;
  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="baseUrl">The base url for the API.</param>
  137. /// <param name="pluginAssemblies">An IEnumberable containing all plugin assemblies with API controllers.</param>
  138. /// <returns>The MVC builder.</returns>
  139. public static IMvcBuilder AddJellyfinApi(this IServiceCollection serviceCollection, string baseUrl, IEnumerable<Assembly> pluginAssemblies)
  140. {
  141. IMvcBuilder mvcBuilder = serviceCollection
  142. .AddCors(options =>
  143. {
  144. options.AddPolicy(ServerCorsPolicy.DefaultPolicyName, ServerCorsPolicy.DefaultPolicy);
  145. })
  146. .Configure<ForwardedHeadersOptions>(options =>
  147. {
  148. options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
  149. })
  150. .AddMvc(opts =>
  151. {
  152. opts.UseGeneralRoutePrefix(baseUrl);
  153. opts.OutputFormatters.Insert(0, new CamelCaseJsonProfileFormatter());
  154. opts.OutputFormatters.Insert(0, new PascalCaseJsonProfileFormatter());
  155. opts.OutputFormatters.Add(new CssOutputFormatter());
  156. opts.OutputFormatters.Add(new XmlOutputFormatter());
  157. })
  158. // Clear app parts to avoid other assemblies being picked up
  159. .ConfigureApplicationPartManager(a => a.ApplicationParts.Clear())
  160. .AddApplicationPart(typeof(StartupController).Assembly)
  161. .AddJsonOptions(options =>
  162. {
  163. // Update all properties that are set in JsonDefaults
  164. var jsonOptions = JsonDefaults.GetPascalCaseOptions();
  165. // From JsonDefaults
  166. options.JsonSerializerOptions.ReadCommentHandling = jsonOptions.ReadCommentHandling;
  167. options.JsonSerializerOptions.WriteIndented = jsonOptions.WriteIndented;
  168. options.JsonSerializerOptions.DefaultIgnoreCondition = jsonOptions.DefaultIgnoreCondition;
  169. options.JsonSerializerOptions.NumberHandling = jsonOptions.NumberHandling;
  170. options.JsonSerializerOptions.Converters.Clear();
  171. foreach (var converter in jsonOptions.Converters)
  172. {
  173. options.JsonSerializerOptions.Converters.Add(converter);
  174. }
  175. // From JsonDefaults.PascalCase
  176. options.JsonSerializerOptions.PropertyNamingPolicy = jsonOptions.PropertyNamingPolicy;
  177. });
  178. foreach (Assembly pluginAssembly in pluginAssemblies)
  179. {
  180. mvcBuilder.AddApplicationPart(pluginAssembly);
  181. }
  182. return mvcBuilder.AddControllersAsServices();
  183. }
  184. /// <summary>
  185. /// Adds Swagger to the service collection.
  186. /// </summary>
  187. /// <param name="serviceCollection">The service collection.</param>
  188. /// <returns>The updated service collection.</returns>
  189. public static IServiceCollection AddJellyfinApiSwagger(this IServiceCollection serviceCollection)
  190. {
  191. return serviceCollection.AddSwaggerGen(c =>
  192. {
  193. c.SwaggerDoc("api-docs", new OpenApiInfo { Title = "Jellyfin API", Version = "v1" });
  194. c.AddSecurityDefinition(AuthenticationSchemes.CustomAuthentication, new OpenApiSecurityScheme
  195. {
  196. Type = SecuritySchemeType.ApiKey,
  197. In = ParameterLocation.Header,
  198. Name = "X-Emby-Authorization",
  199. Description = "API key header parameter"
  200. });
  201. var securitySchemeRef = new OpenApiSecurityScheme
  202. {
  203. Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = AuthenticationSchemes.CustomAuthentication },
  204. };
  205. // TODO: Apply this with an operation filter instead of globally
  206. // https://github.com/domaindrivendev/Swashbuckle.AspNetCore#add-security-definitions-and-requirements
  207. c.AddSecurityRequirement(new OpenApiSecurityRequirement
  208. {
  209. { securitySchemeRef, Array.Empty<string>() }
  210. });
  211. // Add all xml doc files to swagger generator.
  212. var xmlFiles = Directory.GetFiles(
  213. AppContext.BaseDirectory,
  214. "*.xml",
  215. SearchOption.TopDirectoryOnly);
  216. foreach (var xmlFile in xmlFiles)
  217. {
  218. c.IncludeXmlComments(xmlFile);
  219. }
  220. // Order actions by route path, then by http method.
  221. c.OrderActionsBy(description =>
  222. $"{description.ActionDescriptor.RouteValues["controller"]}_{description.RelativePath}");
  223. // Use method name as operationId
  224. c.CustomOperationIds(
  225. description =>
  226. {
  227. description.TryGetMethodInfo(out MethodInfo methodInfo);
  228. // Attribute name, method name, none.
  229. return description?.ActionDescriptor?.AttributeRouteInfo?.Name
  230. ?? methodInfo?.Name
  231. ?? null;
  232. });
  233. // TODO - remove when all types are supported in System.Text.Json
  234. c.AddSwaggerTypeMappings();
  235. c.OperationFilter<FileResponseFilter>();
  236. });
  237. }
  238. private static void AddSwaggerTypeMappings(this SwaggerGenOptions options)
  239. {
  240. /*
  241. * TODO remove when System.Text.Json supports non-string keys.
  242. * Used in Jellyfin.Api.Controller.GetChannels.
  243. */
  244. options.MapType<Dictionary<ImageType, string>>(() =>
  245. new OpenApiSchema
  246. {
  247. Type = "object",
  248. Properties = typeof(ImageType).GetEnumNames().ToDictionary(
  249. name => name,
  250. name => new OpenApiSchema
  251. {
  252. Type = "string",
  253. Format = "string"
  254. })
  255. });
  256. /*
  257. * Support BlurHash dictionary
  258. */
  259. options.MapType<Dictionary<ImageType, Dictionary<string, string>>>(() =>
  260. new OpenApiSchema
  261. {
  262. Type = "object",
  263. Properties = typeof(ImageType).GetEnumNames().ToDictionary(
  264. name => name,
  265. name => new OpenApiSchema
  266. {
  267. Type = "object", Properties = new Dictionary<string, OpenApiSchema>
  268. {
  269. {
  270. "string",
  271. new OpenApiSchema
  272. {
  273. Type = "string",
  274. Format = "string"
  275. }
  276. }
  277. }
  278. })
  279. });
  280. }
  281. }
  282. }