我在检索经过身份验证的用户的访问令牌方面遇到了问题 . 下面是我的配置
ASP.NET MVC 5客户端:
-
OpenIdConnect
-
IdentityServer3库
-
ResponseType = "code id_token"
ASP.NET核心标识服务器:
-
IdentityServer4库
-
客户端配置:AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
我正在尝试使用以下方法在我的客户端获取访问令牌:
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
中的属性具有空值 . 我需要访问令牌,以便登录客户端的用户可以访问api . 以下是我尝试检索访问令牌的另一种方法:
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;
为空 . 我已经在asp.net核心中尝试过IdentityServer4版本,但这似乎是我的一大迁移 . 谢谢 .
[updated]
我从未想到IdentityServer3中的 endpoints 与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中不存在 endpoints "core" . 我能够在这一行获得访问令牌 var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(n.Code, n.RedirectUri);
但是在授权之后,我仍然得到这个 var accessToken = user.FindFirst("access_token").Value;
代码行的空引用异常 .
2 回答
鉴于IdentityServer 4文档
和来自IdentityServer3.Samples的示例客户端
你应该能够设置一个工作环境 .
为了支持调试,您应始终进行适当的响应处理,如下面的示例和copied from example client所示 . 在您的问题中添加任何回复错误 .
最后,我建议为基于IdentityServer3 / 4的设置的所有重要部分添加代码 - 因为事实通常隐藏在细节中 .
根据这些帖子,https://github.com/IdentityServer/IdentityServer3/issues/2457&https://github.com/IdentityServer/IdentityServer3/issues/2015#issuecomment-172623173,最好不要在声明中包含访问令牌 . 因此,我按照他的示例https://github.com/Mich-b/IdentityServerTMLClient/blob/master/IdentityServerTMLClient/Startup.cs,其中在Http会话存储中添加了访问令牌 .