19

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.

Sknecht
  • 789
  • 2
  • 10
  • 27
  • I found the problem. I had a typo in the line where it sets the cookie: HttpContext.Authentication.SignInAsync("typo here", new ClaimsPrincipal(auth));. Sorry for the unnecessary work people. – Sknecht Aug 24 '16 at 14:54
  • Just a suggestion, it might be a bad idea to access claims by index.. Might want to use claim types as in JDupont's answer. – juunas Aug 24 '16 at 15:39
  • 1
    You are right it already caused an out of bounds once we removed a claim from the system. It is already a task on the board but got not jet around to it. – Sknecht Aug 25 '16 at 06:36

3 Answers3

29

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

Community
  • 1
  • 1
JDupont
  • 1,334
  • 9
  • 14
  • I first stumbled on the one you linked at the end, but I find that your answer is the better solution. Since creating an extention allows your to use it better throughout the most of the application. – Carsten Oct 08 '19 at 12:44
5

Tested in .net core 2.2 in the razor page :

@User.FindFirst("nameOfClaim").Value

MAK
  • 169
  • 2
  • 5
0

In Core 3.0, use view authorization

Startup.cs

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

Then inside the UI

    if ((AuthorizationService.AuthorizeAsync(User, "Claim_Name")).Result.Succeeded){
        //show ui element
    }

View-based authorization in ASP.NET Core MVC

Jeff
  • 550
  • 4
  • 13
  • See this related post with concerns about this policy based approach: https://stackoverflow.com/a/41348219/943435 – Roberto Mar 08 '20 at 06:46