ApiServiceCollectionExtensions.cs 13 KB

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