2

I have this custom authorization class to check if a user is an admin:

public class IsAdminAttribute : AuthorizeAttribute
    {
        private datacontext() db = new datacontext();
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var isAuthorized = base.AuthorizeCore(httpContext);
            if (isAuthorized)
            {
                var currentUser = httpContext.User.Identity.Name;
                return db.Users.Where(u => u.UserName == currentUser).Where(ut => ut.UserTypeID == 2).Count() == 1 ? true : false;
            }
            return isAuthorized;
        }

    }

and is used here:

[IsAdmin]
public ActionResult CreateUser()
{
    ViewBag.UserTypeID = new SelectList(db.UserTypes, "UserTypeId", "Name");
    return View();
}

and works ok but takes me back to my log in page when the user is not authorized. What I want to happen is for the user to be redirected somewhere with an error message popping up. How do I handle the denied access event?

1 Answer 1

7

How do I handle the denied access event?

Simply override the HandleUnauthorizedRequest method and return directly the view you like:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    filterContext.Result = new ViewResult
    {
        ViewName = "Unauthorized"
    };
}

This will render ~/Views/Shared/Unauthorized.cshtml. You could also pass view models, master pages, etc... to this ViewResult.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.