2017-02-17 100 views
0

我使用下面的代碼使用Amazon Cognito註冊用戶。然後,我想在用戶註冊時將文件上傳到Amazon S3 Bucket。使用Amazon Cognito上傳到Amazon S3登錄

一旦用戶註冊,我需要做些什麼來配置桶準備上傳? 謝謝

var roleArn = 'arn:aws:iam::123456:role/Cognito_Auth_Role'; 
    var bucketName = 'MY_BUCKET'; 
    AWS.config.region = 'eu-west-1'; 
     var poolData = { 
      UserPoolId : 'POOL_ID', // your user pool id here 
      ClientId : 'CLIENT_ID' // your app client id here 
     }; 
     var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData); 
     var userData = { 
      Username : 'username', // your username here 
      Pool : userPool 
     }; 
     var attributeList = []; 
     var password 
     //Create Bucket 
     var bucket = new AWS.S3({ 
     params: { 
      Bucket: bucketName 
     } 
    }); 

var dataEmail = { 
    Name : 'email', 
    Value : '[email protected]' // your email here 
}; 
var dataPhoneNumber = { 
    Name : 'phone_number', 
    Value : '+1234567890' // your phone number here with +country code and no delimiters in front 
}; 

...

var attributeEmail = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataEmail); 
var attributePhoneNumber = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataPhoneNumber); 
attributeList.push(attributeEmail); 
attributeList.push(attributePhoneNumber); 
var cognitoUser; 
userPool.signUp('username', 'password', attributeList, null, function(err, result){ 
    if (err) { 
     alert(err); 
     return; 
    } 
    cognitoUser = result.user; 
    console.log('user name is ' + cognitoUser.getUsername()); 

}); 

回答

2

您需要創建在Cognito聯合身份標識池。讓您的用戶池成爲特定身份池的身份提供者以獲得身份驗證身份。

上述註冊用戶與您的代碼後,你就需要用下面的代碼,以確認他,登錄並獲得AWS憑據(用自己的信息替換佔位符):

var cognitoUser = userPool.getCurrentUser(); 

if (cognitoUser != null) { 
    cognitoUser.getSession(function(err, result) { 
     if (result) { 
      console.log('You are now logged in.'); 

      // Add the User's Id Token to the Cognito credentials login map. 
      AWS.config.credentials = new AWS.CognitoIdentityCredentials({ 
       IdentityPoolId: 'YOUR_IDENTITY_POOL_ID', 
       Logins: { 
        'cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>': result.getIdToken().getJwtToken() 
       } 
      }); 
     } 
    }); 
} 
//call refresh method in order to authenticate user and get new temp credentials 
AWS.config.credentials.refresh((error) => { 
    if (error) { 
     console.error(error); 
    } else { 
     console.log('Successfully logged!'); 
    } 
    }); 

在那麼您將獲得AWS憑證,您可以使用主要的AWS SDK for JavaScript(s3客戶端)將文件上載到S3。

+0

你好。我收到來自Chrome控制檯的此錯誤:未捕獲的錯誤:無法讀取屬性'刷新'null –

+0

感謝百萬人,拯救了我的一天!試圖使用cognito將圖像上傳到S3時感到非常沮喪,然後遇到了您的代碼......謝謝。 –

+0

我說得太快了!事實證明,它使用Unauthenticated身份登錄,只要我禁用,我得到一個NotAuthorizedException異常! –