IdentityServer4 通过 AccessToken 获取 UserClaims

实现效果:通过生成的access_token获取用户的一些信息,这样客户端请求的时候,不需要传递用户信息了。

示例配置:

public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentityServer()
        .AddTemporarySigningCredential()
        .AddInMemoryIdentityResources(new List<IdentityResource>
        {
            new IdentityResources.OpenId(), //必须要添加,否则报无效的scope错误
            new IdentityResources.Profile(),
        })
        .AddInMemoryApiResources(new List<ApiResource>
        {
            new ApiResource("api1", "My API")
        })
        .AddInMemoryClients(new List<Client>
        {
            new Client
            {
                ClientId = "client",
                AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,

                ClientSecrets =
                {
                    new Secret("secret".Sha256())
                },
                AllowedScopes = 
                { 
                  "api1",
                  IdentityServerConstants.StandardScopes.OpenId, //必须要添加,否则报forbidden错误
                  IdentityServerConstants.StandardScopes.Profile
                }
            }
        });
}

Http 调用示例:

GET /connect/userinfo
Authorization: Bearer <access_token>


HTTP/1.1 200 OK
Content-Type: application/json

{
    "sub": "248289761001",
    "name": "Bob Smith",
    "given_name": "Bob",
    "family_name": "Smith",
    "role": [
        "user",
        "admin"
    ]
}

UserInfoClient调用示例:

var token = "";
var client = new DiscoveryClient(_appSettings.IssuerUri);
client.Policy.RequireHttps = false;
var disco = await client.GetAsync();
var userInfoClient = new UserInfoClient(doc.UserInfoEndpoint);

var response = await userInfoClient.GetAsync(token);
var claims = response.Claims;

参考资料:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值