|
@@ -0,0 +1,42 @@
|
|
|
+using Microsoft.AspNetCore.Mvc;
|
|
|
+using Microsoft.AspNetCore.Mvc.Filters;
|
|
|
+
|
|
|
+namespace Hotline.Api.Filter
|
|
|
+{
|
|
|
+ public class ClientIpFilterAttribute : ActionFilterAttribute
|
|
|
+ {
|
|
|
+ private readonly List<string> _whiteIps;
|
|
|
+ private readonly ILogger _logger;
|
|
|
+
|
|
|
+ public ClientIpFilterAttribute(List<string> whiteIps, ILogger logger)
|
|
|
+ {
|
|
|
+ _whiteIps = whiteIps;
|
|
|
+ _logger = logger;
|
|
|
+ }
|
|
|
+
|
|
|
+ public override void OnActionExecuting(ActionExecutingContext context)
|
|
|
+ {
|
|
|
+ if(!_whiteIps.Any()) return;
|
|
|
+
|
|
|
+ //var ip = context.HttpContext.Connection.RemoteIpAddress?.ToString();
|
|
|
+ //if (ip != null)
|
|
|
+ //{
|
|
|
+ // context.HttpContext.Items["ClientIp"] = ip;
|
|
|
+ //}
|
|
|
+ var ip = context.HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
|
|
|
+ if (string.IsNullOrEmpty(ip))
|
|
|
+ {
|
|
|
+ _logger.LogWarning("Forbidden Request from IP: {RemoteIp}", ip);
|
|
|
+ context.Result = new StatusCodeResult(StatusCodes.Status403Forbidden);
|
|
|
+ }
|
|
|
+
|
|
|
+ if(!_whiteIps.Contains(ip))
|
|
|
+ {
|
|
|
+ _logger.LogWarning("Forbidden Request from IP: {RemoteIp}", ip);
|
|
|
+ context.Result = new StatusCodeResult(StatusCodes.Status403Forbidden);
|
|
|
+ }
|
|
|
+
|
|
|
+ base.OnActionExecuting(context);
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|