Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I restrict access to certain pages in ASP.NET MVC?

I wish to lock out access to a user's EDIT page (eg. /user/pure.krome/edit) if

a) Identity.IsAuthenticated = false

or they are authenticated but

b) Idenitity.Name != user name of the user page they are trying to edit
c) Identity.UserType() != UserType.Administrator // This is like a Role, without using RoleProviders.

I'm assuming u can decorate a controller or a controller's action method with something(s), but i'm just not sure what?

like image 236
Pure.Krome Avatar asked Jun 03 '09 13:06

Pure.Krome


2 Answers

Look at the AuthorizeAttribute.

ASP.Net MVC: Can the AuthorizeAttribute be overriden?

like image 68
Daniel A. White Avatar answered Nov 15 '22 04:11

Daniel A. White


A custom attribute derived from AuthorizeAttribute is what I use to do this. Override the OnAuthorize method and implement your own logic.

public class OnlyUserAuthorizedAttribute : AuthorizeAttribute
{
    public override void OnAuthorize( AuthorizationContext filterContext )
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            filterContext.Result = new HttpUnauthorizeResult();
        }
        ...
    }
}
like image 25
tvanfosson Avatar answered Nov 15 '22 03:11

tvanfosson