如何进行需要OAuth访问令牌的集成测试?

问题描述 投票:0回答:2

我与 Linkedin API 集成,并且我有这样的代码。我想测试它并在 CI/CD 中运行它。要获取访问令牌,我应该打开浏览器并允许我的应用程序访问我的测试 linkedin 帐户。另外,我无法直接将访问令牌放入代码中,因为它可能会过期。刷新令牌早已过期,但仍然可能过期。测试这样的第三方 API 的最佳方法是什么?

await sendPostToLinkedIn({
  access_token: 'xxx',
  content: 'I got promoted today!'
}); 
api oauth-2.0 oauth linkedin-api
2个回答
1
投票

通常只为自己的代码编写 CI/CD 集成测试,而不是第三方代码。对于您自己的 API,可以使用发布您自己的模拟 JWT 访问令牌的技术,然后公开模拟 JWKS URI 以获取令牌签名密钥,如我的这些示例集成测试所示。这避免了处理 OAuth 登录的需要。

对于必须运行授权代码流程的第三方 API,一种选择是偶尔手动执行该步骤,然后使用访问令牌运行测试套件。毕竟,当您自己的客户端代码发生变化时,第三方 API 不会发生变化。也许在 CI / CD 期间,您可以模拟真实的 API,并运行相同的测试,重点是测试您自己的客户端代码。

可以通过遵循重定向并发出表单帖子来编写自己的客户端代码来运行代码流。但这样的代码很复杂,而且有点脆弱,所以我只会谨慎使用它。


0
投票

我认为有几种不同的方法可以解决这个问题。

1. You can use some mock library which helps you create MockServer(for ex.
WireMock c#). Then set up that mock servers with request and
response. In your case the request would be the LinkedIn uri being
used. You can set the mock response accordingly. In this way for each
test case you can have separate setup and expectation. And you won't
need token at all as you will be using the Mock server for linkedin
not the original linkedin apis. 

2. And another not so good solution may be to have a Client registered
with oauth ClientCredentials flow(with your identity provider). And use this client in your test
cases. Since it's a Client Credential flow you won't require the
user.
© www.soinside.com 2019 - 2024. All rights reserved.