ApiServiceCollectionExtensions.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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.FirstTimeSetupOrDefaultPolicy;
  11. using Jellyfin.Api.Auth.FirstTimeSetupOrElevatedPolicy;
  12. using Jellyfin.Api.Auth.IgnoreParentalControlOrFirstTimeSetupPolicy;
  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, IgnoreParentalControlOrFirstTimeSetupHandler>();
  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.IgnoreParentalControlOrFirstTimeSetup,
  92. policy =>
  93. {
  94. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  95. policy.AddRequirements(new IgnoreParentalControlOrFirstTimeSetupRequirement());
  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. })
  154. // Clear app parts to avoid other assemblies being picked up
  155. .ConfigureApplicationPartManager(a => a.ApplicationParts.Clear())
  156. .AddApplicationPart(typeof(StartupController).Assembly)
  157. .AddJsonOptions(options =>
  158. {
  159. // Update all properties that are set in JsonDefaults
  160. var jsonOptions = JsonDefaults.GetPascalCaseOptions();
  161. // From JsonDefaults
  162. options.JsonSerializerOptions.ReadCommentHandling = jsonOptions.ReadCommentHandling;
  163. options.JsonSerializerOptions.WriteIndented = jsonOptions.WriteIndented;
  164. options.JsonSerializerOptions.Converters.Clear();
  165. foreach (var converter in jsonOptions.Converters)
  166. {
  167. options.JsonSerializerOptions.Converters.Add(converter);
  168. }
  169. // From JsonDefaults.PascalCase
  170. options.JsonSerializerOptions.PropertyNamingPolicy = jsonOptions.PropertyNamingPolicy;
  171. })
  172. .AddControllersAsServices();
  173. }
  174. /// <summary>
  175. /// Adds Swagger to the service collection.
  176. /// </summary>
  177. /// <param name="serviceCollection">The service collection.</param>
  178. /// <returns>The updated service collection.</returns>
  179. public static IServiceCollection AddJellyfinApiSwagger(this IServiceCollection serviceCollection)
  180. {
  181. return serviceCollection.AddSwaggerGen(c =>
  182. {
  183. c.SwaggerDoc("api-docs", new OpenApiInfo { Title = "Jellyfin API", Version = "v1" });
  184. c.AddSecurityDefinition(AuthenticationSchemes.CustomAuthentication, new OpenApiSecurityScheme
  185. {
  186. Type = SecuritySchemeType.ApiKey,
  187. In = ParameterLocation.Header,
  188. Name = "X-Emby-Token",
  189. Description = "API key header parameter"
  190. });
  191. var securitySchemeRef = new OpenApiSecurityScheme
  192. {
  193. Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = AuthenticationSchemes.CustomAuthentication },
  194. };
  195. // TODO: Apply this with an operation filter instead of globally
  196. // https://github.com/domaindrivendev/Swashbuckle.AspNetCore#add-security-definitions-and-requirements
  197. c.AddSecurityRequirement(new OpenApiSecurityRequirement
  198. {
  199. { securitySchemeRef, Array.Empty<string>() }
  200. });
  201. // Add all xml doc files to swagger generator.
  202. var xmlFiles = Directory.GetFiles(
  203. AppContext.BaseDirectory,
  204. "*.xml",
  205. SearchOption.TopDirectoryOnly);
  206. foreach (var xmlFile in xmlFiles)
  207. {
  208. c.IncludeXmlComments(xmlFile);
  209. }
  210. // Order actions by route path, then by http method.
  211. c.OrderActionsBy(description =>
  212. $"{description.ActionDescriptor.RouteValues["controller"]}_{description.RelativePath}");
  213. // Use method name as operationId
  214. c.CustomOperationIds(
  215. description =>
  216. {
  217. description.TryGetMethodInfo(out MethodInfo methodInfo);
  218. // Attribute name, method name, none.
  219. return description?.ActionDescriptor?.AttributeRouteInfo?.Name
  220. ?? methodInfo?.Name
  221. ?? null;
  222. });
  223. // TODO - remove when all types are supported in System.Text.Json
  224. c.AddSwaggerTypeMappings();
  225. });
  226. }
  227. private static void AddSwaggerTypeMappings(this SwaggerGenOptions options)
  228. {
  229. /*
  230. * TODO remove when System.Text.Json supports non-string keys.
  231. * Used in Jellyfin.Api.Controller.GetChannels.
  232. */
  233. options.MapType<Dictionary<ImageType, string>>(() =>
  234. new OpenApiSchema
  235. {
  236. Type = "object",
  237. Properties = typeof(ImageType).GetEnumNames().ToDictionary(
  238. name => name,
  239. name => new OpenApiSchema
  240. {
  241. Type = "string",
  242. Format = "string"
  243. })
  244. });
  245. /*
  246. * Support BlurHash dictionary
  247. */
  248. options.MapType<Dictionary<ImageType, Dictionary<string, string>>>(() =>
  249. new OpenApiSchema
  250. {
  251. Type = "object",
  252. Properties = typeof(ImageType).GetEnumNames().ToDictionary(
  253. name => name,
  254. name => new OpenApiSchema
  255. {
  256. Type = "object", Properties = new Dictionary<string, OpenApiSchema>
  257. {
  258. {
  259. "string",
  260. new OpenApiSchema
  261. {
  262. Type = "string",
  263. Format = "string"
  264. }
  265. }
  266. }
  267. })
  268. });
  269. }
  270. }
  271. }