我正在使用 JWT token 和 OpenIdConnectServer。一切正常,但我无法在 token 响应中添加自定义属性...结果如下:
resource": "resource_server_1",
"token_type": "bearer",
"access_token": "eyJhb....LSk5PQldEVVFaTllNU",
"expires_in": "3600"
我想添加一些属性,例如用户名或角色... 我试图通过 AuthenticationProperties 添加,但它不起作用。这是我的代码:
public override Task GrantResourceOwnerCredentials(GrantResourceOwnerCredentialsContext context)
{
ClaimsIdentity identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme);
identity.AddClaim(ClaimTypes.Name, "test", "token id_token");
identity.AddClaim(ClaimTypes.Role, "test", "token id_token");
var ticket = new AuthenticationTicket(
new ClaimsPrincipal(identity),
new AuthenticationProperties(new Dictionary<string, string>
{
{"username", "test" }
}),
context.Options.AuthenticationScheme);
ticket.SetResources(new[] { "resource_server_1" });
context.Validated(ticket);
return Task.FromResult<object>(null);
}
最佳答案
要将自定义属性添加到 token 响应,您可以查看其他 SO 问题:Overriding TokenEndPoint in AspNet.Security.OpenIdConnect.Server
也就是说,这不是我推荐的方法。相反,您应该使用 OpenID Connect 提供的新 id_token
概念,ASOS 中的密码流也支持该概念,并允许在授权服务器和客户端应用程序之间共享用户详细信息。
为此,将 scope=openid
添加到您的 token 请求中,OIDC 服务器中间件将开始返回一个 JSON Web token ,您将能够读取该 token 以提取用户名等用户详细信息。请注意,只有指定 id_token
目的地的声明才会包含在身份 token 中。阅读此 SO 帖子以获取更多信息:https://stackoverflow.com/a/35041102/542757
(在相关说明中,您没有向身份验证票证添加 ClaimTypes.NameIdentifier
声明:这不是合法操作,因为 OIDC 服务器中间件需要唯一 ID 来识别用户)
关于asp.net - 如何更改 asp.net core 1 中的 token 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36579568/