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












1















I am trying to restrict access to my controller's methods, through roles, in the traditional way, the complete controller rejects the authentication of roles for all users of all roles



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

}

}


This is the login () with a return message, '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();
}


for some reason he keeps sending me to: RedirectToAction ("Index", "Home"),
This should only happen at the start



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


This is the verification function of the registered user.
This class is used to obtain the information of the logged in user, to use as an audit and to show some data in the view.



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









share|improve this question

























  • Question is not clear, as per provided code action method "ReportDmsVehiculos" is accessible to user having role "Administrador".

    – Ashish Mishra
    Dec 30 '18 at 6:48











  • That is exactly what does not work, it is blocked for all users, now I have to leave it without a specific role.

    – Maurico Bello
    Jan 2 at 13:43











  • Please try with [Authorize("Administrador") instead of [AuthorizeRoles(Rol.Administrador)] and see if it works. Not sure about AuthorizeRoles class. Please also share your AuthorizeRoles class, may be some thing has been missed out in that class.

    – Ashish Mishra
    Jan 2 at 14:42











  • That was my first option but it does not work.

    – Maurico Bello
    Jan 2 at 16:24











  • When the user logs in, how do I identify the role, with which is it authenticated?

    – Maurico Bello
    Jan 3 at 14:06
















1















I am trying to restrict access to my controller's methods, through roles, in the traditional way, the complete controller rejects the authentication of roles for all users of all roles



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

}

}


This is the login () with a return message, '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();
}


for some reason he keeps sending me to: RedirectToAction ("Index", "Home"),
This should only happen at the start



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


This is the verification function of the registered user.
This class is used to obtain the information of the logged in user, to use as an audit and to show some data in the view.



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









share|improve this question

























  • Question is not clear, as per provided code action method "ReportDmsVehiculos" is accessible to user having role "Administrador".

    – Ashish Mishra
    Dec 30 '18 at 6:48











  • That is exactly what does not work, it is blocked for all users, now I have to leave it without a specific role.

    – Maurico Bello
    Jan 2 at 13:43











  • Please try with [Authorize("Administrador") instead of [AuthorizeRoles(Rol.Administrador)] and see if it works. Not sure about AuthorizeRoles class. Please also share your AuthorizeRoles class, may be some thing has been missed out in that class.

    – Ashish Mishra
    Jan 2 at 14:42











  • That was my first option but it does not work.

    – Maurico Bello
    Jan 2 at 16:24











  • When the user logs in, how do I identify the role, with which is it authenticated?

    – Maurico Bello
    Jan 3 at 14:06














1












1








1


1






I am trying to restrict access to my controller's methods, through roles, in the traditional way, the complete controller rejects the authentication of roles for all users of all roles



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

}

}


This is the login () with a return message, '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();
}


for some reason he keeps sending me to: RedirectToAction ("Index", "Home"),
This should only happen at the start



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


This is the verification function of the registered user.
This class is used to obtain the information of the logged in user, to use as an audit and to show some data in the view.



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









share|improve this question
















I am trying to restrict access to my controller's methods, through roles, in the traditional way, the complete controller rejects the authentication of roles for all users of all roles



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

}

}


This is the login () with a return message, '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();
}


for some reason he keeps sending me to: RedirectToAction ("Index", "Home"),
This should only happen at the start



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


This is the verification function of the registered user.
This class is used to obtain the information of the logged in user, to use as an audit and to show some data in the view.



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






c# asp.net-mvc-5






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 5 at 14:13







Maurico Bello

















asked Dec 29 '18 at 18:29









Maurico BelloMaurico Bello

85




85













  • Question is not clear, as per provided code action method "ReportDmsVehiculos" is accessible to user having role "Administrador".

    – Ashish Mishra
    Dec 30 '18 at 6:48











  • That is exactly what does not work, it is blocked for all users, now I have to leave it without a specific role.

    – Maurico Bello
    Jan 2 at 13:43











  • Please try with [Authorize("Administrador") instead of [AuthorizeRoles(Rol.Administrador)] and see if it works. Not sure about AuthorizeRoles class. Please also share your AuthorizeRoles class, may be some thing has been missed out in that class.

    – Ashish Mishra
    Jan 2 at 14:42











  • That was my first option but it does not work.

    – Maurico Bello
    Jan 2 at 16:24











  • When the user logs in, how do I identify the role, with which is it authenticated?

    – Maurico Bello
    Jan 3 at 14:06



















  • Question is not clear, as per provided code action method "ReportDmsVehiculos" is accessible to user having role "Administrador".

    – Ashish Mishra
    Dec 30 '18 at 6:48











  • That is exactly what does not work, it is blocked for all users, now I have to leave it without a specific role.

    – Maurico Bello
    Jan 2 at 13:43











  • Please try with [Authorize("Administrador") instead of [AuthorizeRoles(Rol.Administrador)] and see if it works. Not sure about AuthorizeRoles class. Please also share your AuthorizeRoles class, may be some thing has been missed out in that class.

    – Ashish Mishra
    Jan 2 at 14:42











  • That was my first option but it does not work.

    – Maurico Bello
    Jan 2 at 16:24











  • When the user logs in, how do I identify the role, with which is it authenticated?

    – Maurico Bello
    Jan 3 at 14:06

















Question is not clear, as per provided code action method "ReportDmsVehiculos" is accessible to user having role "Administrador".

– Ashish Mishra
Dec 30 '18 at 6:48





Question is not clear, as per provided code action method "ReportDmsVehiculos" is accessible to user having role "Administrador".

– Ashish Mishra
Dec 30 '18 at 6:48













That is exactly what does not work, it is blocked for all users, now I have to leave it without a specific role.

– Maurico Bello
Jan 2 at 13:43





That is exactly what does not work, it is blocked for all users, now I have to leave it without a specific role.

– Maurico Bello
Jan 2 at 13:43













Please try with [Authorize("Administrador") instead of [AuthorizeRoles(Rol.Administrador)] and see if it works. Not sure about AuthorizeRoles class. Please also share your AuthorizeRoles class, may be some thing has been missed out in that class.

– Ashish Mishra
Jan 2 at 14:42





Please try with [Authorize("Administrador") instead of [AuthorizeRoles(Rol.Administrador)] and see if it works. Not sure about AuthorizeRoles class. Please also share your AuthorizeRoles class, may be some thing has been missed out in that class.

– Ashish Mishra
Jan 2 at 14:42













That was my first option but it does not work.

– Maurico Bello
Jan 2 at 16:24





That was my first option but it does not work.

– Maurico Bello
Jan 2 at 16:24













When the user logs in, how do I identify the role, with which is it authenticated?

– Maurico Bello
Jan 3 at 14:06





When the user logs in, how do I identify the role, with which is it authenticated?

– Maurico Bello
Jan 3 at 14:06












2 Answers
2






active

oldest

votes


















1














As per provided code your adding Roles in user data of authentication ticket (Last Parameter of new FormsAuthenticationTicket(). This user data can be utilized.



By default FormsAuthenticationTicket works with "Users" not with "Roles" so attribute
[Authorize(Users = "model.Usuario")] will work but [Authorize(Roles= "Adminstrador")] will give you Unauthorized.



To work with roles you need to add roles in HttpContext.User from AuthTicket.
Add below method in your controller:-



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


You can also create Authorization filter for same so that same can be used across your application.



If you override OnAuthorization, AuthorizeCore and HandleUnauthorizedRequest methods in your custom authorization class, then it will call OnAuthorization method, then if you call base.OnAuthorization(filterContext) method in overriden OnAuthorization method, then it will call AuthorizeCore method, if that return false, then it will call HandleUnauthorizedRequest method.






share|improve this answer


























  • I tried but it does not work, for some reason it sends me to: RedirectToAction ("Index", "Home"), This should only happen at Start.

    – Maurico Bello
    Jan 3 at 23:01











  • I just added some changes to the first code that I published.

    – Maurico Bello
    Jan 3 at 23:13











  • ((ClaimsIdentity)HttpContext.User.Identity).AddClaim(new Claim(ClaimTypes.Role, model.Roles)); I use it in both functions, one at a time and then in both, it does not work.

    – Maurico Bello
    Jan 3 at 23:33













  • Currently, the method of action is as follows: [Authorize(Roles = "Administrador")] public ActionResult ReportDmsVehiculos() { return View(); }

    – Maurico Bello
    Jan 3 at 23:40











  • Please see the updated solution. No need to add Claims.

    – Ashish Mishra
    Jan 4 at 5:46



















0














User this for code returning view with respect to a Specific role:



Instead of This:



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

return View();
}


Try This:



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

return View();
}





share|improve this answer
























  • Excellent is just what I needed. Thank you..: 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(); }

    – Maurico Bello
    Jan 5 at 14:05











  • @MauricoBello Good To see that. 😍😍😇

    – Rehan
    Jan 5 at 15:16













  • @MauricoBello - Mark it as a answer 👍. -Thanks

    – Rehan
    Jan 5 at 15:18













Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53972268%2fhow-to-authorize-a-method-from-one-controller-to-one-role-or-multiple-roles-with%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














As per provided code your adding Roles in user data of authentication ticket (Last Parameter of new FormsAuthenticationTicket(). This user data can be utilized.



By default FormsAuthenticationTicket works with "Users" not with "Roles" so attribute
[Authorize(Users = "model.Usuario")] will work but [Authorize(Roles= "Adminstrador")] will give you Unauthorized.



To work with roles you need to add roles in HttpContext.User from AuthTicket.
Add below method in your controller:-



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


You can also create Authorization filter for same so that same can be used across your application.



If you override OnAuthorization, AuthorizeCore and HandleUnauthorizedRequest methods in your custom authorization class, then it will call OnAuthorization method, then if you call base.OnAuthorization(filterContext) method in overriden OnAuthorization method, then it will call AuthorizeCore method, if that return false, then it will call HandleUnauthorizedRequest method.






share|improve this answer


























  • I tried but it does not work, for some reason it sends me to: RedirectToAction ("Index", "Home"), This should only happen at Start.

    – Maurico Bello
    Jan 3 at 23:01











  • I just added some changes to the first code that I published.

    – Maurico Bello
    Jan 3 at 23:13











  • ((ClaimsIdentity)HttpContext.User.Identity).AddClaim(new Claim(ClaimTypes.Role, model.Roles)); I use it in both functions, one at a time and then in both, it does not work.

    – Maurico Bello
    Jan 3 at 23:33













  • Currently, the method of action is as follows: [Authorize(Roles = "Administrador")] public ActionResult ReportDmsVehiculos() { return View(); }

    – Maurico Bello
    Jan 3 at 23:40











  • Please see the updated solution. No need to add Claims.

    – Ashish Mishra
    Jan 4 at 5:46
















1














As per provided code your adding Roles in user data of authentication ticket (Last Parameter of new FormsAuthenticationTicket(). This user data can be utilized.



By default FormsAuthenticationTicket works with "Users" not with "Roles" so attribute
[Authorize(Users = "model.Usuario")] will work but [Authorize(Roles= "Adminstrador")] will give you Unauthorized.



To work with roles you need to add roles in HttpContext.User from AuthTicket.
Add below method in your controller:-



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


You can also create Authorization filter for same so that same can be used across your application.



If you override OnAuthorization, AuthorizeCore and HandleUnauthorizedRequest methods in your custom authorization class, then it will call OnAuthorization method, then if you call base.OnAuthorization(filterContext) method in overriden OnAuthorization method, then it will call AuthorizeCore method, if that return false, then it will call HandleUnauthorizedRequest method.






share|improve this answer


























  • I tried but it does not work, for some reason it sends me to: RedirectToAction ("Index", "Home"), This should only happen at Start.

    – Maurico Bello
    Jan 3 at 23:01











  • I just added some changes to the first code that I published.

    – Maurico Bello
    Jan 3 at 23:13











  • ((ClaimsIdentity)HttpContext.User.Identity).AddClaim(new Claim(ClaimTypes.Role, model.Roles)); I use it in both functions, one at a time and then in both, it does not work.

    – Maurico Bello
    Jan 3 at 23:33













  • Currently, the method of action is as follows: [Authorize(Roles = "Administrador")] public ActionResult ReportDmsVehiculos() { return View(); }

    – Maurico Bello
    Jan 3 at 23:40











  • Please see the updated solution. No need to add Claims.

    – Ashish Mishra
    Jan 4 at 5:46














1












1








1







As per provided code your adding Roles in user data of authentication ticket (Last Parameter of new FormsAuthenticationTicket(). This user data can be utilized.



By default FormsAuthenticationTicket works with "Users" not with "Roles" so attribute
[Authorize(Users = "model.Usuario")] will work but [Authorize(Roles= "Adminstrador")] will give you Unauthorized.



To work with roles you need to add roles in HttpContext.User from AuthTicket.
Add below method in your controller:-



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


You can also create Authorization filter for same so that same can be used across your application.



If you override OnAuthorization, AuthorizeCore and HandleUnauthorizedRequest methods in your custom authorization class, then it will call OnAuthorization method, then if you call base.OnAuthorization(filterContext) method in overriden OnAuthorization method, then it will call AuthorizeCore method, if that return false, then it will call HandleUnauthorizedRequest method.






share|improve this answer















As per provided code your adding Roles in user data of authentication ticket (Last Parameter of new FormsAuthenticationTicket(). This user data can be utilized.



By default FormsAuthenticationTicket works with "Users" not with "Roles" so attribute
[Authorize(Users = "model.Usuario")] will work but [Authorize(Roles= "Adminstrador")] will give you Unauthorized.



To work with roles you need to add roles in HttpContext.User from AuthTicket.
Add below method in your controller:-



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


You can also create Authorization filter for same so that same can be used across your application.



If you override OnAuthorization, AuthorizeCore and HandleUnauthorizedRequest methods in your custom authorization class, then it will call OnAuthorization method, then if you call base.OnAuthorization(filterContext) method in overriden OnAuthorization method, then it will call AuthorizeCore method, if that return false, then it will call HandleUnauthorizedRequest method.







share|improve this answer














share|improve this answer



share|improve this answer








edited Jan 5 at 7:01

























answered Jan 3 at 16:24









Ashish MishraAshish Mishra

1658




1658













  • I tried but it does not work, for some reason it sends me to: RedirectToAction ("Index", "Home"), This should only happen at Start.

    – Maurico Bello
    Jan 3 at 23:01











  • I just added some changes to the first code that I published.

    – Maurico Bello
    Jan 3 at 23:13











  • ((ClaimsIdentity)HttpContext.User.Identity).AddClaim(new Claim(ClaimTypes.Role, model.Roles)); I use it in both functions, one at a time and then in both, it does not work.

    – Maurico Bello
    Jan 3 at 23:33













  • Currently, the method of action is as follows: [Authorize(Roles = "Administrador")] public ActionResult ReportDmsVehiculos() { return View(); }

    – Maurico Bello
    Jan 3 at 23:40











  • Please see the updated solution. No need to add Claims.

    – Ashish Mishra
    Jan 4 at 5:46



















  • I tried but it does not work, for some reason it sends me to: RedirectToAction ("Index", "Home"), This should only happen at Start.

    – Maurico Bello
    Jan 3 at 23:01











  • I just added some changes to the first code that I published.

    – Maurico Bello
    Jan 3 at 23:13











  • ((ClaimsIdentity)HttpContext.User.Identity).AddClaim(new Claim(ClaimTypes.Role, model.Roles)); I use it in both functions, one at a time and then in both, it does not work.

    – Maurico Bello
    Jan 3 at 23:33













  • Currently, the method of action is as follows: [Authorize(Roles = "Administrador")] public ActionResult ReportDmsVehiculos() { return View(); }

    – Maurico Bello
    Jan 3 at 23:40











  • Please see the updated solution. No need to add Claims.

    – Ashish Mishra
    Jan 4 at 5:46

















I tried but it does not work, for some reason it sends me to: RedirectToAction ("Index", "Home"), This should only happen at Start.

– Maurico Bello
Jan 3 at 23:01





I tried but it does not work, for some reason it sends me to: RedirectToAction ("Index", "Home"), This should only happen at Start.

– Maurico Bello
Jan 3 at 23:01













I just added some changes to the first code that I published.

– Maurico Bello
Jan 3 at 23:13





I just added some changes to the first code that I published.

– Maurico Bello
Jan 3 at 23:13













((ClaimsIdentity)HttpContext.User.Identity).AddClaim(new Claim(ClaimTypes.Role, model.Roles)); I use it in both functions, one at a time and then in both, it does not work.

– Maurico Bello
Jan 3 at 23:33







((ClaimsIdentity)HttpContext.User.Identity).AddClaim(new Claim(ClaimTypes.Role, model.Roles)); I use it in both functions, one at a time and then in both, it does not work.

– Maurico Bello
Jan 3 at 23:33















Currently, the method of action is as follows: [Authorize(Roles = "Administrador")] public ActionResult ReportDmsVehiculos() { return View(); }

– Maurico Bello
Jan 3 at 23:40





Currently, the method of action is as follows: [Authorize(Roles = "Administrador")] public ActionResult ReportDmsVehiculos() { return View(); }

– Maurico Bello
Jan 3 at 23:40













Please see the updated solution. No need to add Claims.

– Ashish Mishra
Jan 4 at 5:46





Please see the updated solution. No need to add Claims.

– Ashish Mishra
Jan 4 at 5:46













0














User this for code returning view with respect to a Specific role:



Instead of This:



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

return View();
}


Try This:



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

return View();
}





share|improve this answer
























  • Excellent is just what I needed. Thank you..: 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(); }

    – Maurico Bello
    Jan 5 at 14:05











  • @MauricoBello Good To see that. 😍😍😇

    – Rehan
    Jan 5 at 15:16













  • @MauricoBello - Mark it as a answer 👍. -Thanks

    – Rehan
    Jan 5 at 15:18


















0














User this for code returning view with respect to a Specific role:



Instead of This:



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

return View();
}


Try This:



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

return View();
}





share|improve this answer
























  • Excellent is just what I needed. Thank you..: 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(); }

    – Maurico Bello
    Jan 5 at 14:05











  • @MauricoBello Good To see that. 😍😍😇

    – Rehan
    Jan 5 at 15:16













  • @MauricoBello - Mark it as a answer 👍. -Thanks

    – Rehan
    Jan 5 at 15:18
















0












0








0







User this for code returning view with respect to a Specific role:



Instead of This:



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

return View();
}


Try This:



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

return View();
}





share|improve this answer













User this for code returning view with respect to a Specific role:



Instead of This:



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

return View();
}


Try This:



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

return View();
}






share|improve this answer












share|improve this answer



share|improve this answer










answered Jan 5 at 8:33









RehanRehan

487113




487113













  • Excellent is just what I needed. Thank you..: 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(); }

    – Maurico Bello
    Jan 5 at 14:05











  • @MauricoBello Good To see that. 😍😍😇

    – Rehan
    Jan 5 at 15:16













  • @MauricoBello - Mark it as a answer 👍. -Thanks

    – Rehan
    Jan 5 at 15:18





















  • Excellent is just what I needed. Thank you..: 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(); }

    – Maurico Bello
    Jan 5 at 14:05











  • @MauricoBello Good To see that. 😍😍😇

    – Rehan
    Jan 5 at 15:16













  • @MauricoBello - Mark it as a answer 👍. -Thanks

    – Rehan
    Jan 5 at 15:18



















Excellent is just what I needed. Thank you..: 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(); }

– Maurico Bello
Jan 5 at 14:05





Excellent is just what I needed. Thank you..: 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(); }

– Maurico Bello
Jan 5 at 14:05













@MauricoBello Good To see that. 😍😍😇

– Rehan
Jan 5 at 15:16







@MauricoBello Good To see that. 😍😍😇

– Rehan
Jan 5 at 15:16















@MauricoBello - Mark it as a answer 👍. -Thanks

– Rehan
Jan 5 at 15:18







@MauricoBello - Mark it as a answer 👍. -Thanks

– Rehan
Jan 5 at 15:18




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53972268%2fhow-to-authorize-a-method-from-one-controller-to-one-role-or-multiple-roles-with%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Mossoró

Error while reading .h5 file using the rhdf5 package in R

Pushsharp Apns notification error: 'InvalidToken'