Redirect the user when he is not authorized to the page in MVC3

I have an mvc 3 project and I use AD to authorize users. I have a page where only users with the Administrator role should have access.

I made a sign in the work and authorization of users, so only administrators can access the administrative part of the site. My problem is, when users are not administrators, 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

+4
source share
1 answer

If isAuthorised is false, you will need to send them to a page where you can display "You do not have access to the page, etc.". To do the redirection, you must do the following (in my example, I redirect them to Account / AccessDenied, which will return a view containing the message "You do not have access, etc ....":

 if (!isAuthorised) { filterContext.Result = new RedirectToRouteResult( new RouteValueDictionary {{"action", "AccessDenied"}, {"controller", "Account"}}); } 
+3
source

Source: https://habr.com/ru/post/1411115/


All Articles