AWS Cognito未经身份验证的登录错误(未定义窗口)[JS]

问题描述 投票:6回答:3

我正在使用AWS Cognito来用户用户池和身份验证。

我的注册工作正常,但我的登录功能引发了错误:

/node_modules/aws-sdk/lib/request.js:31 throw err; ^

ReferenceError:未定义窗口

这是功能:

app.post('/login', function(req, res, next) {

console.log("Email: " + req.body.email);
console.log("Password: " + req.body.password);

var authenticationData = {
  Username: req.body.username,
  Password: req.body.password
};

var authenticationDetails = new AWS.CognitoIdentityServiceProvider
  .AuthenticationDetails(authenticationData);

var poolData = {
  UserPoolId: '*removed for security*',
  ClientId: '*removed for security*'
};

var userPool = new AWS.CognitoIdentityServiceProvider.CognitoUserPool(
poolData);
var userData = {
Username: req.body.username,
Pool: userPool
};

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

cognitoUser.authenticateUser(authenticationDetails, {
  onSuccess: function(result) {
    console.log('access token + ' +   result.getAccessToken().getJwtToken());

  AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: '*removed for security*',
    Logins: {
      '*removed for security*': result
        .getIdToken().getJwtToken()
    }
  });

},
onSuccess: function(suc) {
  console.log('Login Successful!');
},
onFailure: function(err) {
        console.log('Login Unsuccessful');
  alert(err);
},

});
});

我非常确定在执行以下行时出现错误,因为我在整个代码中放置了调试日志,它只执行到此处:

var cognitoUser = new AWS.CognitoIdentityServiceProvider.CognitoUser(userData);
javascript amazon-web-services
3个回答
13
投票

AWS Cognito JS SDK旨在用于客户端。如果您希望在服务器端使用它,可以使用window-mock库来模拟窗口对象。

npm install --save window-mock

然后,在文件顶部和函数之前,添加以下内容:

import WindowMock from 'window-mock';
global.window = {localStorage: new WindowMock().localStorage};

在此之后,你将得到navigator not defined错误,你可以解决:

global.navigator = () => null;

然后你应该能够在任何一个回调上打印结果。


7
投票

我发现只有在用户池中启用“记住用户的设备”时,才能在NodeJS中运行时出现此问题。如果我禁用相同,则不会发生错误。它确实有意义,因为正如Sam所说,它意味着在客户端使用,因为从服务器端运行将不具备这些浏览器属性。我得到类似的相关错误“ReferenceError:导航器未定义”。


1
投票

如果您在nodejs中运行并且不想要记住任何设备,请在所有设备管理部分中设置“否”。 CogintoUser API尝试从设备获取UserAgent并假定导航器为设备。

© www.soinside.com 2019 - 2024. All rights reserved.