3

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 that 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.

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Why do you use a custom filter and not the out of the box "Authorize" filter?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.