I have a mvc 3 project and I use AD to authorise users.
I have a page where only users with the role “Admin” should have access.
I’ve made the sign in working and authorise users so only admins can acces the admin part of the site.
The problem I have is when a users is not admin, I seem to be unable to show a good error message.
Here is my actionFilterattribute
public class AdminOnlyAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
bool isAuthorised = false;
IPrincipal user = filterContext.HttpContext.User;
if (user.Identity.IsAuthenticated)
{
if (user.IsInRole("Admin"))
{
isAuthorised = true;
}
}
if (!isAuthorised)
{
//error message here
}
}
And this is my controller for admin
[AdminOnly]
public ActionResult Index()
{
//admin stuff
}
Any help is appreciated, thanks in advance
If the
isAuthorisedis false, you’ll need to take them to a page where you can display a “You do not have access to the page etc.”. To do the redirect, you must do the following (in my example I’m redirecting them to Account/AccessDenied that will return a view containing a message saying “You do not have access etc…”: