Lock Down ASP.NET MVC App Administration Site to L

2019-02-18 18:25发布

问题:

I have an ASP.NET MVC website that I would like to add a small administration page to. The issue I have is that I will be deploying this all over and I will not have SSL available. I am OK with requiring the administrator to remote desktop and use the local browser to perform the administration.

Can this be done? I would basically like to get the same behavior as <customeErrors mode="RemoteOnly" /> except for my administration pages. Can I do this via web.config some how?

回答1:

Request.IsLocal is your friend.

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

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

Custom Attribute

You could then extend this to be a custom attribute, but that might be overkill. If that is the route you choose this is a good example that does something similar:

Custom Attributes on ActionResult

MVC3 onwards allows you to set an attribute at Controller level, rather than Method too, so you could lock access to the entire controller responsible for the admin pages.



回答2:

I did it by writing a custom attribute, like this:

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 on an entire controller:

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

or on 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();
    }
}