我希望使用boto3和python为AWS Cognito创建/计算SECRET_HASH。这将被合并到我的warrant分支中。
我配置了我的cognito应用程序客户端以使用应用程序客户端密钥
。但是,这破坏了以下代码。
def renew_access_token(self):
"""
Sets a new access token on the User using the refresh token.
NOTE:
Does not work if "App client secret" is enabled. 'SECRET_HASH' is needed in AuthParameters.
'SECRET_HASH' requires HMAC calculations.
Does not work if "Device Tracking" is turned on.
https://dev59.com/_FoU5IYBdhLWcg3wc2tW#40875783
'DEVICE_KEY' is needed in AuthParameters. See AuthParameters section.
https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html
"""
refresh_response = self.client.initiate_auth(
ClientId=self.client_id,
AuthFlow='REFRESH_TOKEN',
AuthParameters={
'REFRESH_TOKEN': self.refresh_token
# 'SECRET_HASH': How to generate this?
},
)
self._set_attributes(
refresh_response,
{
'access_token': refresh_response['AuthenticationResult']['AccessToken'],
'id_token': refresh_response['AuthenticationResult']['IdToken'],
'token_type': refresh_response['AuthenticationResult']['TokenType']
}
)
当我运行这个程序时,我收到了以下异常:
botocore.errorfactory.NotAuthorizedException:
An error occurred (NotAuthorizedException) when calling the InitiateAuth operation:
Unable to verify secret hash for client <client id echoed here>.
这个回答告诉我使用cognito客户端密钥需要SECRET_HASH。
aws API参考文档中的AuthParameters部分说明如下:
对于REFRESH_TOKEN_AUTH/REFRESH_TOKEN:USERNAME(必需),SECRET_HASH(如果应用程序客户端配置了客户端密钥,则必需),REFRESH_TOKEN(必需),DEVICE_KEY
boto3文档指出,SECRET_HASH是
使用用户池客户端的秘密密钥和消息中的用户名加上客户端ID计算得出的密钥散列消息认证代码(HMAC)。
文档解释了所需内容,但没有说明如何实现。
dig = hmac.new(...)
行收到了这个错误“TypeError:key:期望字节或字节数组,但得到'str'”
。解决方法是在hmac.new
的第一个参数处执行简单的bytearray(self.client_secret,“utf-8”)
。 - CarlosR