Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC 3 Redirect UnAuthorized User not to loginUrl

i have a project using ASP.Net MVC3 and using membership for roles. i use authorize in every controller. eg:

[Authorize(Roles = "Administrator")]
    public ActionResult Index(string q, int i)
    {
      return View(model);
    }

if someone doesnt have role for administrator, then it will redirect to login page by default. how to change it,so it will redirect into Views/Shared/UnAuthorize.cshtml ? or maybe if someone doesnt have role for administrator, it will show message box (alert) ?

thanks in advance.

like image 376
ntep vodka Avatar asked Oct 05 '11 02:10

ntep vodka


2 Answers

i solved my problem. i only do this :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

public class MyAuthorize : AuthorizeAttribute
{
   protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
   {
     //you can change to any controller or html page.
     filterContext.Result = new RedirectResult("/cpanel/roles/unauthorize");

   }
 }

and apply MyAuthorize to class or action:

[MyAuthorize]
public class AdminController :Controller
{
}

thats it.

like image 89
ntep vodka Avatar answered Nov 11 '22 15:11

ntep vodka


Just change the page that have to be shown in the web.config (check that the route exists)

<authentication mode="Forms">
  <forms loginUrl="~/UnAuthorize" timeout="2880" />
</authentication>

If you, instead, want to redirect to a specific path for every roles you can extend the AuthorizeAttribute with your own. Something like this (not tested, I write this to give you an idea)

public class CheckAuthorize : ActionFilterAttribute
{
  public Roles[] Roles { get; set; }
  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
    //Your code to get the user
    var user = ((ControllerBase)filterContext.Controller).GetUser();

    if (user != null)
    {
      foreach (Role role in Roles)
      {
        if (role == user.Role)
          return;
      }
    }      
    RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
    if user.Role==Role.Administrator
    {
      redirectTargetDictionary.Add("action", "Unauthorized");
      redirectTargetDictionary.Add("controller", "Home");
    }
    else
    {
      redirectTargetDictionary.Add("action", "Logon");
      redirectTargetDictionary.Add("controller", "Home");
    }
    filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
  }
}
like image 39
Iridio Avatar answered Nov 11 '22 14:11

Iridio