How to get claim inside Asp.Net Core Razor View

41.5k views Asked by At

I did it in my rc1 project like:

User.Claims.ElementAt(#).Value

But after I switched to rtm it wouldn’t work anymore. When I debug the Razor view the object looks the same but User.Claims is just empty. Any idea what the reason could be.

4

There are 4 answers

2
JDupont On BEST ANSWER

Assuming you have claims attached to the current principal. In your Razor view:

@((ClaimsIdentity) User.Identity)

This will give you access to the ClaimsIdentity of the current user. In an effort to keep your claims fetching clean you may want to create an extension method for searching claims.

public static string GetSpecificClaim(this ClaimsIdentity claimsIdentity, string claimType)
{
    var claim = claimsIdentity.Claims.FirstOrDefault(x => x.Type == claimType);

    return (claim != null) ? claim.Value : string.Empty;
}

Then you can just access whatever claim you want with:

@((ClaimsIdentity) User.Identity).GetSpecificClaim("someclaimtype")

Hope this helps.

Quick search for claims identity in razor view came up with a similar question and answer: MVC 5 Access Claims Identity User Data

2
Jeff On

In Core 3.0, use view authorization.

In Startup.cs:

    services.AddAuthorization(options =>
    {
        options.AddPolicy("Policy_Name", x => x.RequireClaim("Policy_Name"));
    });

At the top of your UI file where you are inserting the conditional element, insert:

@using Microsoft.AspNetCore.Authorization
@inject IAuthorizationService AuthorizationService

Then inside the body use:

    @if ((await AuthorizationService.AuthorizeAsync(User, "Policy_Name")).Succeeded){
        //show ui element
    }

View-based authorization in ASP.NET Core MVC

1
MAK On

Tested in .net core 2.2 in the razor page :

@User.FindFirst("nameOfClaim").Value

0
cdie On

You can achieve this with the following code in your view :

if(User.FindFirst("MyClaim")?.Value == "some_value")
{
  ... Show concerned UI block
}

Altough, if you use policies (as it's the recommended way), I suggest to define policies in your Startup.cs/Program.cs and use injected IAuthorizationService to call AuthorizeAsync :

if((await AuthorizationService.AuthorizeAsync(User, "MyClaim")).Succeeded)
{
   ... Show concerned UI block
}

This way is better as it use defined policies, which can validates many different values.