我正在构建 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/