【问题标题】:How to properly obtain the token using C# from Identity Server 4 to use in Postman?如何使用 C# 从 Identity Server 4 正确获取令牌以在 Postman 中使用?
【发布时间】:2019-04-08 04:48:04
【问题描述】:

我正在执行以下 C# 魔术并读取在 jwt.io 中获得的令牌。一切看起来都很棒。

DiscoveryResponse vasco = DiscoveryClient.GetAsync("http://localhost:5100").Result;
string tokenUri = vasco.TokenEndpoint;

TokenClient client = new TokenClient(vasco.TokenEndpoint, "Blopp", "SuperSecret");
TokenResponse cred = client.RequestClientCredentialsAsync("secured_api").Result;
string token = cred.AccessToken ?? "none!";

但是,它似乎不是完全正常运行的,因为当使用键 Authorization 和值 Bearer + token (手动添加的前缀)粘贴到 Postman 中时,我进入无法访问的服务(如this question 中所述)。

在端点 http://localhost:5100/connect/token 和 Postman 的基于 OAuth 2.0 的向导上使用相同的凭据,生成一个有效的令牌。

我的结论是,我不知何故没有使用我的代码获取正确的令牌(并且由于无知而未能意识到),或者我获取的令牌丢失了一些东西。

如何获取正确的令牌,完整且完全等同于 Postman 在上述 URL 中获得的令牌?

【问题讨论】:

  • 如果令牌不正确,您应该得到unauthorized 响应。根据另一个问题,您可以检查您的网站是否使用httpshttp。当站点实际上在http 上时使用https 通常会导致Could not get any response 错误。
  • @SimplyGed 如问题所述 - 令牌正确且经过验证。我尝试了 HTTP 和 HTTPS——那里的结果相同。无论如何,我很确定它与令牌有关,但我不知道如何。我有某种感觉,当我获取令牌字符串时,非法字符正在被复制(并且 JWT.io 将它们过滤掉)......

标签: c# asp.net-core jwt postman identityserver4


【解决方案1】:

我的结论是,我不知何故没有使用我的代码获取正确的令牌(并且由于无知而未能意识到),或者我获取的令牌丢失了一些东西。

根据你的代码,你是 protecting an API using Client Credentials,所以首先请按照文章中的详细步骤配置身份服务器、web api和客户端。

为了测试,我按照文章中的步骤,并使用与您显示的相同的代码来获取令牌:

        // discover endpoints from metadata
        var disco = await DiscoveryClient.GetAsync("http://localhost:5000");
        if (disco.IsError)
        {
            Console.WriteLine(disco.Error);
            return;
        }

        // request token
        var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret");
        var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1");

        if (tokenResponse.IsError)
        {
            Console.WriteLine(tokenResponse.Error);
            return;
        }

        Console.WriteLine(tokenResponse.Json);
        Console.WriteLine("\n\n");

'http://localhost:5000' 是身份服务器的主机端点,clinet/secret 是我的客户端的凭据:

 public static IEnumerable<Client> GetClients()
 {
  return new List<Client>
  {
    new Client
    {
        ClientId = "client",

        // no interactive user, use the clientid/secret for authentication
        AllowedGrantTypes = GrantTypes.ClientCredentials,

        // secret for authentication
        ClientSecrets =
        {
            new Secret("secret".Sha256())
        },

        // scopes that client has access to
        AllowedScopes = { "api1" }
    }
};
}

使用该令牌访问 Postman 中的 web api:

您还可以在使用基于 OAuth 2.0 的向导时比较获取令牌请求,并确认您使用的是客户端凭据流。

【讨论】:

  • 好吧,你的分析错了,但无论如何都设法让我走上正确的道路,干得好。事实证明,当我复制令牌时,它以某种方式将换行符转换为空格,然后 PostMan 拒绝开始调用。现在它起作用了!谢谢。
猜你喜欢
  • 2021-03-01
  • 2021-09-10
  • 1970-01-01
  • 2020-11-12
  • 1970-01-01
  • 1970-01-01
  • 2021-07-28
  • 2023-03-05
  • 1970-01-01
相关资源
最近更新 更多