Search code examples
c#asp.netasp.net-mvcasp.net-mvc-4simplemembership

Restrict access to the site for specific role


I have 3 roles: Registered Users, Approved Users, and Admins.
Access to the site is only available to Approved users and Admins.

To restrict anonymous access I've added a filter in FilterConfig as follows:

filters.Add(new System.Web.Mvc.AuthorizeAttribute());   

Now, for registered users I want them to redirect to a landing page saying:

Please contact one of the administrators to approve you.

I'm not really sure what's the correct way to do that.
I can setup authorize attribute on each of the controllers, but I'm not sure if that's a good way.
Also, I'm not sure where I should specify default redirect action based on the role.
I know that I can specify default redirect action in RouteConfig.cs but not sure where to specify a role.


Solution

  • StanK is right that having [Authorize] attribute will redirect all users who are not logged-in to the login page. That's half of your dillema.

    From there you need to alter your logon method to check if a newly logged-in user has the right role (e.g. ConfirmedUser). This is tricky because User.IsInRole("ConfirmedUser") will always be false in your logon method. This is because the User object is populated by the http object, which will not be re-populated until the next re-cycle. Luckily, you can use the Roles.IsUserInRole(userName, "ConfirmedUser") to check if the user has the right role.

    So, within your logon method, after authenticating user, log the user out and re-direct them to an [AllowAnonymous] method which informs them that they are not yet confirmed.

    if (Roles.IsUserInRole(userName, "ConfirmedUser")
    {
                    FormsAuthentication.SignOut();
                    return RedirectToAction("WarningMsg", "Home");
    
    }