我在检索经过身份验证的用户的访问 token 时遇到问题。以下是我的配置
ASP.NET MVC 5 客户端:
- OpenIdConnect
- IdentityServer3 库
- ResponseType = "代码 id_token"
ASP.NET Core 身份服务器:
- IdentityServer4 库
- 客户端配置:AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
我正在尝试使用以下方法在客户端中获取访问 token :
AuthorizationCodeReceived = async n =>
{
// use the code to get the access and refresh token
var tokenClient = new TokenClient(TokenEndpoint, "clientid", "secret");
var response = await tokenClient.RequestAuthorizationCodeAsync(n.Code, n.RedirectUri);
},
我在上述实现中使用了此引用 - https://github.com/IdentityServer/IdentityServer3/issues/2457
但是 response
中的属性有空值。我需要访问 token ,以便登录客户端的用户可以访问 api。以下是我尝试检索访问 token 的另一种方法:
public async Task<ActionResult> CallApiUsingUserAccessToken()
{
var user = User as ClaimsPrincipal;
var accessToken = user.FindFirst("access_token").Value;
var client = new HttpClient();
client.SetBearerToken(accessToken);
var content = await client.GetStringAsync("http://localhost:6001/api/values");
ViewBag.Json = JArray.Parse(content).ToString();
return View("json");
}
但是,user.FindFirst("access_token").Value;
一片空白。我正在考虑将我的 MVC 客户端迁移到 Core,因为我已经在 asp.net core 中尝试过 IdentityServer4 版本,但这对我来说似乎是一个很大的迁移。谢谢。
[已更新]
我从来没有想到 IdentityServer3 中的端点与 IDS4 不同。我确实必须改变var tokenClient = new TokenClient(TokenEndpoint, "client", "secret");
至var tokenClient = new TokenClient("http://localhost:9000/connect/token", "client", "secret")
因为 IDS3 中的 TokenEndpoint 是 http://localhost:9000/core/connect/token IDS4 中不存在端点“core”。我能够在这一行 var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(n.Code, n.RedirectUri);
中获取访问 token 但授权后,我仍然收到此 var accessToken = user.FindFirst("access_token").Value;
的空引用异常代码行。
最佳答案
鉴于 IdentityServer 4 文档
以及来自 IdentityServer3.Samples 的示例客户端
您应该能够设置工作环境。
为了支持调试,您应该始终进行正确的响应处理,如下面的示例和 copied from example client 所示。 。将任何回答错误添加到您的问题中。
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthorizationCodeReceived = async n =>
{
// use the code to get the access and refresh token
var tokenClient = new TokenClient(
Constants.TokenEndpoint,
"mvc.owin.hybrid",
"secret");
var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(
n.Code, n.RedirectUri);
if (tokenResponse.IsError)
{
throw new Exception(tokenResponse.Error);
}
最后,我建议为基于 IdentityServer3/4 的设置的所有重要部分添加代码 - 因为真相通常隐藏在细节中。
关于asp.net - IdentityServer混合流-用户成功登录后访问 token 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47073814/