2017-08-09 20 views
1

即時通訊目前使用用戶藏授權獲得前3個令牌我的API:如何使用UserPools idToken獲取AWS憑證?

  • idToken
  • refreshToken
  • 的accessToken

在這裏,我想請求憑據能夠將SigV4請求發送到我已經建立的API網關,但首先我需要獲取請求的憑證才能執行SigV4。

在我發現這個文檔:

// Set the region where your identity pool exists (us-east-1, eu-west-1) 
AWSCognito.config.region = 'us-east-1'; 

// Configure the credentials provider to use your identity pool 
AWSCognito.config.credentials = new AWSCognito.CognitoIdentityCredentials({ 
    IdentityPoolId: 'us-east-1:009xxxx ...', 
}); 

// Make the call to obtain credentials 
AWSCognito.config.credentials.get(function(){ 

    // Credentials will be available when this function is called. 
    var accessKeyId = AWSCognito.config.credentials.accessKeyId; 
    var secretAccessKey = AWSCognito.config.credentials.secretAccessKey; 
    var sessionToken = AWSCognito.config.credentials.sessionToken; 

}); 

令我驚訝的是,回調的調用,但對於 值 - accessKeyId - secretAccessKey - sessionToken 均爲空。

我在等待某種方法,在那裏我發送了我的第一個idToken,並且基於這個我得到了證書,但是看起來這個問題都是在隱藏的問題之下?反正它不適合我。

回答

1

經過一番研究,我意識到有這樣做的無證方式。

您需要首先建立這個對象:

let url = 'cognito-idp.' + 'identity pool region' + '.amazonaws.com/' + 'your user pool id'; 
let logins = {}; 

logins[url] = idTokenJwt; // <- the one obtained before 

let params = { 
    IdentityPoolId: 'the federated identity pool id', 
    Logins: logins 
}; 

let creds = new AWS.CognitoIdentityCredentials(params); 


AWS.config.region = 'us-east-1'; 
AWS.config.credentials = creds; 

creds.get(function (err: any) { 
    if (!err) { 
    console.log("returned without error"); // <-- this gets called!!! 

    // and the values are correctly set! 
    var accessKeyId = AWS.config.credentials.accessKeyId; 
    var secretAccessKey = AWS.config.credentials.secretAccessKey; 
    var sessionToken = AWS.config.credentials.sessionToken; 

    } 
    else{ 
    console.log("returned with error"); // <-- might get called if something is missing, anyways self-descriptive. 
    console.log(err); 
    } 
}); 

在我來說,我還是不得不配置的作用和身份池,這裏的例子之間的信任關係:

{ 
    "Sid": "", 
    "Effect": "Allow", 
    "Principal": { 
    "Federated": "cognito-identity.amazonaws.com" 
    }, 
    "Action": "sts:AssumeRoleWithWebIdentity", 
    "Condition": { 
    "StringEquals": { 
     "cognito-identity.amazonaws.com:aud": "your federated identity pool id" 
    }, 
    "ForAnyValue:StringLike": { 
     "cognito-identity.amazonaws.com:amr": "authenticated" 
    } 
    } 
} 

*您還可以根據您的需要將「authenticated」替換爲「未經驗證」,「graph.facebook.com」,「google ...」。