Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve identity claim values in _Layout.cshtml

I am googling for this thing for quit a long time but still can't get proper answer. I am using identity claim for user authentication and I need some claim values in my _Layout.cshtml page. However I can retrieve custom identity claim values but not built in ones.

Here I set my identity:

 var ident = new ClaimsIdentity(
                new[] { 
                    // adding following 2 claim just for supporting default antiforgery provider
                    new Claim(ClaimTypes.NameIdentifier, user.LoginId),
                    new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),
                    new Claim(ClaimTypes.Name,user.UserName),
                    new Claim(ClaimTypes.Sid,user.UserId.ToString()),
                    new Claim("OperationType", user.OperationType.ToString()),
                    new Claim("ImageLink", user.ImageLink.ToString())

                },
                DefaultAuthenticationTypes.ApplicationCookie);
            var claimsPrincipal = new ClaimsPrincipal(ident);
            // Set current principal
            Thread.CurrentPrincipal = claimsPrincipal;

and my layout page code:

@using System.Security.Claims;
...........
@{  
    string userDesignation = ((ClaimsIdentity)User.Identity).FindFirst("OperationType").Value; ;
    string userImage = ((ClaimsIdentity)User.Identity).FindFirst("ImageLink").Value; ;

}

I can retrieve my custom claims(ImageLink,OperationType) values but couldn't able to retrieve (Name,Sid) with the same pattern. Some of answers I found that said about Extension methods. Is that only way for retrieve values or have any other way? Thanks in advance

like image 356
Parvez Avatar asked Dec 05 '25 02:12

Parvez


1 Answers

Please use threading namespace in top of your layout page

@using System.Threading;

and access your claim types as following

@{  
string userDesignation = ((ClaimsIdentity)User.Identity).FindFirst("OperationType").Value;
string userImage = ((ClaimsIdentity)User.Identity).FindFirst("ImageLink").Value;


var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;

    // Get the claims values
    var id= identity.Claims.Where(c => c.Type == ClaimTypes.Sid)
        .Select(c => c.Value).SingleOrDefault();
    var s = id;
//so on.......
}

But @Erik Philips is right. You should use those logic as partial.

like image 184
Md. Akhtar Uzzaman Avatar answered Dec 07 '25 19:12

Md. Akhtar Uzzaman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!