简体   繁体   English

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

[英]OpenIddict Get User Id in the token Response

Using ASP.NET Core with OpenIddict password grant. 使用ASP.NET Core和OpenIddict密码授予。

When calling an authentication end point, I am getting this: 在调用身份验证终结点时,我得到了这个:

{
  "token_type": "Bearer",
  "access_token": "eyJhbGciOiJ...",
  "expires_in": 1800
}

How can I include the user id in the response? 如何在响应中包含用户ID? I can see it in the decoded token, but my user app will not be decoding it. 我可以在解码的令牌中看到它,但我的用户应用程序不会解码它。

How can I include the user id in the response? 如何在响应中包含用户ID?

Ideally, consider using the identity token - always a JWT by definition - returned by OpenIddict when you specify scope=openid . 理想情况下,在指定scope=openid时,请考虑使用OpenIddict返回的标识令牌 - 永远是JWT。

Alternatively, you can also enable the userinfo endpoint and send a userinfo request to get back a sub claim containing the user identifier: http://openid.net/specs/openid-connect-core-1_0.html#UserInfo . 或者,您也可以启用userinfo端点并发送userinfo请求以获取包含用户标识符的sub声明: http//openid.net/specs/openid-connect-core-1_0.html#UserInfo

If you really prefer returning the user identifier as a token response property, you have two options: 如果您真的更喜欢将用户标识符作为令牌响应属性返回,那么您有两个选择:

Using a special "public" property (in your authorization controller, where authentication tickets are created): 使用特殊的“公共”属性(在授权控制器中,创建身份验证票证):

ticket.SetProperty("user_id" + OpenIddictConstants.PropertyTypes.String, user.Id);

Note: OpenIddictConstants.PropertyTypes.String is a special suffix indicating the authentication property added to the ticket can be exposed as part of the token response. 注意: OpenIddictConstants.PropertyTypes.String是一个特殊后缀,表示添加到OpenIddictConstants.PropertyTypes.String的身份验证属性可以作为令牌响应的一部分公开。 Other constants are available if you prefer returning your identifier as a JSON number or a more complex JSON structure. 如果您希望将标识符作为JSON编号或更复杂的JSON结构返回,则可以使用其他常量。

Using the events model (in Startup.cs): 使用事件模型(在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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM