首页 文章

AWS API网关Cognito用户池授权人Lambda - 我需要设置哪些HTTP标头和权限?

提问于
浏览
5

我在AWS上通过HTTP标头(没有AWS API Gateway SDK)获取Cognito用户池的API授权时遇到问题 .

My setup:

在AWS上:

  • 在AWS Lambda上实现的REST API(通过Serverless框架部署),

  • 使用类型LAMBDA_PROXY通过API网关公开(无手动映射)

  • 通过提供的"Cognito User Pool authorizer" API API网关授权(没有"AWS_IAM"选项,没有自定义编码授权器)

  • 通过Postman测试API

在iOS客户端上

  • 通过AWS Cognito注册/登录(从AWS Mobile Hub生成的演示Xcode项目复制的SDK和UI)

  • 使用AWSAPIGateway SDK通过RestKitnot 访问REST API

What is working:

API方法通过无服务器正确部署 .

我可以通过Postman呼叫公众(不设置使用用户池) .

对于私有API方法,我可以看到在API网关管理控制台中设置了Cognito用户池授权程序,包括"Identity token source"设置为 method.request.header.Authorization (默认值),如here所述

在iOS上,我可以正确注册并以用户身份登录 . 我可以将AWS Credentials详细信息转储到控制台,显示 AccessKeySecretKeySessionKey .

在iOS上,我可以通过RestKit查询公共API .

当我尝试通过Postman调用私有API方法时,我收到了一个带有正文 {"message": "Unauthorized"} 的HTTP错误401 . (预计没有设置任何授权 . )

What fails:

为了测试授权,在邮递员中,我试过了

结果始终是401错误 .

What do I need to set as HTTP headers, in order to authorize the calls to the private API? "Authorization" should work - maybe I am missing some role permissions?

How can I better debug the permissions / authorization flow?

3 回答

  • 2

    这是如何获得会话:

    AWSCognitoIdentityUserPool *pool = [AWSCognitoIdentityUserPool CognitoIdentityUserPoolForKey:AWSCognitoUserPoolsSignInProvi‌​derKey]; 
    AWSCognitoIdentityUser *user = [pool currentUser]; 
    AWSTask<AWSCognitoIdentityUserSession *> *task = [user getSession];
    

    然后, task.result.idToken.tokenString 可以设置为"Authorization"标头,它可以工作 .

    谢谢彼得的小费!

  • 2

    适用于iOS(截至2017年5月11日)

    let headerParameters = [
                   "Content-Type": "application/json",
                   "Accept": "application/json",
                   "AccessKey" : awsCredentials.accessKey,
                   "SecretKey" : awsCredentials.secretKey,
                   "SessionKey" : awsCredentials.sessionKey,
                   "Authorization" :
                    AWSCognitoUserPoolsSignInProvider.sharedInstance().getUserPool().currentUser()?.getSession().result?.idToken?.tokenString
                ]
    

    您可以在成功登录时获取awsCredentials并将其存储在您自己的代码中(AuthorizationService?) . 我保持“授权”值这么长,以便开发人员更容易知道这个隐藏对象的完整位置 . 您应该将它保存在您自己的AuthorizationService类中(或作为AwsCredentials的扩展成员?)

  • 0

    如果您使用Swift 3,您可以通过以下代码获取身份令牌 .

    let pool = AWSCognitoUserPoolsSignInProvider.sharedInstance().getUserPool()
            let currentUser = pool.currentUser()
            let task = currentUser?.getSession()
            let identityToken = task?.result?.idToken?.tokenString
            print("identityToken: \(String(describing: identityToken))")
    

相关问题