Authorize mvc user access

2

I am implementing the use of user permissions with the Authorize , I have correctly implemented its operation, but I would like to know how I do that when the user is not authorized to access that view in the controller Authorize does not redirect me to the login if not to a warning window that does not have the permissions:

public class UnidadesController : Controller
{
    SidcarEntities1 db = new SidcarEntities1();
    // GET: Unidades
    [Authorize(Users = "Usuario1, Usuario2")]
    public ActionResult Arope()
    {
        List<Departamento> DepartamentoList = db.Departamentos.ToList();
        ViewBag.DepartamentoList = new SelectList(DepartamentoList, "IdDepartamento", "Departamento1");
        return View();
    }
}
    
asked by Jager Rubio 30.05.2018 в 16:09
source

2 answers

0

Good, good option, there is no where I am. The Authorize attribute returns a code 401 regardless of whether the user is logged in or not. Solutions that I have used other times: Option 1- Create your own attribute that inherits from Authorize, in which you check whether or not you are logged in and return Forbidden or Unauthorized as the case may be:

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAuthenticated)
        {
            filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}

Option 2- (Even more ugly), in the Login you add a condition to check if the user is authenticated or not. If you are authenticated and have been redirected to the Login, then you assume that it is not authorized to do what you intended to do and you redirect it to your own view with the message "You do not have blablablbla permissions"

    
answered by 30.05.2018 в 16:52
0

There are two ways, the first and the most viable is

  • Validate the session through a FilterAttribute
  • Only make use of the annotation [Authorize]
  • 1. Using a FilterAttribute

    You can implement a FilterAttribute where you can validate if the user is authenticated. First you must create a class ValidateAuthenticationFilterAttribute that inherits from ActionFilterAttribute , and if the user has not been authenticated, a redirection must be made to the permission page denied (assuming that your Controller is called Permissions and the Action is Denied):

    public class ValidateAuthenticationFilterAttribute : ActionFilterAttribute
    {
    
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (/*Aquí validas si el usuario tiene los permisos*/)
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Permisos", action = "Denegado" }));
            }
            base.OnActionExecuting(filterContext);
        }
    }
    

    Finally, in the Controler sol you will have to put the annotation [ValidateAuthenticationFilter] :

    [ValidateAuthenticationFilter]
    public class UnidadesController : Controller
    {
        //TO DO
    }
    

    2. Using the annotation [Authorize]

    If the user is not logged in the system and this annotation is used, the application will redirect to Controller and Action declared by default in the App_Start \ RouteConfig.cs file:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Login", action = "Index", id = UrlParameter.Optional }
        );
    }
    

    Your code would be as follows:

    [Authorize]
    public class UnidadesController : Controller
    {
        //TO DO
    }
    
        
    answered by 30.05.2018 в 18:43