IpBasedAccessValidationMiddleware.cs 1.7 KB

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