开发者

asp.net mvc - limit access to web pages

Greetings, in my asp.net mvc application what i would like to do is to enable access to some pages only after user was successfully authorized. I have already created custom membership provider and tha开发者_运维技巧t works fine. How can I, in web config create such rule - for instance for all pages in ~Admin/ folder? I don't want to create on every controller's action the validation code. For now i have in my web.config the following statement:

    <location path="~/Admin"> 
<system.web>
  <authorization>
    <deny users="?"/> 
  </authorization>
</system.web>

but it doesn't work.


Doing authorization logic in config files has one big disadvantage: it cannot be easily unit tested, and something so important as authentication should be unit tested. I would recommend you for this matter to write a custom authorization filter which could be used to decorate a base controller for all admin actions that requires authentication:

[AttributeUsage(
    AttributeTargets.Method | AttributeTargets.Class, 
    Inherited = true
)]
public class RequiresAuthenticationAttribute 
    : FilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            filterContext.Result = new RedirectResult(
                string.Format("{0}?ReturnUrl={1}", 
                    FormsAuthentication.LoginUrl, 
                    filterContext.HttpContext.Request.Url.AbsoluteUri
                )
            );
        }
    }
}

And your admin controller:

[RequiresAuthentication]
public class AdminController : Controller
{
    // .. some actions that require authorized access
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜