jellyfin/Jellyfin.Api/Middleware/IpBasedAccessValidationMiddleware.cs

52 lines
1.6 KiB
C#
Raw Normal View History

using System.Net;
2020-09-03 09:32:22 +00:00
using System.Threading.Tasks;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using Microsoft.AspNetCore.Http;
2023-01-31 11:18:10 +00:00
namespace Jellyfin.Api.Middleware;
/// <summary>
/// Validates the IP of requests coming from local networks wrt. remote access.
/// </summary>
2023-02-17 18:27:36 +00:00
public class IPBasedAccessValidationMiddleware
2020-09-03 09:32:22 +00:00
{
2023-01-31 11:18:10 +00:00
private readonly RequestDelegate _next;
2020-09-03 09:32:22 +00:00
/// <summary>
2023-02-17 18:27:36 +00:00
/// Initializes a new instance of the <see cref="IPBasedAccessValidationMiddleware"/> class.
2020-09-03 09:32:22 +00:00
/// </summary>
2023-01-31 11:18:10 +00:00
/// <param name="next">The next delegate in the pipeline.</param>
2023-02-17 18:27:36 +00:00
public IPBasedAccessValidationMiddleware(RequestDelegate next)
2020-09-03 09:32:22 +00:00
{
2023-01-31 11:18:10 +00:00
_next = next;
}
2020-09-03 09:32:22 +00:00
2023-01-31 11:18:10 +00:00
/// <summary>
/// Executes the middleware action.
/// </summary>
/// <param name="httpContext">The current HTTP context.</param>
/// <param name="networkManager">The network manager.</param>
/// <returns>The async task.</returns>
public async Task Invoke(HttpContext httpContext, INetworkManager networkManager)
{
if (httpContext.IsLocal())
2020-09-03 09:32:22 +00:00
{
2023-01-31 11:18:10 +00:00
// Running locally.
await _next(httpContext).ConfigureAwait(false);
return;
2020-09-03 09:32:22 +00:00
}
2023-02-17 18:27:36 +00:00
var remoteIP = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback;
2020-09-03 09:32:22 +00:00
2023-02-17 18:27:36 +00:00
if (!networkManager.HasRemoteAccess(remoteIP))
2023-01-31 11:18:10 +00:00
{
// No access from network, respond with 503 instead of 200.
httpContext.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
2023-01-31 11:18:10 +00:00
return;
2020-09-03 09:32:22 +00:00
}
2023-01-31 11:18:10 +00:00
await _next(httpContext).ConfigureAwait(false);
2020-09-03 09:32:22 +00:00
}
}