Block ASP.NET MVC Applications Administration Site for LocalHost only

I have an ASP.NET MVC website that I would like to add a small admin page to. The problem is that I will be deploying the whole thing and I will not have SSL. I'm fine, requiring a remote desktop administrator and using a local browser for administration.

Can this be done? Basically I would like to get the same behavior <customeErrors mode="RemoteOnly" />

as excluding my admin pages. Can I do this via web.config in some way?

+3


source to share


2 answers


Request.IsLocal

- your friend.

http://msdn.microsoft.com/en-us/library/system.web.httprequest.islocal.aspx

You can use this to check that the request is coming from the local machine.

Custom attribute



You can then extend this to become a custom attribute, but that might be overkill. If this is your chosen route, this is a good example that does something like this:

Custom Attributes in ActionResult

MVC3 onwards allows you to set an attribute at the controller level rather than a method, so you can block access to the entire controller responsible for admin pages.

+10


source


I did it by writing a custom attribute like:

public class IsLocalAttribute : AuthorizeAttribute
{
    public bool ThrowSecurityException { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isLocal = httpContext.Request.IsLocal;
        if (!isLocal && ThrowSecurityException)
            throw new SecurityException();
        return isLocal;
    }
}

      

Basic usage for the whole controller:

[IsLocal]
public class LocalOnlyController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

      



or by a specific method:

public class SomeController : Controller
{
    [IsLocal]
    public ActionResult LocalOnlyMethod()
    {
        return View();
    }
}

      

If you want to throw a security exception instead of a 302 redirect:

public class SomeController : Controller
{
    [IsLocal(ThrowSecurityException = true)]
    public ActionResult LocalOnlyMethod()
    {
        return View();
    }
}

      

+7


source







All Articles