oauth-2.0 - 如何添加使用 OpenIddict 请求 token 时返回的自定义声明?

标签 oauth-2.0 asp.net-core openiddict

我正在构建 ASP.NET Core 1.1 应用程序(跨平台),并尝试(使用 this sample )在请求 /connect/token< 时向返回的 access_token 添加自定义声明 端点。
我需要的不仅是返回 access_token 中序列化的声明,还要在响应中返回它们,如下所示:

{
 "token_type": "Bearer",
 "access_token": "...",
 "expires_in": 1799,
 "custom_claim": "..."
}

我在互联网上找到的我必须使用的AspNet.Security.OpenIdConnect.Server并写下我的提供者以便能够做我想做的事情。
使用第一个示例没有简单的方法吗?
我使用的是 OAUth 2.0,授予类型密码,并且没有 JWT。
并不是不使用 JWT 的要求,只是我习惯了 ASP.NET 4.5 中的 OAuth

最佳答案

What I need is to not only return the claims serialized in the access_token but to return them in the response like this:

虽然我鼓励您将这些声明存储在身份 token 中 - 以便客户端可以以完全标准的方式轻松读取它们,但这在 OpenIddict 1.0 和 2.0 RTM 中是可能的。为此,您有 2 个选择:

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

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

注意:OpenIddictConstants.PropertyTypes.String 是一个特殊后缀,指示添加到票证的身份验证属性可以作为 token 响应的一部分公开。如果您希望将声明作为 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["custom_claim"] = principal.FindFirst("your_claim_attached_to_the_principal").Value;
                }

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

    // Register the OpenIddict validation handler.
    .AddValidation();

关于oauth-2.0 - 如何添加使用 OpenIddict 请求 token 时返回的自定义声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40502600/

相关文章:

java - 如何使用联合 SSO (SAML2) 调用 AtTask REST API

spring - 如何在 Spring Security JDBC 中保留 oauth 访问 token ?

c# - Blazor Framework 如何在属性值更改时收到通知

Openiddict 自省(introspection)不起作用(访问 token 无效。)

c# - OpenIddict 的依赖注入(inject)错误

python - Authlib token 未保存在数据库中

c# - AspNetCore Web Api Microsoft 帐户身份验证

asp.net-core - 在 ASP.NET MVC6 中使用 TagHelpers 与 ViewComponents

.net-core - 获取token后无法使用jwt访问授权路由

python - 使用 OAuth2 进行身份验证 + 与 google.appengine.api.users 服务兼容