I'm building ASP.NET Core 1.1 app (cross platform) and trying (using this sample) to add custom claims to the returned access_token
when requesting /connect/token
endpoint.
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_type": "Bearer",
"access_token": "...",
"expires_in": 1799,
"custom_claim": "..."
}
What I found on internet that I have to use AspNet.Security.OpenIdConnect.Server
and write my provider in order to be able to do what I want.
Isn't there a simple way using the first sample ?
I'm using OAUth 2.0, grant type Password
and no JWT.
Not a requirement to not use JWT, it's just I used to OAuth in ASP.NET 4.5
答案 0 :(得分:4)
我需要的是不仅要返回access_token中序列化的声明,还要在响应中返回它们,如下所示:
虽然我鼓励您将这些声明存储在身份令牌中 - 以便客户可以通过完全标准的方式轻松阅读这些声明,但在OpenIddict 1.0和2.0 RTM中也是如此。为此,您有两个选择:
ticket.SetProperty("custom_claim" + OpenIddictConstants.PropertyTypes.String, user.Id);
注意:OpenIddictConstants.PropertyTypes.String
是一个特殊后缀,表示添加到故障单的身份验证属性可以作为令牌响应的一部分公开。如果您希望将声明作为JSON编号或更复杂的JSON结构返回,则可以使用其他常量。
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();
答案 1 :(得分:1)
嗯,我们是通过使用启动的配置方法中 OpenIdConnectOptions 的事件属性来实现的>添加Open Id Connect中间件时的类,例如:
Events = new OpenIdConnectEvents
{
OnTicketReceived = n =>
{
//TODO Your logic here to add custom claims via n.Principal.Identities.First().AddClaims();
return Task.CompletedTask;
}
}
这是您用例的选项吗?
答案 2 :(得分:0)
作为@Pinpoint在其openiddict-samples
存储库中的答案,我跟踪了this article(在Implementing the Connect/Token Endpoint
部分中)..
我从他的回答中得出结论,我所做的不是标准,这就是为什么它不那么明显和容易做到的原因。
您需要使用JWT并向其添加自定义声明,以便客户端可以对其进行解码并获取声明,而不是通过自己的响应发送它们。