ApiServiceCollectionExtensions.cs 14 KB

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