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.
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.
假设您有附加到当前委托人的索赔。在你的 Razor 视图中:
@((ClaimsIdentity) User.Identity)
这将使您能够访问当前用户的 ClaimsIdentity。为了使您的声明保持干净,您可能需要创建一个扩展方法来搜索声明。
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;
}
然后你可以访问任何你想要的声明:
@((ClaimsIdentity) User.Identity).GetSpecificClaim("someclaimtype")
希望这可以帮助。
在剃刀视图中快速搜索声明身份提出了一个类似的问题和答案: MVC 5 Access Claims Identity User Data
在剃须刀页面中的 .net core 2.2 中测试:
@User.FindFirst("nameOfClaim").Value
在 Core 3.0 中,使用视图授权
启动.cs
services.AddAuthorization(options =>
{
options.AddPolicy("Claim_Name", x => x.RequireClaim("Claim_Name"));
});
然后在UI里面
if ((AuthorizationService.AuthorizeAsync(User, "Claim_Name")).Result.Succeeded){
//show ui element
}
您可以在视图中使用以下代码实现此目的:
if(User.FindFirst("MyClaim")?.Value == "some_value")
{
... Show concerned UI block
}
尽管如此,如果您使用策略(因为这是推荐的方式),我建议您在 Startup.cs/Program.cs 中定义策略并使用注入IAuthorizationService
来调用AuthorizeAsync
:
if((await AuthorizationService.AuthorizeAsync(User, "MyClaim")).Succeeded)
{
... Show concerned UI block
}
这种方式更好,因为它使用定义的策略,可以验证许多不同的值。