作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个静态无服务器网站,允许使用 AWS Cognito User Pool 通过 Javascript 进行身份验证.
现在我正在尝试启用一些编程访问,因此我需要通过 Python 脚本执行相同的身份验证。这可能吗?文档不提供任何 code examples用于 Python。
我只是想找到一些方法让 Python 对 AWS URL 发出 GET 或 POST 请求,将用户名和登录名传递给它,然后取回 signed cookies验证身份验证。
我找到的最接近的例子是 this code ,它引用了 cognito-idp API .我修改为:
import boto3
client_id = '<my_app_client_id>'
region_name = 'us-east-1'
auth_data = { 'USERNAME':'myusername' , 'PASSWORD':'mypassword' }
provider_client = boto3.client('cognito-idp', region_name=region_name)
resp = provider_client.initiate_auth(AuthFlow='USER_PASSWORD_AUTH', AuthParameters=auth_data, ClientId=client_id)
print('resp:', resp)
但是,即使我使用与通过 Javascript API 相同的凭据,这也无法进行身份验证并仅返回错误:
botocore.exceptions.NoCredentialsError: Unable to locate credentials
这是 Javascript Cognito API 的正确 Python 等价物?
最佳答案
以下代码段显示了使用 boto3 的 Cognito 的完整身份验证工作流程。
def get_secret_hash(username):
msg = username + CLIENT_ID
dig = hmac.new(
str(CLIENT_SECRET).encode('utf-8'),
msg=str(msg).encode('utf-8'),
digestmod=hashlib.sha256
).digest()
d2 = base64.b64encode(dig).decode()
return d2
def initiate_auth(client, username, password):
secret_hash = get_secret_hash(username)
try:
resp = client.admin_initiate_auth(
UserPoolId=USER_POOL_ID,
ClientId=CLIENT_ID,
AuthFlow='ADMIN_NO_SRP_AUTH',
AuthParameters={
'USERNAME': username,
'SECRET_HASH': secret_hash,
'PASSWORD': password,
},
ClientMetadata={
'username': username,
'password': password, })
except client.exceptions.NotAuthorizedException:
return None, "The username or password is incorrect"
except client.exceptions.UserNotConfirmedException:
return None, "User is not confirmed"
except Exception as e:
return None, e.__str__()
return resp, None
@app.route('/auth/login', methods=['POST'])
def login():
event = auth.current_request.json_body
client = boto3.client('cognito-idp')
username = event['username']
password = event['password']
for field in ["username", "password"]:
if event.get(field) is None:
return {"error": True,
"success": False,
"message": f"{field} is required",
"data": None}
resp, msg = initiate_auth(client, username, password)
if msg != None:
return {'message': msg,
"error": True, "success": False, "data": None}
if resp.get("AuthenticationResult"):
return {'message': "success",
"error": False,
"success": True,
"data": {
"id_token": resp["AuthenticationResult"]["IdToken"],
"refresh_token": resp["AuthenticationResult"]["RefreshToken"],
"access_token": resp["AuthenticationResult"]["AccessToken"],
"expires_in": resp["AuthenticationResult"]["ExpiresIn"],
"token_type": resp["AuthenticationResult"]["TokenType"]
}}
else: # this code block is relevant only when MFA is enabled
return {"error": True,
"success": False,
"data": None, "message": None}
这是从函数中解析出来的重要部分。
resp = client.admin_initiate_auth(
UserPoolId=USER_POOL_ID,
ClientId=CLIENT_ID,
AuthFlow='ADMIN_NO_SRP_AUTH',
AuthParameters={
'USERNAME': username,
'SECRET_HASH': secret_hash,
'PASSWORD': password,
},
ClientMetadata={
'username': username,
'password': password, })
这些示例取自一个由四部分组成的教程,不幸的是,该教程没有帮助我将其与 Chalice CognitoUserPoolAuthorizer 集成,但在其他方面似乎运行良好。如果您找不到更好的代码示例,可以引用这里的教程。
关于python - 如何在 Python 中针对 AWS Cognito 用户池进行身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61281852/
我是一名优秀的程序员,十分优秀!