ApiServiceCollectionExtensions.cs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text.Json.Serialization;
  7. using Jellyfin.Api;
  8. using Jellyfin.Api.Auth;
  9. using Jellyfin.Api.Auth.FirstTimeSetupOrElevatedPolicy;
  10. using Jellyfin.Api.Auth.RequiresElevationPolicy;
  11. using Jellyfin.Api.Constants;
  12. using Jellyfin.Api.Controllers;
  13. using Jellyfin.Server.Formatters;
  14. using Microsoft.AspNetCore.Authentication;
  15. using Microsoft.AspNetCore.Authorization;
  16. using Microsoft.Extensions.DependencyInjection;
  17. using Microsoft.OpenApi.Models;
  18. using Swashbuckle.AspNetCore.SwaggerGen;
  19. namespace Jellyfin.Server.Extensions
  20. {
  21. /// <summary>
  22. /// API specific extensions for the service collection.
  23. /// </summary>
  24. public static class ApiServiceCollectionExtensions
  25. {
  26. /// <summary>
  27. /// Adds jellyfin API authorization policies to the DI container.
  28. /// </summary>
  29. /// <param name="serviceCollection">The service collection.</param>
  30. /// <returns>The updated service collection.</returns>
  31. public static IServiceCollection AddJellyfinApiAuthorization(this IServiceCollection serviceCollection)
  32. {
  33. serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeSetupOrElevatedHandler>();
  34. serviceCollection.AddSingleton<IAuthorizationHandler, RequiresElevationHandler>();
  35. return serviceCollection.AddAuthorizationCore(options =>
  36. {
  37. options.AddPolicy(
  38. Policies.RequiresElevation,
  39. policy =>
  40. {
  41. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  42. policy.AddRequirements(new RequiresElevationRequirement());
  43. });
  44. options.AddPolicy(
  45. Policies.FirstTimeSetupOrElevated,
  46. policy =>
  47. {
  48. policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
  49. policy.AddRequirements(new FirstTimeSetupOrElevatedRequirement());
  50. });
  51. });
  52. }
  53. /// <summary>
  54. /// Adds custom legacy authentication to the service collection.
  55. /// </summary>
  56. /// <param name="serviceCollection">The service collection.</param>
  57. /// <returns>The updated service collection.</returns>
  58. public static AuthenticationBuilder AddCustomAuthentication(this IServiceCollection serviceCollection)
  59. {
  60. return serviceCollection.AddAuthentication(AuthenticationSchemes.CustomAuthentication)
  61. .AddScheme<AuthenticationSchemeOptions, CustomAuthenticationHandler>(AuthenticationSchemes.CustomAuthentication, null);
  62. }
  63. /// <summary>
  64. /// Extension method for adding the jellyfin API to the service collection.
  65. /// </summary>
  66. /// <param name="serviceCollection">The service collection.</param>
  67. /// <param name="baseUrl">The base url for the API.</param>
  68. /// <returns>The MVC builder.</returns>
  69. public static IMvcBuilder AddJellyfinApi(this IServiceCollection serviceCollection, string baseUrl)
  70. {
  71. return serviceCollection.AddMvc(opts =>
  72. {
  73. opts.UseGeneralRoutePrefix(baseUrl);
  74. opts.OutputFormatters.Insert(0, new CamelCaseJsonProfileFormatter());
  75. opts.OutputFormatters.Insert(0, new PascalCaseJsonProfileFormatter());
  76. })
  77. // Clear app parts to avoid other assemblies being picked up
  78. .ConfigureApplicationPartManager(a => a.ApplicationParts.Clear())
  79. .AddApplicationPart(typeof(StartupController).Assembly)
  80. .AddJsonOptions(options =>
  81. {
  82. // Setting the naming policy to null leaves the property names as-is when serializing objects to JSON.
  83. options.JsonSerializerOptions.PropertyNamingPolicy = null;
  84. })
  85. .AddControllersAsServices();
  86. }
  87. /// <summary>
  88. /// Adds Swagger to the service collection.
  89. /// </summary>
  90. /// <param name="serviceCollection">The service collection.</param>
  91. /// <returns>The updated service collection.</returns>
  92. public static IServiceCollection AddJellyfinApiSwagger(this IServiceCollection serviceCollection)
  93. {
  94. return serviceCollection.AddSwaggerGen(c =>
  95. {
  96. c.SwaggerDoc("api-docs", new OpenApiInfo { Title = "Jellyfin API" });
  97. c.AddSecurityDefinition(AuthenticationSchemes.CustomAuthentication, new OpenApiSecurityScheme
  98. {
  99. Type = SecuritySchemeType.ApiKey,
  100. In = ParameterLocation.Header,
  101. Name = "X-Emby-Token",
  102. Description = "API key header parameter"
  103. });
  104. var securitySchemeRef = new OpenApiSecurityScheme
  105. {
  106. Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = AuthenticationSchemes.CustomAuthentication },
  107. };
  108. // TODO: Apply this with an operation filter instead of globally
  109. // https://github.com/domaindrivendev/Swashbuckle.AspNetCore#add-security-definitions-and-requirements
  110. c.AddSecurityRequirement(new OpenApiSecurityRequirement
  111. {
  112. { securitySchemeRef, Array.Empty<string>() }
  113. });
  114. // Add all xml doc files to swagger generator.
  115. var xmlFiles = Directory.GetFiles(
  116. AppContext.BaseDirectory,
  117. "*.xml",
  118. SearchOption.TopDirectoryOnly);
  119. foreach (var xmlFile in xmlFiles)
  120. {
  121. c.IncludeXmlComments(xmlFile);
  122. }
  123. // Order actions by route path, then by http method.
  124. c.OrderActionsBy(description =>
  125. $"{description.ActionDescriptor.RouteValues["controller"]}_{description.HttpMethod}");
  126. // Use method name as operationId
  127. c.CustomOperationIds(description =>
  128. description.TryGetMethodInfo(out MethodInfo methodInfo) ? methodInfo.Name : null);
  129. });
  130. }
  131. }
  132. }