22

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

4 回答 4

30

假设您有附加到当前委托人的索赔。在你的 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

于 2016-08-24T14:23:53.123 回答
12

在剃须刀页面中的 .net core 2.2 中测试:

@User.FindFirst("nameOfClaim").Value

于 2020-05-01T22:36:32.697 回答
1

在 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
    }

ASP.NET Core MVC 中基于视图的授权

于 2019-10-29T02:37:44.497 回答
0

您可以在视图中使用以下代码实现此目的:

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
}

这种方式更好,因为它使用定义的策略,可以验证许多不同的值。

于 2022-01-09T09:52:39.353 回答