How to get claim inside Asp.Net Core Razor View

让人想犯罪 __ 提交于 2019-12-18 04:34:32

问题


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.


回答1:


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:


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



来源:https://stackoverflow.com/questions/39125347/how-to-get-claim-inside-asp-net-core-razor-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!