IdentityServer混合流 - 用户成功登录后访问令牌为空

时间:2017-11-02 11:08:02

标签: asp.net identityserver3 openid-connect identityserver4

我在检索经过身份验证的用户的访问令牌方面遇到了问题。下面是我的配置

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;为空。我正在考虑将我的MVC客户端迁移到Core,因为我已经在asp.net核心中尝试过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,其中端点&#34;核心&#34}在IDS4中不存在。我可以在此行var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(n.Code, n.RedirectUri);中获取访问令牌,但在授权后,我仍然会在此var accessToken = user.FindFirst("access_token").Value;代码行中获得空引用异常。

2 个答案:

答案 0 :(得分:1)

鉴于

上的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的设置的所有重要部分添加代码 - 因为事实通常都隐藏在细节中。

答案 1 :(得分:0)

相关问题