Я пытаюсь ограничить доступ к методам моего контроллера, через роли, традиционным способом, полный контроллер отклоняет аутентификацию ролей для всех пользователей всех ролей
Авторизация атрибута с несколькими ролями
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 («Index»), «Домой»), это должно происходить только при запуске
[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;
}
}