ApiServiceCollectionExtensions.cs 13 KB

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