如何使用python以编程方式交换授权码以从cognito获取访

如何使用python以编程方式交换授权码以从cognito获取访

本文介绍了如何使用python以编程方式交换授权码以从cognito获取访问令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我一直在寻找有关如何交换授权代码以务实地从 cognito 获取访问令牌的解决方案.我已经创建了认知池和集成的应用程序客户端.所以当我以下面的格式调用登录域时,我得到了登录页面并能够登录/注册

I been searching for a solution on how to exchange authorization_code to get the access token from cognito pragmatically . i have created cognito pool and integrated app client. so when i invoke the login domain in the below format, iam getting the login page and able to login/sign up

https://<your_domain>/login?response_type=code&client_id=<your_app_client_id>&redirect_uri=<your_callback_url>

现在上面的url将返回authorization_code作为参数.我使用 post man 通过以下查询获取结果,该查询返回 id 令牌、访问令牌、刷新令牌.

Now the above url will return the authorization_code as parameter. I used post man to get the result with following query, which return the id token, acccess token, refresh token.

POST https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/token&
Content-Type='application/x-www-form-urlencoded'
grant_type=authorization_code&
client_id=myid&
code=AUTHORIZATION_CODE&
redirect_uri=http://localhost:5000/login

现在我需要在我的应用程序中实现相同的来获取访问令牌下面是我试过的代码

Now i would need to implement the same in my app to get the access tokenBelow is the code i tried

 response = requests.post(url + '/oauth2/token',
                             auth=(App_client_id),
                             data={'grant_type': grant_type, 'code': accessCode, 'client_id': App_client_id,
                                   "redirect_uri":'http://localhost:5000/login'})
print(response.json())

但我没有得到任何回应.

But i am not getting any response.

  1. 我有一个与认知用户池/授权方相关联的 api-gatway,这个 api-gateway 返回来自其他 aws 服务(如 lambda)的响应.

2.在我的应用程序 - Flask 应用程序中,我想以这样的方式放置一个逻辑,即一旦用户在登录后通过用户池进行身份验证,它就会返回 redirect_uri 中的 authorization_code.

2.In my application - Flask App, i want to put a logic in such a way that once user authenticated with the user pool after login, it return the authorization_code in the redirect_uri.

  1. 在redirect_uri 中,我有特定的操作——读/写/删除任务.对于每个任务,我需要使用通过 authorization_code 交换收到的访问令牌进行身份验证.所以只有登录的用户才能从重定向 uri 执行操作.

感谢是否有人可以帮助解决此问题?

Appreciate if anyone can help to resolve this?

谢谢

推荐答案

对于其他坚持要让它工作的人,我发现它使用 requests.postparams 参数有效/代码>

For anyone else stuck on getting this to work, I found it worked using the params argument in requests.post

token_url="https://myapp.auth.us-east-1.amazoncognito.com/oauth2/token"
message = bytes(f"{client_id}:{client_secret}",'utf-8')
secret_hash = base64.b64encode(message).decode()
payload = {
    "grant_type": 'authorization_code',
    "client_id": client_id,
    "code": code,
    "redirect_uri": redirect_uri
}
headers = {"Content-Type": "application/x-www-form-urlencoded",
            "Authorization": f"Basic {secret_hash}"}

resp = requests.post(token_url, params=payload, headers=headers)

这篇关于如何使用python以编程方式交换授权码以从cognito获取访问令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 17:18