AWS cognito - 从 Cognito 登录表单登录后如何从收到的代码中获取令牌?

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

我的问题与那里提出的问题非常相似https://stackoverflow.com/questions/45785898/how-to-use-the-code-returned-from-cognito-to-get-aws-credentials

基本上我使用 Cognito 应用程序登录。成功登录后,我将使用查询字符串中的代码重定向到我的应用程序。我知道我应该使用以下端点将该代码交换为令牌:/oauth2/token 但我系统地收到 invalid_client 的“400 - 错误请求”,即使我使用与 /login 或 /signup 相同的 client_id。

(我正在用 Typescript 编写我的 aws 堆栈)

我正在尝试找出错误可能来自哪里。

我的要求是这样的:

POST https://<domain name>.amazoncognito.com/oauth2/token?client_id=<client_id>&grant_type=authorization_code&redirect_uri=http://localhost:4200&code=<code I get in the query param after login>

在标题中:

Authorization: Basic <app credential>

Content-Type: application/x-www-form-urlencoded

对于

app credential
,我从以下地方得到它:

const secret = this.userPoolClient.userPoolClientSecret as any;

this.appCredentials = btoa(this.userPoolClient.userPoolClientId + ":" + secret.value);

...而身体是空的

(我知道我应该创建一个 SecretManagerStack 来存储秘密,但现在,我只是想获取该令牌。稍后我会担心如何保护秘密)

我有3个问题:

  1. 从 Cognito 登录表单回来后,我确实应该使用 /oauth2/token 还是应该做一些不同的事情?
  2. 我是否正确使用该 API /oauth2/token 以及所有必要的输入和标头?
  3. 我的应用程序凭据可能有误吗?我该如何取回客户端机密?
amazon-web-services amazon-cognito aws-cdk
1个回答
0
投票
  1. 是的,从 Cognito 登录表单返回后,您确实应该使用 /oauth2/token 端点将授权代码交换为访问令牌。
  2. 假设 client_id 和 code 参数是您从 Cognito 获取的值,您的请求对我来说看起来是正确的。您可以从 Cognito 控制台导航到“应用程序客户端”部分来验证这一点。
  3. 应用程序凭据是通过结合客户端 ID 和客户端密钥生成的。看起来您正在从 userPoolClient.userPoolClientSecret 属性中正确检索客户端密钥。

您可以检查以下几项:

<ul>
  <li>The authorization code is valid. The authorization code has a short expiration time, so you need to exchange it for an access token as soon as possible after receiving it.</li>
  <li>The Authorization header must be set to Basic <app credential>. The Content-Type header must be set to application/x-www-form-urlencoded.</li>
  <li>The client ID and client secret are properly encoded in the Authorization header. You can use a tool like Base64 Encoder/Decoder to verify the encoding.</li>
  <li>Make sure that the request body is empty. The request body should only be used for the client_credentials grant type.</li>
  <li>The grant_type parameter is set to authorization_code.</li>
</ul>

© www.soinside.com 2019 - 2024. All rights reserved.