Amazon-cognito-identity-js: Question about the ClientId

Created on 19 Aug 2016  路  12Comments  路  Source: amazon-archives/amazon-cognito-identity-js

My question is where is ClientId coming from?

Thanks in advance for any clue.

AWSCognito.config.region = 'us-east-1'; //This is required to derive the endpoint

var poolData = { 
    UserPoolId : '...', // Your user pool id here
    ClientId : '...' // Your client id here
};

Most helpful comment

it may take you 5 minutes to complete a better example

Actually, doc updates seem to take me at least twice as long as the code itself - that PR update is ~10 hours work :cry:

All 12 comments

Command Line: aws cognito-idp list-user-pool-clients --user-pool-id <your-pool-id> --max-results <number>

Or AWS Console: Cognito User Pools, then "App" tab on left side

Thank you for your quick response.
Thank you Sir.

@cdock1029

I still have questions. I am working on a IoT project, using AWS S3 static hosting. The framework I am using is react-redux. I just want to do the typical sign-up and login pages. I can not find documents specific to sign-up and log-in. I mean the full steps of doing the login and sign-up. I found many documents, yet I can only find snippets, other than a full work flow.

The following code is from a typical client.js file in a React project. I always got errors.
I have create the identify pool.
but the AWSCognito.config.credentials just return null. I guess that
new AWSCognito.CognitoIdentityCredentials() should be a asynchronous function.

AWSCognito.config.credentials.get() should be called in the callback function.

AWSCognito.config.credentials = new AWSCognito.CognitoIdentityCredentials({
 IdentityPoolId: 'us-east-1:bf6edaa6-69fb-4e81-bdd5-cd7xxxxxxxx'
})

Can you give me some clue?

AWSCognito.config.region = 'us-east-1'; //This is required to derive the endpoint
AWSCognito.config.credentials = new AWSCognito.CognitoIdentityCredentials({
 IdentityPoolId: 'us-east-1:bf6edaa6-69fb-4e81-bdd5-cd7xxxxxxxx'
})

AWSCognito.config.credentials.get(function(){
  console.log(AWSCognito.config.credentials)
  var accessKeyId = AWSCognito.config.credentials.accessKeyId;
  var secretAccessKey = AWSCognito.config.credentials.secretAccessKey;
  var sessionToken = AWSCognito.config.credentials.sessionToken;

  console.log(accessKeyId, secretAccessKey, sessionToken)
});

I do believe that I can solve these problems.

I just recommend creators of this library provide more self-contained examples from ground-up.

Since you are creators of these libraries, it may take you 5 minutes to complete a better example. Yet, your 5 minutes may save 5 days or 5 weeks for other developers.

I don't think you are getting credentials correctly.

You need to use UserPoolId and ClientId to setup the cognito SDK.
Then authenticate a user with the cognito SDK (and user's username and password), and you will get back an ID token, which you can use to instantiate AWS credentials.

See Use case 4 on the README of this repo.

I believe the example Conor provided should do the trick.

Updated readme PR #119 includes extra info on how to get config, since I had some of the same confusion starting out.

@cdock1029
@itrestian
@simonbuchan

Thank you for your information.

I still have errors reported when I try the User Case 4.
From my Chrome console I got

Uncaught TypeError: Cannot read property 'BigInteger' of undefined.
I am using webpack and react-redux, any clue about this>

image

Sorry, this was my bug - I broke it in #112 and fixed it in #121, but it's not been merged yet. Neither have been pushed to npmjs.org though, you are cloning github still?

it may take you 5 minutes to complete a better example

Actually, doc updates seem to take me at least twice as long as the code itself - that PR update is ~10 hours work :cry:

This should work with the dist files on github.

@cdock1029
@simonbuchan

Thank you for your response!

I tried according to your suggestion, but I still got the same problems. I just got stuck here for the past week! I tested according to Use Case 4 (in the middle of the following client.js file). Previously I used Firebase, which worked fine for logging in and out, until I found that I had to implement a TLS 1.2 library for my IoT before I can connect my IoT to Firebase. Then I switched to AWS. I think that I have set up the User Pool and Identity Pool correctly this time. I granted the identity pool unauthenticated logging right.

Would you please give me the details here, since I also found it confusing when you referenced materials somewhere else.

aws cognito-idp create-user-pool-client --user-pool-id  us-east-1_qWYXXXXXX --client-name clientname1
{
    "UserPoolClient": {
        "UserPoolId": "us-east-1_qWYpXXXXXX",
        "LastModifiedDate": 1471871472.647,
        "ClientId": "5gvf9g9ee0dtvb9rm3acoXXXX",
        "RefreshTokenValidity": 30,
        "CreationDate": 1471871472.647,
        "ClientName": "clientname1"
    }
}

aws cognito-idp list-user-pool-clients --user-pool-id  us-east-1_qWYpdXXXX --max-results 10
{
    "UserPoolClients": [
        {
            "ClientName": "clientname1",
            "UserPoolId": "us-east-1_qWYpdXXXX",
            "ClientId": "5gvf9g9ee0dtvb9rm3acoXXXX"
        }
    ]
}

Since Webpack has becoming an industry standard, would you please make clear how to set up Cognito using Weback and React in doing the typical logging in and out?

The following is my index.html

<!DOCTYPE html>
<html lang='zh-cn'>
  <head>
    <meta charset='UTF-8'/>
    <script src="dist/jsbn.js"></script>
    <script src="dist/jsbn2.js"></script>
    <script src="dist/sjcl.js"></script>
    <script src="dist/aws-cognito-sdk.js"></script>
    <script src="dist/amazon-cognito-identity.min.js"></script>
    <script src="dist/aws-sdk.min.js"></script>      
  </head>
  <body>
    <div id='app'></div>
  </body>
</html>

The following is the webpack.config.js for development purpose

require('babel-polyfill')

// Webpack config for creating the production bundle.
var path = require('path')
var webpack = require('webpack')
var CleanPlugin = require('clean-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var strip = require('strip-loader')
var CopyWebpackPlugin = require('copy-webpack-plugin')

var projectRootPath = path.resolve(__dirname, '../')
var srcPath = path.resolve(__dirname, '../', 'src')
var buildPath = path.resolve(projectRootPath, './build')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  devtool: 'inline-source-map',

  context: path.resolve(__dirname, '../'),

  entry: {
    'main': [
      'bootstrap-sass!./src/theme/bootstrap.config.js',
      'font-awesome-webpack!./src/theme/font-awesome.config.js',
      './src/client.js'
    ]
  },

  output: {
    path: buildPath,
    filename: '[name].js'
  },

  module: {
    loaders: [
      { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel'},
      { test: /\.json$/, loader: 'json-loader' },
      { test: /\.less$/, loader: 'style!css?modules&importLoaders=2&sourceMap&localIdentName=[local]___[hash:base64:5]!autoprefixer?browsers=last 2 version!less?outputStyle=expanded&sourceMap' },
      { test: /\.scss$/, loader: 'style!css?modules&importLoaders=2&sourceMap&localIdentName=[local]___[hash:base64:5]!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded&sourceMap' },
      { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
      { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
      { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream" },
      { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file" },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml" },
      { test: /(png|jpg|gif)$/, loader: 'url-loader?limit=10240' }
    ]
  },

  progress: true,

  resolve: {
    modulesDirectories: [
      'src',
      'node_modules'
    ],
    extensions: ['', '.json', '.js', '.jsx']
  },

  devServer: {
    contentBase: projectRootPath,
    historyApiFallback: true,
    hot: true,
    inline: true,
    progress: true
  },


  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new CopyWebpackPlugin([
        {from: path.join(srcPath, 'assets', 'favicon.ico'), to: '/'},
        {from: path.join(srcPath, 'assets', 'dist', 'amazon-cognito-identity.min.js'), to: '/dist'},
        {from: path.join(srcPath, 'assets', 'dist', 'amazon-cognito-identity.min.js.map'), to: '/dist'},
        {from: path.join(srcPath, 'assets', 'dist', 'aws-cognito-sdk.js'), to: '/dist'},
        {from: path.join(srcPath, 'assets', 'dist', 'aws-cognito-sdk.min.js'), to: '/dist'},
        {from: path.join(srcPath, 'assets', 'dist', 'aws-cognito-sdk.min.js.map'), to: '/dist'},
        {from: path.join(srcPath, 'assets', 'dist', 'aws-sdk.min.js'), to: '/dist'},
        {from: path.join(srcPath, 'assets', 'dist', 'jsbn.js'), to: '/dist'},
        {from: path.join(srcPath, 'assets', 'dist', 'jsbn2.js'), to: '/dist'},
        {from: path.join(srcPath, 'assets', 'dist', 'sjcl.js'), to: '/dist'}
    ]),

    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery",
      "window.jQuery": "jquery"
    }),

    new HtmlWebpackPlugin({
      title: '鍖楁枟瀹夊悍',
      template: path.join(srcPath, 'assets', 'index.html')
    }),

    // ignore dev config
    new webpack.IgnorePlugin(/\.\/dev/, /\/config$/),

    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
        PORT:     JSON.stringify(process.env.PORT),
        APIPORT:  JSON.stringify(process.env.APIPORT)
      },

      __CLIENT__:       true,
      __SERVER__:       false,
      __DEVELOPMENT__:  true,
      __DEVTOOLS__:     true
    })
  ]
}

The following is entry file client.js of my project. I intended to use S3 static hosting.

import 'babel-polyfill'
import React                    from 'react'
import ReactDOM                 from 'react-dom'
import {Provider}               from 'react-redux'
import {Router, browserHistory} from 'react-router'
import {syncHistoryWithStore}   from 'react-router-redux'
import {ReduxAsyncConnect}      from 'redux-async-connect'
import useScroll                from 'scroll-behavior/lib/useStandardScroll' 
import createStore              from './redux/create'
import ApiClient                from './helpers/ApiClient'

//diff
//import Firebase                 from 'firebase'
import getRoutes                from './routes'

//const firebase        = new Firebase('https://bdak.firebaseio.com')
const client            = new ApiClient()
const _browserHistory   = useScroll(() => browserHistory)()
const dest              = document.getElementById('app')

const store             = createStore(_browserHistory, client, window.__data)
const history           = syncHistoryWithStore(_browserHistory, store)

//
var authenticationData = {
    Username : 'username',
    Password : 'password',
}

var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData)
var poolData = { 
    UserPoolId : 'us-east-1_xxxxxx', // Your user pool id here
    ClientId : '5gvf9g9ee0dtvb9rxxxxxxxxxx' // Your client id here
}

var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
var userData = {
    Username : 'username',
    Pool : userPool
};

var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);

cognitoUser.authenticateUser(authenticationDetails, {
    onSuccess: function (result) {
      console.log('access token + ' + result.getAccessToken().getJwtToken());
      AWS.config.credentials = new AWS.CognitoIdentityCredentials({
          IdentityPoolId : 'us-east-1:xxxxxxxxxx-69fb-4e81-bdd5-xxxxxxxxxxxx',
          Logins : {
              'us-east-1_qWYxxxxxx' : result.getIdToken().getJwtToken()
          }
        });
    },

    onFailure: function(err) {
        alert(err);
    },

});
//

const component = (
  <Router render={(props) => <ReduxAsyncConnect {...props} helpers={{client}} filter={item => !item.deferred} /> } history={history}>
    {getRoutes(store)}
  </Router>
)

ReactDOM.render(
  <Provider store={store} key='provider'>
    {component}
  </Provider>,
  document.getElementById('app')
)

Was this page helpful?
0 / 5 - 0 ratings