DaGrooveNL
DaGrooveNL

Reputation: 187

MVC prevent access to controller method if specific variable has specific value

I am trying to figure out how to prevent access to a controller's method if user is not logged in or is not an admin. I have a class with variables inside which keep track of the user and his state (logged in, admin, etc.).

I think this can be done by using a ValidationAttribute. I have not used this technique before so I am probably doing something wrong.

AccountController.CS

[AdminUserValidation]
public ActionResult Index()
{          
        var account1 = account.GetAccountsWithType();
        return View(account1.ToList());
}

AdminUserValidation.CS

public class AdminUserValidationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (UserSession.Current.IsAdmin)
        {
            //Allow access to the controller's method
        }
        else
        {
            //Prevent access to the controller's method and show error page (bad request/forbidden)
        }
        base.OnActionExecuting(filterContext);
    }
}

Upvotes: 1

Views: 939

Answers (2)

DaGrooveNL
DaGrooveNL

Reputation: 187

I solved the issue by using the following code:

AccountController.CS

 [AdminUserValidation]
    public ActionResult Index()
    {          
        var account1 = account.GetAccountsWithType();
        return View(account1.ToList());
    }

AdminUserValidation.CS

public class AdminUserValidationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (UserSession.Current.IsAdmin == false)
        {
            //Prevent access to the controller's method and show error page (bad request/forbidden)
            filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden);
        }
        base.OnActionExecuting(filterContext);
    }
}

Upvotes: 0

Nick Spicer
Nick Spicer

Reputation: 2707

This functionality is already is User Roles, you need to assign each user a role using the UserManager like so:

User user = UserManager.FindById(userID);       
UserManager.AddToRole(userID, roleID);

The role IDs can be created by you, there is a default table called "AspNetRoles" which is where the roleID will be stored and AddToRole will insert records into "AspNetUserRoles".

Then in your controller you can specify which roles should be able to access the entire controller or individual methods.

[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
    ...
}

Users will need to log out and back in for the role to take effect as it is stored in a cookie.

Upvotes: 1

Related Questions