डेमियन बोड कैसे मिडलवेयर लागू करने के लिए प्रदर्शित किया कि एक blog post बना दिया है आईपी whitelisting संभाल करने के लिए।
वह वैश्विक मिडलवेयर या एक्शन फ़िल्टर के उदाहरण देता है।
किसी भी तरह से आपको अपने appsettings.json
पर अनुमत आईपी पते जोड़ने की आवश्यकता है, और उनके खिलाफ क्लाइंट आईपी पता जांचें।
क्लाइंट आईपी पता HttpContext
(उदा। context.Connection.RemoteIpAddress
) के माध्यम से उपलब्ध है।
आप IP पता श्रेणी श्वेतसूची में चाहते हैं, तो आप Nuget पैकेज IPAddressRange है, जो इस तरह के "192.168.0.0/24" के रूप में विभिन्न स्वरूपों का समर्थन करता उपयोग कर सकते हैं और "192.168.0.0/255.255.255.0", सीआईडीआर भाव और सहित आईपीवी 6।
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();
}
}
}
आप यह पता लगाने कर सकते हैं क्या आंतरिक सर्वर त्रुटि है और अपनी पोस्ट में जोड़ने? – mason
ipSecurity आईआईएस विशिष्ट है, जबकि एएसपी.NET कोर क्रॉस प्लैटफॉर्म के बारे में केस्ट्रल सर्वर के माध्यम से वेब अनुरोध की सेवा करता है। एक बेहतर तरीका हो सकता है लेकिन मिडलवेयर पाइपलाइन के माध्यम से http://stackoverflow.com/questions/28664686/how-do-i-get-client-ip-address-in-asp में वर्णित आईपी पते को पुनर्प्राप्त करना संभव है। नेट-कोर और एक नोटफॉउंड परिणाम लौटाएं। –
@ आरबो आह हाँ, यह समझ में आता है। तो आपको लगता है कि इसे मैन्युअल रूप से जोड़ने का मामला है? यह सोच रहा था कि – MartinM