IpBasedAccessValidationMiddleware.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System.Net;
  2. using System.Threading.Tasks;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Common.Net;
  5. using Microsoft.AspNetCore.Http;
  6. namespace Jellyfin.Api.Middleware;
  7. /// <summary>
  8. /// Validates the IP of requests coming from local networks wrt. remote access.
  9. /// </summary>
  10. public class IPBasedAccessValidationMiddleware
  11. {
  12. private readonly RequestDelegate _next;
  13. /// <summary>
  14. /// Initializes a new instance of the <see cref="IPBasedAccessValidationMiddleware"/> class.
  15. /// </summary>
  16. /// <param name="next">The next delegate in the pipeline.</param>
  17. public IPBasedAccessValidationMiddleware(RequestDelegate next)
  18. {
  19. _next = next;
  20. }
  21. /// <summary>
  22. /// Executes the middleware action.
  23. /// </summary>
  24. /// <param name="httpContext">The current HTTP context.</param>
  25. /// <param name="networkManager">The network manager.</param>
  26. /// <returns>The async task.</returns>
  27. public async Task Invoke(HttpContext httpContext, INetworkManager networkManager)
  28. {
  29. if (httpContext.IsLocal())
  30. {
  31. // Running locally.
  32. await _next(httpContext).ConfigureAwait(false);
  33. return;
  34. }
  35. var remoteIP = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback;
  36. if (!networkManager.HasRemoteAccess(remoteIP))
  37. {
  38. // No access from network, respond with 503 instead of 200.
  39. httpContext.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
  40. return;
  41. }
  42. await _next(httpContext).ConfigureAwait(false);
  43. }
  44. }