【问题标题】:How can I call a protected API from IdentityServer4?如何从 IdentityServer4 调用受保护的 API?
【发布时间】:2018-08-20 11:25:51
【问题描述】:

我想通过调用由 IS 认证的单独 api 将电子邮件服务从身份服务器项目中分离出来。

我的问题是从身份服务器调用 api。目前我在 IdentityServer 中有额外的“假”客户端正在调用 api。

这是客户端凭据流的标准选项。

  1. 获取令牌
  2. 返回令牌
  3. 调用api
  4. 检查令牌
  5. 返回数据

但我想省略客户端。所以 IdentityServer 是客户端。 我在 IS 中创建了一个“假”客户端,我认为这是错误的做法?

IdentityServer 中的MessageService.cs

 // Authenticating the fake client
 var disco = await DiscoveryClient.GetAsync("http://localhost:5000");
 var tokenClient = new TokenClient(disco.TokenEndpoint, "MailApiClient", "secret");
 var tokenResponse = await tokenClient.RequestClientCredentialsAsync("EmailScope");
 // Setting the token
 client.SetBearerToken(tokenResponse.AccessToken);
 var content = new StringContent(JsonConvert.SerializeObject(someMailModel));
 // Posting to api
 var response = await client.PostAsync(_emailSettings.RequestUri, content).ConfigureAwait(false);

假客户端通过 IS 进行身份验证,然后将带有令牌的消息发送到 mailapi。 而不是在 IS 中创建假客户端,我希望 IS 本身就是客户端。所以IdentityServer会在没有中间件客户端的情况下调用api。

未来还有一些其他客户端将使用 MailApi。

【问题讨论】:

  • 为什么要从IDS4调用MailApi?如果完全有商业原因,你不能将 ITokenService 或任何其他负责直接创建令牌的服务注入到调用 MailAPI 的类中吗?而不是进行自我网络调用?
  • 我可以看到这样做的必要性。一个很好的例子是,如果您将用户声明放在 API 中,并且希望将该 API 公开给许多其他 API 和 IdentityServer4 以获取数据。
  • 我认为您的问题更像是“如何从 IdentityServer4 调用受保护的 API?”
  • @Gokulnath 目前我不需要将 api 暴露给其他人,但在“不久的”将来我想将邮件 api 暴露给需要一些授权的 javascript 客户端(只有 IS并且客户将能够使用它)。我正在寻找使用 ITokenService 自己创建令牌(省略额外的假客户端),看起来有点难,但会尝试这样做。
  • @aaronR 哦,这个标题更简单明了,谢谢:)

标签: identityserver4


【解决方案1】:

有一个类“IdentityServerTools”可以在 IdentityServer 中手动发出令牌。

How to protect Web API called by IdentityServer4 https://identityserver4.readthedocs.io/en/release/topics/tools.html

【讨论】:

    猜你喜欢
    • 2021-06-20
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    相关资源
    最近更新 更多