59 lines
2.1 KiB
C#
59 lines
2.1 KiB
C#
using System.Net;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using StopShopping.FileApi.Extensions;
|
|
|
|
namespace StopShopping.FileApi.Middlewares;
|
|
|
|
public class InternalAccessOnlyMiddleware
|
|
{
|
|
public InternalAccessOnlyMiddleware(
|
|
RequestDelegate next,
|
|
IProblemDetailsService problemDetailsService,
|
|
ILogger<InternalAccessOnlyMiddleware> logger)
|
|
{
|
|
_next = next;
|
|
_problemService = problemDetailsService;
|
|
_logger = logger;
|
|
}
|
|
|
|
private readonly RequestDelegate _next;
|
|
private readonly IProblemDetailsService _problemService;
|
|
private readonly ILogger<InternalAccessOnlyMiddleware> _logger;
|
|
|
|
public async Task InvokeAsync(HttpContext httpContext)
|
|
{
|
|
var endpoint = httpContext.GetEndpoint();
|
|
if (null != endpoint)
|
|
{
|
|
var internalOnlyMetadata = endpoint.Metadata.GetMetadata<InternalOnlyMetadata>();
|
|
if (null != internalOnlyMetadata)
|
|
{
|
|
if (null == httpContext.Connection.RemoteIpAddress
|
|
|| !IPAddress.IsLoopback(httpContext.Connection.RemoteIpAddress))
|
|
{
|
|
var problemDetails = new ProblemDetails
|
|
{
|
|
Detail = $"remote ip: {httpContext.Connection.RemoteIpAddress}",
|
|
Instance = httpContext.Request.Path,
|
|
Status = StatusCodes.Status403Forbidden,
|
|
Title = "access denied, local access only."
|
|
};
|
|
|
|
httpContext.Response.StatusCode = StatusCodes.Status403Forbidden;
|
|
httpContext.Response.ContentType = "application/problem+json";
|
|
|
|
await _problemService.WriteAsync(new ProblemDetailsContext
|
|
{
|
|
HttpContext = httpContext,
|
|
ProblemDetails = problemDetails,
|
|
});
|
|
|
|
_logger.LogInformation("denied access: {Ip}", httpContext.Connection.RemoteIpAddress);
|
|
}
|
|
}
|
|
}
|
|
|
|
await _next(httpContext);
|
|
}
|
|
}
|