2017-07-24 157 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時。

非常感謝!