Damian Bod đã làm cho một blog post chứng minh làm thế nào để thực hiện middleware để xử lý danh sách trắng IP.
Anh ấy đưa ra các ví dụ về bộ lọc hành động hoặc phần mềm trung gian toàn cầu.
Dù bằng cách nào bạn cần phải thêm địa chỉ IP được phép vào appsettings.json
và kiểm tra địa chỉ IP của khách hàng với chúng.
Địa chỉ IP của khách hàng có sẵn qua HttpContext
(ví dụ: context.Connection.RemoteIpAddress
).
Nếu bạn muốn thêm dải địa chỉ IP vào danh sách trắng, bạn có thể sử dụng gói Nuget IPAddressRange, hỗ trợ các định dạng khác nhau như "192.168.0.0/24" và "192.168.0.0/255.255.255.0", bao gồm các biểu thức CIDR và IPv6.
Dưới đây là một ví dụ về làm thế nào để làm điều đó trong một bộ lọc:
appsettings.json:
{
"IPAddressWhitelistConfiguration": {
"AuthorizedIPAddresses": [
"::1", // IPv6 localhost
"127.0.0.1", // IPv4 localhost
"192.168.0.0/16", // Local network
"10.0.0.0/16", // Local network
]
}
}
IPWhiteListConfiguration.cs:
namespace My.Web.Configuration
{
using System.Collections.Generic;
public class IPWhitelistConfiguration : IIPWhitelistConfiguration
{
public IEnumerable<string> AuthorizedIPAddresses { get; set; }
}
}
Startup.cs:
public class Startup
{
// ...
public void ConfigureServices(IServiceCollection services)
{
// ...
services.Configure<IPWhitelistConfiguration>(
this.Configuration.GetSection("IPAddressWhitelistConfiguration"));
// ...
}
}
ClientIPAddressFilterAttribute.cs:
namespace My.Web.Filters
{
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using NetTools;
using My.Web.Configuration;
public class ClientIPAddressFilterAttribute : ActionFilterAttribute
{
private readonly IEnumerable<IPAddressRange> authorizedRanges;
public ClientIPAddressFilterAttribute(IIPWhitelistConfiguration configuration)
{
this.authorizedRanges = configuration.AuthorizedIPAddresses
.Select(item => IPAddressRange.Parse(item));
}
public override void OnActionExecuting(ActionExecutingContext context)
{
var clientIPAddress = context.HttpContext.Connection.RemoteIpAddress;
if (!this.authorizedRanges.Any(range => range.Contains(clientIPAddress)))
{
context.Result = new UnauthorizedResult();
}
}
}
Bạn có thể tìm ra những gì các lỗi máy chủ nội bộ là gì và thêm nó vào bài viết của bạn? – mason
ipSecurity là IIS cụ thể, trong khi ASP.NET Core ist về giao diện chéo phục vụ yêu cầu web thông qua máy chủ Kestrel. Có thể có một cách tốt hơn nhưng thông qua đường ống trung gian, có thể truy xuất địa chỉ IP như được mô tả trong http://stackoverflow.com/questions/28664686/how-do-i-get-client-ip-address-in-asp -net-core và trả về kết quả NotFound. –
@ rboe ah vâng, điều đó sẽ có ý nghĩa. Vì vậy, bạn nghĩ rằng một trường hợp của nó thêm nó bằng tay sau đó? Đã nghĩ rằng có thể là trường hợp – MartinM