LoginSignup
6
7

More than 5 years have passed since last update.

Cognitoの認証済みユーザーでセッションを確立する

Posted at

ちょっとハマったのでまとめました。ポイントは、取得したユーザーのIdTokenをLogin Mapに入れる時に、cognito-idp.ap-northeast-1.amazonaws.com/COGNITO_USER_POOL_ID

COGNITO_USER_POOL_ID
の部分に、
User Pool ID(ap-northeast-1_XXXXXXX)
を入れることです。

(ここをIdentity Pool IDだと思っていてミスりました。その場合は"Invalid login token. Issuer doesn't match providerName"というエラーが返ってきます。)

AWS_REGION →CognitoがあるAWSのリージョンです
COGNITO_IDENTITY_POOL_ID →Identity Pool IDです。
COGNITO_USER_POOL_ID →User Pool IDです
COGNITO_CLIENT_ID →IdentityPoolに対して設定されたUser PoolのAppのClient IDです。

下はセッション確立用の関数です

var validateSession = function(){
  return new Promise(function(resolve, reject){
    AWS.config.region = AWS_REGION;
    var data = {
      UserPoolId: COGNITO_USER_POOL_ID,
      ClientId: COGNITO_CLIENT_ID
    };
    var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data);
    var cognitoUser = userPool.getCurrentUser();
    if(cognitoUser != null){
      cognitoUser.getSession(function(err, sessresult){
        if(sessresult){
          var cognitoParams = {
            IdentityPoolId: COGNITO_IDENTITY_POOL_ID,
            Logins: {'cognito-idp.ap-northeast-1.amazonaws.com/COGNITO_USER_POOL_ID': sessresult.getIdToken().getJwtToken()
            }
          };
          AWS.config.credentials = new AWS.CognitoIdentityCredentials(cognitoParams);
          AWS.config.credentials.get(function(err){
            if(err){
              reject(err);
            }
          });
            resolve();
          });
        }else{
          reject(err);
        }
      });
    }else{
      reject('No cognito User');
    }
  });
};

参考にしたサイト

http://dev.classmethod.jp/cloud/aws/login-form-by-using-aws-sdk-for-javascript/
http://docs.aws.amazon.com/ja_jp/cognito/latest/developerguide/getting-credentials.html#getting-credentials-1.javascript
https://github.com/aws/amazon-cognito-identity-js/issues/40

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7