OpenIddict 在令牌响应中获取用户 ID

Ada*_*dam 5 asp.net-core-mvc openid-connect aspnet-contrib asp.net-core openiddict

将 ASP.NET Core 与 OpenIddict 密码授予结合使用。

当调用身份验证端点时,我得到以下信息:

{
  "token_type": "Bearer",
  "access_token": "eyJhbGciOiJ...",
  "expires_in": 1800
}
Run Code Online (Sandbox Code Playgroud)

如何在响应中包含用户 ID?我可以在解码的令牌中看到它,但我的用户应用程序不会对其进行解码。

Kév*_*let 4

如何在响应中包含用户 ID?

理想情况下,请考虑使用身份令牌(根据定义始终是 JWT),当您指定 时,由 OpenIddict 返回scope=openid

或者,您还可以启用 userinfo 端点并发送 userinfo 请求以取回sub包含用户标识符的声明:http://openid.net/specs/openid-connect-core-1_0.html#UserInfo

如果您确实更喜欢将用户标识符作为令牌响应属性返回,则有两种选择:

使用特殊的“公共”属性(在您的授权控制器中,在其中创建身份验证票证):

ticket.SetProperty("user_id" + OpenIddictConstants.PropertyTypes.String, user.Id);
Run Code Online (Sandbox Code Playgroud)

注意:OpenIddictConstants.PropertyTypes.String是一个特殊后缀,表示添加到票证中的身份验证属性可以作为令牌响应的一部分公开。如果您希望将标识符作为 JSON 数字或更复杂的 JSON 结构返回,则可以使用其他常量。

使用事件模型(在 Startup.cs 中):

services.AddOpenIddict()

    // Register the OpenIddict core services.
    .AddCore(options =>
    {
        // ...
    })

    // Register the OpenIddict server handler.
    .AddServer(options =>
    {
        // ...

        options.AddEventHandler<OpenIddictServerEvents.ApplyTokenResponse>(
            notification =>
            {
                if (string.IsNullOrEmpty(notification.Context.Error))
                {
                    var principal = notification.Context.Ticket.Principal;
                    var response = notification.Context.Response;
                    response["user_id"] = principal.FindFirst(OpenIddictConstants.Claims.Subject).Value;
                }

                return Task.FromResult(OpenIddictServerEventState.Unhandled);
            });
    })

    // Register the OpenIddict validation handler.
    .AddValidation();
Run Code Online (Sandbox Code Playgroud)