2017-07-24 158 views
1

我从AWS上的无服务器开始,我正在使用AWS Cognito进行用户身份验证和授权。对于我在文档和示例中看到的内容,您可以创建组以允许某些用户能够使用Api网关端点,并将角色和策略附加到该组。我尝试了这一点,然后创建了一个简单的客户端,并尝试使用两个不同的用户,并且都能够获得200个状态代码,而不是其中的一个,因为它没有得到授权。为了创建角色,我去了IAM,创建角色,身份提供者访问角色,授予对Web身份提供者的访问权限,然后选择Amazon Cognito并选择我的Cognito用户池。 信任关系:AWS Cognito组和AWS Api网关

{ 
    "Version": "2012-10-17", 
    "Statement": [ 
    { 
     "Effect": "Allow", 
     "Principal": { 
     "Federated": "cognito-identity.amazonaws.com" 
     }, 
     "Action": "sts:AssumeRoleWithWebIdentity", 
     "Condition": { 
     "StringEquals": { 
      "cognito-identity.amazonaws.com:aud": "us-east-1_8TAUVKbGP" 
     } 
     } 
    } 
    ] 
} 

政策:

{ 
    "Version": "2012-10-17", 
    "Statement": [ 
     { 
      "Effect": "Allow", 
      "Action": [ 
       "execute-api:Invoke" 
      ], 
      "Resource": [ 
       "my-arn-resourse-from-api-gateway" 
      ] 
     } 
    ] 
} 

然后我分配这个角色给我的管理组和连接相关政策的用户添加到组,这应该允许访问API网关资源在用户登录时向用户发送。但是,当我尝试与不在该用户组中的用户通信时,它仍然有效。顺便说一句,在我的API网关资源请求我把认证池授权。

非常感谢!

回答

1

好吧,终于我得到它的工作完美!这个问题在我的IAM角色,信任关系文件中

"Condition": { 
 
     "StringEquals": { 
 
      "cognito-identity.amazonaws.com:aud": "identity_pool_id" 
 
     },

在那一部分,而不是用我的身份池ID,我是用我的用户池ID。一旦这个问题得到解决,我就拿回了凭证,并且在Postman使用这些凭据进行了尝试,结果非常完美。然后我将同一用户更改为另一个角色,并按计划拒绝访问!对于使用角色授权最简单的方法,最重要的部分是agent420表示使用AWS_IAM方法来保护api,然后其余部分由aws处理。

0

您需要使用AWS_IAM方法代替您的用例。此外,在这种情况下,您的所有API请求都需要进行SIGv4签名。您可以使用Postman(Chrome扩展)进行测试。它包含一个AWS凭证选项。

+0

谢谢!我会试一试,让你知道它是怎么回事! –

0

我试试你说的!我认为我的方式正确,但AWS.config.credentials正在返回sessionToken和accessKeyId,两者均为null。这是我使用的代码:

let poolData = { 
 
     UserPoolId : 'my_user_pool_id', 
 
     ClientId : 'my_app_client_id' 
 
    }; 
 

 
    let authenticationData = { 
 
     Username : 'username', 
 
     Password : 'password', 
 
    }; 
 

 
    let userPool = new CognitoUserPool(poolData); 
 

 
    let userData = { 
 
     Username : 'username', 
 
     Pool : userPool 
 
    }; 
 

 
    let authenticationDetails = new AuthenticationDetails(authenticationData); 
 

 
    let cognitoUser = new CognitoUser(userData); 
 

 
    cognitoUser.authenticateUser(authenticationDetails, { 
 
     onSuccess: (result) => { 
 
     console.log(result); 
 

 
     AWS.config.region = 'my_region'; 
 

 
     AWS.config.credentials = new AWS.CognitoIdentityCredentials({ 
 
      IdentityPoolId : 'my_identity_pool_id', 
 
      Logins : { 
 
      'cognito-idp.my_region.amazonaws.com/my_user_pool_id' : result.getIdToken().getJwtToken() 
 
      } 
 
     }); 
 

 
     console.log(AWS.config.credentials); 
 
     }, 
 
     onFailure: (error) => { 
 

 
     } 
 
    });

结果从的authenticateUser返回预期的令牌。我认为这个问题是在检索CognitoIdentityCredentials时。

非常感谢!