Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a user claim in asp.net mvc 4 razor view

Tags:

asp.net-mvc

How can I get a claim, given its type, of the current authenticate user in a Razor view?

I tried a few options, such as the following, but with no success:

(ClaimsPrincipal)User.Identity).FindFirst(ClaimTypes.NameIdentifier); }

Thank You, Miguel

like image 520
Miguel Moura Avatar asked Oct 22 '13 17:10

Miguel Moura


People also ask

Can you mix razor pages and MVC?

You can add support for Pages to any ASP.NET Core MVC app by simply adding a Pages folder and adding Razor Pages files to this folder. Razor Pages use the folder structure as a convention for routing requests.

What is Aspnetuserclaims?

Claims can be created from any user or identity data which can be issued using a trusted identity provider or ASP.NET Core identity. A claim is a name value pair that represents what the subject is, not what the subject can do.

What is claim in MVC?

The claim is a name-value pair that represents what the subject is or is not, instead of what the subject can and cannot do. The claim based authorization checks the value of the claim and allows access to the resource, based on that value.


1 Answers

Try casting to ClaimsIdentity. This works in my MVC5 project.

        @{
        var claimsIdentity = User.Identity as System.Security.Claims.ClaimsIdentity;

        if (claimsIdentity != null)
        {
            var c = claimsIdentity.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier);

            if (c != null)
            {
             <p>
                 @c.Type.ToString(); 
                 @c.Value.ToString();
             </p>   
            }
        }
    }
like image 62
Rick Rainey Avatar answered Oct 16 '22 15:10

Rick Rainey