locked
How to attach claim permission to action like roles RRS feed

  • Question

  • User264732274 posted

    when we use role then we decorate action with single or multiple role names. if user has that role then user can access that action otherwise not like below code.

    [AuthLog(Roles = "Manager")]
    public ActionResult Create()
    {
        var Product = new ProductMaster();
        return View(Product);
    }

    i guess when we work with identity and claims then there must some way to attach role or permission to each action like role. if anything such exist then please share the idea how to implement this with good example code or provide article links. thanks

    Wednesday, September 21, 2016 8:57 PM

Answers

  • User283571144 posted

    Hi sudip_inn,

    i guess when we work with identity and claims then there must some way to attach role or permission to each action like role. if anything such exist then please share the idea how to implement this with good example code or provide article links. thanks

    According to your description, I suggest you could define a class deriving from AuthorizeAttribute(this class will check the role) to check the claim value as same as auth class.

    Like below:

    More details, you could refer to follow codes:

     public class ClaimsAuthorizeAttribute : AuthorizeAttribute
    
        {
            private string claimType;
            private string claimValue;
            public ClaimsAuthorizeAttribute(string type, string value)
            {
                this.claimType = type;
                this.claimValue = value;
            }
            public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
            {
                var user = filterContext.HttpContext.User as ClaimsPrincipal;
                if (user != null && user.HasClaim(claimType, claimValue))
                {
                    base.OnAuthorization(filterContext);
                }
                else
                {
                    base.HandleUnauthorizedRequest(filterContext);
                }
            }

    In controllers:

      [ClaimsAuthorizeAttribute("E-mail", "aaa")]
            [Authorize(Roles ="amdmin")]
            public ActionResult About()
            {
                ViewBag.Message = "Your application description page.";
                ViewBag.ImgPath = "123";
                var userId = User.Identity.GetUserId();
                ApplicationUserManager UserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
                var claims =  UserManager.GetClaims(userId);
                var someClaim = claims.FirstOrDefault(c => c.Type == "E-mail");
                ViewBag.Email = someClaim.Value;
                return View();
            }

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, September 22, 2016 5:22 AM