【问题标题】:Get Access Token from EndPoint LocalStorage AWS Cognito从 EndPoint LocalStorage AWS Cognito 获取访问令牌
【发布时间】:2020-11-20 01:39:30
【问题描述】:

我使用 aws cognito 和 oauth2 在电子 js 中工作。我需要从云端点中的存储中动态获取 accessToken 以获得获取数据列表的授权。就目前而言,如果我以静态方式指定令牌,我可以获得列表。但我需要它动态。令牌的关键是 CognitoIdentityServiceProvider.COGNITO_CLIENT_ID.username.accessToken 但即使我配置了 Cognito,我似乎也无法得到它

这是我的配置文件代码,其中还包含登录功能:

const  { Auth } = require('@aws-amplify/auth');
const { Amplify } = require('aws-amplify');
const AmazonCognitoIdentity = require('amazon-cognito-identity-js');
const CognitoUserPool = require('amazon-cognito-identity-js-node').CognitoUserPool;
const CognitoUserSession = require('amazon-cognito-identity-js-node').CognitoUserSession;
const CognitoUser = require('amazon-cognito-identity-js-node').CognitoUser;
const CognitoIdToken = require('amazon-cognito-identity-js-node').CognitoIdToken;
const CognitoAccessToken = require('@aws-amplify/auth');
const CognitoRefreshToken = require('amazon-cognito-identity-js-node').CognitoRefreshToken;
const COGNITO_USER_POOL_ID = 'eu-west-1_P0Jcr7nig';
const COGNITO_CLIENT_ID = '4m1utu56hjm835dshts9jg63ou';
const AWS_REGION = 'eu-west-1';

Amplify.configure({
 Auth: {
     // OPTIONAL - Enforce user authentication prior to accessing AWS resources or not
 mandatorySignIn: false,
  region: AWS_REGION,
  userPoolId: COGNITO_USER_POOL_ID,
   userPoolWebClientId: COGNITO_CLIENT_ID,
  // OPTIONAL - Manually set the authentication flow type. Default is 'USER_SRP_AUTH'
   authenticationFlowType: 'USER_PASSWORD_AUTH',

oauth: {
  domain: "https://edc-echosens-cloud.auth.eu-west-1.amazoncognito.com",
  scope: ["email", "profile", "openid"],
  redirectSignIn: "http://localhost:1962/",
  redirectSignOut: "http://localhost:1962/",
  responseType: "code", // or 'token', note that REFRESH token will only be generated when the responseType is code
},

API: {
  endpoints: [
    {
      name: 'PatientsList',
      endpoint: 'https://url',
    },
  ],
},
},
  });

 Auth.signIn({
  username: 'doctoredc@yopmail.com',
  password: 'kinG2804*D',
 }).then().catch(err => {
  console.log(err)});

  function getAccessToken() {
   const poolData = { 
     UserPoolId : COGNITO_USER_POOL_ID,
     ClientId : COGNITO_CLIENT_ID,
   };
   const userPool = new CognitoUserPool(poolData);
    var authenticationData = {
     Username : 'mymail@mail.com', // your username here
     Password : 'kinG2804*D', // your password here,
     authenticationFlowType: 'USER_PASSWORD_AUTH',
     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);
           },
        });
}


// You can get the current config object
//const currentConfig = Auth.configure();
exports.Auth = Auth;
 module.exports.getAccessToken = getAccessToken

我进行了池配置,指定了 api url 和凭据。我还添加了一个 Auth.signIn 函数和一个 getAccessToken 函数。然后这是在我的 main 中调用函数的代码

 const API_URL = 'https://url';
  const headers = {
    "Content-Type": "application/json",
    Authorization: theAccessToken.getAccessToken()
    };
    console.log('Token Value:', theAccessToken.getAccessToken());
    const getPatients = async(API_URL) => {
      try {
        const response = await fetch(API_URL,{
          method: 'GET', headers: headers}
          );
        const json = await response.json();
        console.log(json);
      } catch (error) {
        console.log(error);
      }
      };
   getPatients(API_URL);

问题是使云端点指定 authFlowType 为 USER_PASSWORD_AUTH 的团队,但我收到错误消息 USER_SRP_AUTH 未为客户端启用。他们使用 USER_PASSWORD_AUTH。所以它阻止了我,我不知道没有动态获取访问令牌有什么问题。

请帮助我,我非常接近答案。谢谢

【问题讨论】:

    标签: amazon-web-services oauth-2.0 electron amazon-cognito access-token


    【解决方案1】:

    使用 OAuth 时,您的应用永远不会看到密码。为了动态,Electron 桌面应用程序应该通过系统浏览器执行登录。您还应该使用授权代码流(PKCE)。这两件事应该能够实现最佳的安全性和可用性。

    怎么做

    我有几个使用 Cognito 的 Electron 示例,您可以很容易地运行它们。我没有使用 Amplify,因为我更喜欢开源安全库:

    当然,您可以选择做一些稍微不同的事情,但桌面应用程序的 OAuth 很棘手,这可能会给您一些想法。

    【讨论】:

    • 谢谢你的回答,我会调查的。它将帮助我理解 COGNITO,即使我暂时只需要知道一种动态调用 CognitoIdentityServiceProvider.userpoolid.username.accessToken 的方法。不过谢谢
    猜你喜欢
    • 1970-01-01
    • 2018-04-01
    • 2018-06-07
    • 2020-10-27
    • 2021-01-05
    • 2021-12-21
    • 2020-09-28
    • 2019-10-16
    相关资源
    最近更新 更多