How to Get AccessToken Dynamically from Cognito OAuth2.0 in Electron JS

Viewed 483

Hello i use Electron JS for a desktop app which is related to a cloud plateform from which in needto get a list of Patients.

As far as now i can get it but with a static AccessToken. I really struggled to get it dynamic, please help.

Here is my code :

This is my configuration file where i specify Cognito Parameters :

export default {
s3: {
  REGION: 'YOUR_S3_UPLOADS_BUCKET_REGION',
  BUCKET: 'YOUR_S3_UPLOADS_BUCKET_NAME',
},
apiGateway: {
  REGION: 'YOUR_API_GATEWAY_REGION',
  URL: 'YOUR_API_GATEWAY_URL',
},
cognito: {
  REGION: 'eu-west-1',
  USER_POOL_ID: 'eu-west-1_P0Jcr7nig',
  APP_CLIENT_ID: '4m1utu56hjm835dshts9jg63ou',
  IDENTITY_POOL_ID: 'YOUR_IDENTITY_POOL_ID',
  authenticationFlowType: 'USER_PASSWORD_AUTH',
  AUTHENTICATION_FLOW_TYPE: 'USER_PASSWORD_AUTH',
},
API: {
    endpoints: [
      {
        name: 'PatientsList',
        endpoint: 'https://uo992r7huf.execute-api.eu-west-1.amazonaws.com/Stage/patients',
        //endpoint: 'https://uo992r7huf.execute-api.eu-west-1.amazonaws.com/Stage',
      },
    ],
  },
};

Auth.signIn({
 username: process.env.username,
 password: process.env.password,
}).then().catch(err => {
 console.log(err)});

In another file this is my getaccesstoken function which i export to the main

function getAccessToken() {
 const poolData = { 
  UserPoolId : COGNITO_USER_POOL_ID,
 ClientId : COGNITO_CLIENT_ID,
};
const userPool = new CognitoUserPool(poolData);
var authenticationData = {
      Username : process.env.username, // your username here
      Password : process.env.password, // your password here,
      authenticationFlowType: process.env.AUTHENTICATION_FLOW_TYPE,
      Pool : userPool
  };
  var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(
    authenticationData);
  var cognitoUser = new CognitoUser(authenticationData);
  cognitoUser.authenticateUser(authenticationDetails, {
      onSuccess: function (result) {
        console.log('access token + ' + result.getAccessToken().getJwtToken());
      },
      onFailure: function(err) {
       console.log(err);
      },
  });
}

And finally here is how i get the data in main :

The declarations :

  const  { Auth } = require('./cognitoAuth');
 const theAccessToken = require('./cognitoAuth');

The code :

  //Get Data From Cloud ECS
  const API_URL = 'https://uo992r7huf.execute-api.eu-west-1.amazonaws.com/Stage/patients';
  const headers = {
    "Content-Type": "application/json",
    //Authorization: theAccessToken.getAccessToken()
    Authorization: "eyJraWQiOiJBbE1DZnBCTHYyVUlNazhXSG4xaTk4RG1QNlFmcFpSSjFaSW1qcVVFZnVBPSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiI4OWYyZGMxZi1iMTI3LTQzM2QtODJhYS1iMjNkNWJhNzY5NGEiLCJjb2duaXRvOmdyb3VwcyI6WyJkb2N0b3IiXSwiZXZlbnRfaWQiOiI1OTM0ZmIwNC0yYTUzLTQ2NmQtYTU1Ni0zNTM3M2RhZmU1Y2UiLCJ0b2tlbl91c2UiOiJhY2Nlc3MiLCJzY29wZSI6ImF3cy5jb2duaXRvLnNpZ25pbi51c2VyLmFkbWluIiwiYXV0aF90aW1lIjoxNTk1NDI2NjQ2LCJpc3MiOiJodHRwczpcL1wvY29nbml0by1pZHAuZXUtd2VzdC0xLmFtYXpvbmF3cy5jb21cL2V1LXdlc3QtMV9QMEpjcjduaWciLCJleHAiOjE1OTcxNTUxMDUsImlhdCI6MTU5NzE1MTUwNSwianRpIjoiNGRkN2U5ZGUtYmQ2YS00NTg4LWIzZDAtMTVjMWM1NWQxY2Y2IiwiY2xpZW50X2lkIjoiNG0xdXR1NTZoam04MzVkc2h0czlqZzYzb3UiLCJ1c2VybmFtZSI6Ijg5ZjJkYzFmLWIxMjctNDMzZC04MmFhLWIyM2Q1YmE3Njk0YSJ9.LYvzPRBxvKw2P3gHwV8NhYPg_EB3F7ZK2F5HpRWHtBHksr6D4N5Fw56ZVupkRCxVJSq0f93DdljI7BBcBnp9d_hpLzmJLTfBhA3t870omTxalTqpGXN_SvsZmuwcfCX-awn1Um6x_-fhq3zcfPkB9FBljbtwPN-kvCc-Iynei9anVxXI686nIbkfbYfnuRnHrbY0vg8FtyDIDBMv277FPoJ96NwPD4mJvNBxQHi_KfWxQ1DmLiAC6c_l2jP_wawAPBv788CjD_8OlKBbjAHinGEkaL1K9vjI5MhNPyTA5ym1IaWar7Jr8RkUDzQGvqEUPKoOUe9PswmOOxLBjehMgQ"
    };
    //console.log('Token Value:', theAccessToken.getAccessToken());
    const getPatients = async(API_URL) => {
      try {
        //get data from cloud specifiying get method and headers which contain token
        const response = await fetch(API_URL,{
          method: 'GET', headers: headers}
          );
        var listPatients = await response.json();
        listPatients.items.forEach(patient => {
          //Checking what i got
          console.log(patient);
        });
        } catch(err) {
          console.log("Error" + err);
        }
        };
       getPatients(API_URL);

Now when i make it dynamic by specifying theAccessToken.getAccessToken I get this error, USER_SRP is not enabled even if specify it, when i asked team told me the cloud service doesn't want to enable it. So how can i get this access token please?

1 Answers

For a desktop app it is recommended to do these 2 things, according to security guidance:

  • Use Authorization Code Flow (PKCE)
  • Login via the system browser, so that the app never sees the user's password

I have a couple of Electron code samples that use Cognito, which you can easily run - maybe start here:

Related