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

How to authorize a method from one controller to one role or multiple roles without canceling the entire controller

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

Authorize Attribute with Multiple Roles

     using MBC.ServiciosUtilidad.CatalogoUS.Implementacion;
     using MBC.ServiciosEntidad.ReportesDmsES.Implementacion;
     using System.Web.Mvc;
     using MBC.Models.ReportDms;
     using PagedList;
     using System.Data;
     using System.Linq;
     using MBC.ModeloCanonico.Constantes;
     using System.Web.Security;
     using static MBC.ModeloCanonico.Constantes.CatalogoConstante;

  namespace MBC.Controllers.Report.Vehiculos
 {
[Authorize]
//[Authorize(Roles = CatalogoConstante.Rol.Administrador)]
public class ReportDmsVehiculosController : MasterController
{
    private readonly ICatalogoUSContract _servicioCatalogo;
    private readonly IReportesDmsESContrato _servicioReportesDms;

    //CONSTRUCTOR

    public ReportDmsVehiculosController()
    {
        _servicioCatalogo = new CatalogoUSImplementacion();
        _servicioReportesDms = new ReportesDmsESImplementacion();
    }
    //[Authorize(Roles = CatalogoConstante.Rol.Administrador)] 
    [AuthorizeRoles(Rol.Administrador)]
    public ActionResult ReportDmsVehiculos()
    {
        return View();
    }
}

namespace MBC.ModeloCanonico.Constantes
{
    public static class CatalogoConstante
    {
    public struct Rol
    {
        public const string Administrador = "Administrador";
        public const string RecursosHumanos = "Recursos Humanos";

    }

}

这是带有return消息的登录(),'access denied'

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();
}

出于某种原因,他一直将我发送到:RedirectToAction ("Index", "Home"), 这应该只发生在开始时

[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();
    }

这是注册用户的验证功能。 此class用于获取登录用户的信息,用作审计并在视图中显示一些数据。

    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;
        }
    }

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

默认情况下,FormsAuthenticationTicket 使用 "Users" 而不是 "Roles" 所以属性 [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、AuthorizeCore 和 HandleUnauthorizedRequest 方法 class,那么它将调用 OnAuthorization 方法,然后如果您在覆盖的 OnAuthorization 方法中调用 base.OnAuthorization(filterContext) 方法,则它会调用 AuthorizeCore 方法,如果 return 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();
}