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

时间:2018-12-29 18:29:15

标签: c# asp.net-mvc-5

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

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

    }

}

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

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(“索引”,“首页”), 这应该只在一开始就发生

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

2 个答案:

答案 0 :(得分:1)

根据提供的代码,您在身份验证票证的用户数据中添加角色(最后参数<div id="tabs-2"> <p>This is just a good Top for mid winter season.</p> {{#each longSleeve}} <div class="ui-state-highlight ui-corner-all"><strong> <img class="ads" src="{{this.picture_Url}}" alt=""> <br> Quantity : {{this.Qty}} <br> {{this.Price}} : </strong><a href="#">Buy</a> </div> {{/each}} <input id="addButton" class="button" type="button" name="" value=" + Add"> </div> <div id="addProductDiv" class="post hide"> <!-- This is the most important part with multer image upload the enctype part you dont need to forget --> <form class="" action="/projects" method="post" enctype="multipart/form-data"> <label for="avatar">Choose a file to upload:</label> <input type="file" id="avatar" name="picture_Url" accept="image/png, image/jpeg"> Type : <select class="brandOptions" name="typeOfCloth"> <option class="placeHolder" value="" selected="true" disabled="">SELECT TYPE</option> <option value="Cap">Cap</option> <option value="Long Sleeve">Long Sleeve</option> </select> Size : <input type="text" name="size" value=""> Quantity : <input type="number" name="qty" value=""> Price : <input type="text" name="price" value=""> <input class="button" type="submit" name="" value="Submit"> </form><br> <input id="back" class="backButton" type="submit" name="" value="Back"> </div> 。可以使用此用户数据。

默认情况下,FormsAuthenticationTicket适用于“用户”而不适用于“角色”,因此该属性 new FormsAuthenticationTicket()可以使用,但是[Authorize(Users = "model.Usuario")]会给您未授权的内容。

要使用角色,您需要在AuthTicket的[Authorize(Roles= "Adminstrador")]中添加角色。 在您的控制器中添加以下方法:-

HttpContext.User

您还可以为其创建授权过滤器,以便可以在您的应用程序中使用相同的过滤器。

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

答案 1 :(得分:0)

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

代替此:

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