Restrict access to different site sections by ip

453 Views Asked by At

In our MVC 3 solution we have a site with many sections. Customer want to have a possibility to manage access to each section by IP address(from admin part). What are the standard ways of implementing this requirements? I see, smth like this: every section has a list of wildcards, that represent IP addresses, and then we we somehow validate IP address using this wildcards.

1

There are 1 best solutions below

2
On

I would suggest not using directly IP addresses in your code - these tend to change from time to time. Do create system of "zones", similar like in many personal firewalls.

My solution would be basically like this :

Create custom authorization attribute

public class AuthorizeZone: AuthorizeAttribute
{
    private string _zone; 
    public AuthorizeZone(string zoneName)
    {
        _zone = zoneName;
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var zone = GetZoneIpMappingsFromXMLorDB_IdeallyCached(_zone);
        return zone.ContainsIp(httpContext.Request.UserHostAddress); // implement by simple list or ip-mask
    }        
}

you then use it like this

[AuthorizeZone("Intranet")]
public ActionResult Foo()
{}

Your zones definitions is up to you, use XML, database, whatever...