C# 如何在不取消整个控制器的情况下,将方法从一个控制器授权给一个或多个角色

C# 如何在不取消整个控制器的情况下,将方法从一个控制器授权给一个或多个角色,c#,asp.net-mvc-5,C#,Asp.net Mvc 5,我试图通过角色限制对控制器方法的访问,传统方式是,完整控制器拒绝所有角色的所有用户对角色的身份验证 这是带有返回消息“拒绝访问”的登录() public ActionResult Login() { //if (User.Identity.IsAuthenticated) if (User.IsInRole("ProvideASpecificRoleHere")) return RedirectToAction("Index", "Home"); if

我试图通过角色限制对控制器方法的访问,传统方式是,完整控制器拒绝所有角色的所有用户对角色的身份验证

这是带有返回消息“拒绝访问”的登录()

public ActionResult Login()
{
    //if (User.Identity.IsAuthenticated)
    if (User.IsInRole("ProvideASpecificRoleHere"))
        return RedirectToAction("Index", "Home");

    if (User.Identity.IsAuthenticated)
        ModelState.AddModelError("", "Acceso Denegado.");
    return View();
}
出于某种原因,他一直把我发送到:重定向到操作(“索引”,“主页”), 这应该只发生在一开始

[HttpPost]
    public ActionResult Login(LoginModel model)
    {
        if (User.Identity.IsAuthenticated)
        {
            return RedirectToAction("Index", "Home");
        }
        UserRol userRol = new UserRol();
        userRol.user = _serviceUsuario.ValidarCredencialesRol(model.Usuario, model.Contrasena);
        if (userRol.user != null)
        {
            model.Roles = userRol.user.Roles;
            FormsAuthentication.SetAuthCookie(model.Usuario, false);
            ((ClaimsIdentity)HttpContext.User.Identity).AddClaim(new Claim(ClaimTypes.Role, model.Roles));
            var authTicket = new FormsAuthenticationTicket(1, model.Usuario, DateTime.Now, DateTime.Now.AddMinutes(20), false, model.Roles);
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
            var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            HttpContext.Response.Cookies.Add(authCookie);

            return RedirectToAction("Index", "Home");
        }
        else
        {
            ModelState.AddModelError("", "Invalid login attempt.");
            return View(model);
        }
    }
    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
        UsuarioLogueado();
    }
这是注册用户的验证功能。 此类用于获取登录用户的信息、用作审核以及在视图中显示某些数据

    protected void UsuarioLogueado()
    {
        try
        {
            if (User.Identity.IsAuthenticated)
            {                   
                var usuarioLogueado = Session["UsarioEntityModel"] as UsarioEntityModel;
                if (usuarioLogueado == null)
                {
                    usuarioLogueado = _userService.ObtenerUsuarioLogueado(User.Identity.Name).ToUsarioEntityModel();
                    ((ClaimsIdentity)HttpContext.User.Identity).AddClaim(new Claim(ClaimTypes.Role, usuarioLogueado.Rol));
                    Session["UsarioEntityModel"] = usuarioLogueado;
                }
                ViewBag.usuarioLogueado = usuarioLogueado;
            }
            else
            {
                Session["UsarioEntityModel"] = null;
            }
        }
        catch (AggregateException ex)
        {
            throw ex;
        }
    }

根据提供的代码,在身份验证票证的用户数据中添加角色(新表单身份验证票证()的最后一个参数。。可以使用此用户数据

默认情况下,FormsAuthenticationTicket与“用户”一起工作,而不是与“角色”一起工作
[Authorize(Users=“model.Usuario”)]
可以工作,但
[Authorize(Roles=“Adminstrador”)]
会给您未经授权的权限

要使用角色,您需要在AuthTicket的
HttpContext.User
中添加角色。 在控制器中添加以下方法:-

protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.User != null)
            {
                if (filterContext.HttpContext.User.Identity.IsAuthenticated)
                {
                    if (filterContext.HttpContext.User.Identity is FormsIdentity)
                    {
                        FormsIdentity id = (FormsIdentity)HttpContext.User.Identity;
                        FormsAuthenticationTicket ticket = id.Ticket;
                        string userData = ticket.UserData;
                        string[] roles = userData.Split(',');
                        HttpContext.User = new GenericPrincipal(HttpContext.User.Identity, roles);
                    }
                }
            }
        }
您还可以为其创建授权筛选器,以便在应用程序中使用


如果在自定义授权类中重写OnAuthorization、AuthorizationCore和HandleUnauthorizedRequest方法,则它将调用OnAuthorization方法,如果调用base.OnAuthorization(filterContext)方法,然后它将调用AuthorizeCore方法,如果该方法返回false,则它将调用HandleUnauthorizedRequest方法。

此用户代码返回有关特定角色的视图:

而不是这个:

public ActionResult Login()
{
   if (User.Identity.IsAuthenticated)
      return RedirectToAction("Index", "Home");

   return View();
} 
public ActionResult Login()
{
   if (User.IsInRole("ProvideASpecificRoleHere"))
      return RedirectToAction("Index", "Home");

   return View();
}
试试这个:

public ActionResult Login()
{
   if (User.Identity.IsAuthenticated)
      return RedirectToAction("Index", "Home");

   return View();
} 
public ActionResult Login()
{
   if (User.IsInRole("ProvideASpecificRoleHere"))
      return RedirectToAction("Index", "Home");

   return View();
}

问题不清楚,根据提供的代码操作方法,“ReportDMsVehicleulos”可供具有角色“Administrator”的用户访问。这正是不起作用的,它对所有用户都被阻止,现在我必须将其保留为没有特定角色。请尝试使用[授权(“Administrator”)而不是[授权角色(Rol.Administrator)]并查看它是否有效。不确定AuthorizeRoles类。也请共享您的AuthorizeRoles类,该类中可能遗漏了某些内容。这是我的第一个选项,但不起作用。当用户登录时,我如何识别角色,并对其进行身份验证?我尝试过,但不起作用,出于某种原因,它将我发送到:RedDirectToAction(“Index”,“Home”),这应该只在开始时发生。我刚刚对发布的第一个代码添加了一些更改。((ClaimsIdentity)HttpContext.User.Identity)。AddClaim(新声明(ClaimTypes.Role,model.Roles));我在两个函数中都使用它,一次一个,然后在两个函数中都使用,但都不起作用。目前,操作方法如下:[Authorize(Roles=“Administrador”)]public ActionResult reportdmsvhiveulos(){return View();}请查看更新的解决方案。无需添加声明。非常好正是我所需要的。谢谢..:public ActionResult Login(){//if(User.Identity.IsAuthenticated)if(User.IsInRole(“ProvideSpecificRoleHere”))返回重定向到操作(“Index”,“Home”);if(User.Identity.IsAuthenticated)ModelState.AddModelError(“,“Acceso Denegado.”);返回视图();}@MauricoBello很高兴看到这一点。@MauricoBello-标记它作为另一个问题的答案。如何在C#web API中实现身份验证和基于角色的授权我用C#MVC5实现了这一点,这是正常的,但它不适用于web API C#MVC5