IpBasedAccessValidationMiddleware.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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.Server.Middleware
  7. {
  8. /// <summary>
  9. /// Validates the IP of requests coming from local networks wrt. remote access.
  10. /// </summary>
  11. public class IpBasedAccessValidationMiddleware
  12. {
  13. private readonly RequestDelegate _next;
  14. /// <summary>
  15. /// Initializes a new instance of the <see cref="IpBasedAccessValidationMiddleware"/> class.
  16. /// </summary>
  17. /// <param name="next">The next delegate in the pipeline.</param>
  18. public IpBasedAccessValidationMiddleware(RequestDelegate next)
  19. {
  20. _next = next;
  21. }
  22. /// <summary>
  23. /// Executes the middleware action.
  24. /// </summary>
  25. /// <param name="httpContext">The current HTTP context.</param>
  26. /// <param name="networkManager">The network manager.</param>
  27. /// <returns>The async task.</returns>
  28. public async Task Invoke(HttpContext httpContext, INetworkManager networkManager)
  29. {
  30. if (httpContext.IsLocal())
  31. {
  32. // Running locally.
  33. await _next(httpContext).ConfigureAwait(false);
  34. return;
  35. }
  36. var remoteIp = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback;
  37. if (!networkManager.HasRemoteAccess(remoteIp))
  38. {
  39. return;
  40. }
  41. await _next(httpContext).ConfigureAwait(false);
  42. }
  43. }
  44. }