ASP.NET Core 3.1:User.Identity.Name在API控制器中为空,但存在声明名称 [英] ASP.NET Core 3.1: User.Identity.Name is empty in API Controller, but claim name is present

查看:17
本文介绍了ASP.NET Core 3.1:User.Identity.Name在API控制器中为空,但存在声明名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Identity Server添加到现有项目中。基本上我已经准备好了,但是当我向API发出请求时,User.Identity.Name为空。但是,User.Identity.Claims包含名称Claim:

我知道通过HttpContext.User.FindFirstValue(ClaimTypes.Name)获取用户名的方法,但它需要大量的代码重构,所以我宁愿避免这种方式。

我在Identity服务器中配置ApiResources的方式如下:

public static IEnumerable<ApiResource> ApiResources => new[]
{
    new ApiResource
    {
        Name = "my-api",
        DisplayName = "My API",
        Description = "My API",
        Scopes = new List<string> { "my-api"},
        UserClaims = new List<string> {
            JwtClaimTypes.Email,
            JwtClaimTypes.Name,
            JwtClaimTypes.Subject,
            JwtClaimTypes.Role,
        }
    }
};

和客户端:

public static IEnumerable<Client> Clients =>
    new List<Client>
    {
        new Client
        {
            // ...
            AllowedScopes =
            {
                IdentityServerConstants.StandardScopes.OpenId,
                IdentityServerConstants.StandardScopes.Profile,
                IdentityServerConstants.StandardScopes.Email,
                "name",
                "roles",
                "my-api",
            }
        }
    };

API项目中的身份验证设置:

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
    options.Authority = config["IdentityServer:Domain"];

    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidIssuer = config["IdentityServer:Domain"],
        ValidateAudience = false
    };
});

services.AddAuthorization(options =>
{
    options.AddPolicy("ApiScope", policy =>
    {
        policy.RequireAuthenticatedUser();
        policy.RequireClaim("scope", "my-api");
    });
});

请指教我做错了什么?

推荐答案

问题是微软和OpenID Connect对声明的名称有不同的看法。因此,您需要做的是通过以下方式告诉系统名称声明的名称是什么:

    .AddJwtBearer(opt =>
    {
        ...      
        opt.TokenValidationParameters.RoleClaimType = "roles";
        opt.TokenValidationParameters.NameClaimType = "name";
        ...
    }

这篇关于ASP.NET Core 3.1:User.Identity.Name在API控制器中为空,但存在声明名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆