首页 > 解决方案 > IdentityServer4 - RequestedClaimTypes 为空

问题描述

来自 IdentityServer 4 文档: 如果请求的范围是身份资源,则 RequestedClaimTypes 中的声明将根据 IdentityResource 中定义的用户声明类型填充

这是我的身份资源:

return new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
                new IdentityResources.Phone(),
                new IdentityResources.Email(),
                new IdentityResource(ScopeConstants.Roles, new List<string> { JwtClaimTypes.Role })
            };

这是我的客户

AllowedScopes = {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        IdentityServerConstants.StandardScopes.Phone,
                        IdentityServerConstants.StandardScopes.Email,
                        ScopeConstants.Roles
                    },

ProfileService - GetProfileDataAsync 方法:

public async Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        var sub = context.Subject.GetSubjectId();
        var user = await _userManager.FindByIdAsync(sub);
        var principal = await _claimsFactory.CreateAsync(user);

        var claims = principal.Claims.ToList();
        claims = claims.Where(claim => context.RequestedClaimTypes.Contains(claim.Type)).ToList();

        if (user.Configuration != null)
            claims.Add(new Claim(PropertyConstants.Configuration, user.Configuration));

        context.IssuedClaims = claims;
    }

principal.claims.ToList() 列出了所有声明,但 context.RequestedClaimTypes 为空,因此 context.RequestedClaimTypes.Contains(claim.Type)) 的过滤器不返回任何声明。

客户端配置:

让 header = new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' });

let params = new HttpParams()
    .append('username', userName)
    .append('password', password)
    .append('grant_type', 'password')
    .append('scope', 'email offline_access openid phone profile roles api_resource')
    .append('resource', window.location.origin)
    .append('client_id', 'test_spa');

let requestBody = params.toString();

return this.http.post<T>(this.loginUrl, requestBody, { headers: header });

响应类型:

export interface LoginResponse {
    access_token: string;
    token_type: string;
    refresh_token: string;
    expires_in: number;
}

有人表示添加 AlwaysIncludeUserClaimsInIdToken = true 可以解决问题 - 我试过了,但没有。

我在这里想念什么?请帮忙。

标签: identityserver4claims-based-identity

解决方案


推荐阅读