Reputation: 9017
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.
Upvotes: 1
Views: 2942
Reputation: 32490
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");
}
Upvotes: 1
Reputation: 4770
You should be able to use the [Authorize]
attributes for this.
Restricted pages will have their controller or action decorated with [Authorize(Roles="Approved User,Admin")]
, the 'landing page' for registered users would be [Authorize(Roles="Registered User,Approved User,Admin")]
and the Logon action would have [AllowAnonymous]
.
If the user is not authorised, they would be re-directed to Account/Login
. You would need to build some logic in this action that redirects "Registered Users" who are already logged in to your landing page. Others should just see the standard login page.
EDIT
The logic to redirect "Registered Users" from the login page to the landing page would look something like this
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
if (User.Identity.IsAuthenticated && Roles.IsUserInRole("Registered User"))
return RedirectToAction("LandingPage");
ViewBag.ReturnUrl = returnUrl;
return View();
}
Upvotes: 2