2
0

IpBasedAccessValidationMiddleware.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. return;
  39. }
  40. await _next(httpContext).ConfigureAwait(false);
  41. }
  42. }