AWS Cognito - JavaScript中的开发人员身份验证身份(浏览器) [英] AWS Cognito - Developer Authenticated Identities in JavaScript(Browser)

查看:150
本文介绍了AWS Cognito - JavaScript中的开发人员身份验证身份(浏览器)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在浏览器脚本中获取凭据。

I have trouble getting credentials in a browser script.

验证服务器返回cognito_identityId和cognito_token。

The authentication server returns cognito_identityId and cognito_token.

然后我设置了一个Cookie:

Then I set a Cookie:


  • $。cookie('cognito_identityId')

  • $。 cookie('cognito_token')

我试图在浏览器上以4种方式获取凭据,所有失败:

I tried to get credentials in 4 ways on the browser, and all Failed:


  1. CognitoIdentityCredentials

  1. CognitoIdentityCredentials

AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: 'us-east-1:xxxxxxxxxxxx'
    IdentityId: $.cookie('cognito_identityId'),
    Logins: {
        'myauth': $.cookie('cognito_token')
    }
});

// =>错误:在参数中缺少必需的密钥'IdentityId'

// => Error: Missing required key 'IdentityId' in params

assumeRoleWithWebIdentity

assumeRoleWithWebIdentity

var params = {
  RoleArn: 'arn:aws:iam::xxxxxxxxxxxx:role/Cognito_xxxxxxxAuth_Role',
  RoleSessionName: 'xxxxxxxxxxx',
  WebIdentityToken: $.cookie('cognito_token'),
  DurationSeconds: 900,
  ProviderId: 'myauth'
};
var sts = new AWS.STS({apiVersion: '2011-06-15'});
sts.assumeRoleWithWebIdentity(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

// => AccessDenied:未授权执行sts:AssumeRoleWithWebIdentity

// => AccessDenied: Not authorized to perform sts:AssumeRoleWithWebIdentity

PolicyDocument

PolicyDocument

{
"Version": "2012-10-17",
"Statement": [
  {
    "Sid": "",
    "Effect": "Allow",
    "Principal": {
      "Federated": "cognito-identity.amazonaws.com"
    },
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": {
      "StringEquals": {
        "cognito-identity.amazonaws.com:aud": "us-east-1:xxxxxxxxxxxxx"
      },
      "ForAnyValue:StringLike": {
        "cognito-identity.amazonaws.com:amr": "authenticated"
      }
    }
  }
]
}




  1. GetCredentialsForIdentity

  1. GetCredentialsForIdentity

var params = {
    IdentityId: $.cookie('cognito_identityId'),
    Logins: {
      "myauth": $.cookie('oauth.io_token')
    }
};
var cognitoidentity = new AWS.CognitoIdentity({apiVersion: '2014-06-30'});
cognitoidentity.getCredentialsForIdentity(params, function(err, data) {
  if (err) {
    console.log(err, err.stack); // an error occurred
  }
  else {
    console.log(data);           // successful response
  }
});

// => InvalidParameterException:请提供有效的公共提供者

// => InvalidParameterException: Please provide a valid public provider

WebIdentityCredentials

WebIdentityCredentials

AWS.config.credentials = new AWS.WebIdentityCredentials({
    RoleArn: 'arn:aws:iam::xxxxxxxx:role/Cognito_xxxxxxxxxxAuth_Role',
    WebIdentityToken: $.cookie('cognito_token')
});

// =>错误:有2个验证错误:
// * MissingRequiredParameter:在params中缺少必需的键'IdentityPoolId'
// * MissingRequiredParameter:在params中缺少必需的键'IdentityId'

// => Error: There were 2 validation errors: // * MissingRequiredParameter: Missing required key 'IdentityPoolId' in params // * MissingRequiredParameter: Missing required key 'IdentityId' in params

问题:


  • 我做错了什么?

  • What am I doing wrong?

使用它的正确方法是什么?

What is the correct way to use this?

谢谢。

感谢您的好意。

我提出了建议,但没有改变。

I tyied your advice, but did not change.

错误消息。

POST https://cognito-identity.us-east-1.amazonaws.com/ 400 (Bad Request)
POST https://cognito-identity.us-east-1.amazonaws.com/ 400 (Bad Request)
Error: Missing required key 'IdentityId' in params
    at fail (chrome-extension://hmjdjbikinkmjbilihjibcihbkbjdgjf/bower_components/aws-sdk-js/dist/aws-sdk.js:2163:37)
    at validateStructure (chrome-extension://hmjdjbikinkmjbilihjibcihbkbjdgjf/bower_components/aws-sdk-js/dist/aws-sdk.js:2084:14)
    at validateMember (chrome-extension://hmjdjbikinkmjbilihjibcihbkbjdgjf/bower_components/aws-sdk-js/dist/aws-sdk.js:2110:21)
    at validate (chrome-extension://hmjdjbikinkmjbilihjibcihbkbjdgjf/bower_components/aws-sdk-js/dist/aws-sdk.js:2059:10)
    at Request.VALIDATE_PARAMETERS (chrome-extension://hmjdjbikinkmjbilihjibcihbkbjdgjf/bower_components/aws-sdk-js/dist/aws-sdk.js:800:32)
    at Request.callListeners (chrome-extension://hmjdjbikinkmjbilihjibcihbkbjdgjf/bower_components/aws-sdk-js/dist/aws-sdk.js:3913:20)
    at callNextListener (chrome-extension://hmjdjbikinkmjbilihjibcihbkbjdgjf/bower_components/aws-sdk-js/dist/aws-sdk.js:3903:12)
    at chrome-extension://hmjdjbikinkmjbilihjibcihbkbjdgjf/bower_components/aws-sdk-js/dist/aws-sdk.js:787:9
    at finish (chrome-extension://hmjdjbikinkmjbilihjibcihbkbjdgjf/bower_components/aws-sdk-js/dist/aws-sdk.js:126:7)
    at chrome-extension://hmjdjbikinkmjbilihjibcihbkbjdgjf/bower_components/aws-sdk-js/dist/aws-sdk.js:142:9

链接下面有源代码。

< a href =https://github.com/bisque33/my-custom-dictionary =nofollow noreferrer> https://github.com/bisque33/my-custom-dictionary

,服务器端是AWS Lambda函数。

and server side is a AWS Lambda Function.

var aws = require('aws-sdk');
aws.config.region = 'us-east-1';
var cognitoidentity = new aws.CognitoIdentity();
var identityPoolId = 'us-east-1:0dccff0d-5fd7-4d14-b38f-d27204feaecc';

console.log('Loading function');

exports.handler = function(event, context) {
    console.log('token: %s', event.token);

    var params = {
        IdentityPoolId: identityPoolId,
        Logins: {
            'oauth.io': event.token
        }
    };
    cognitoidentity.getOpenIdTokenForDeveloperIdentity(params,function(err,data){
        if(err){
            console.log(err);
            context.fail('Something went wrong');
        }else{
            context.succeed(data);
        }
    });
};

此程序为Google-Chrome-Extension。

This program is Google-Chrome-Extension.


  • AWS Lambda函数通过getOpenIdTokenForDeveloperIdentity返回令牌。

  • app / scripts / popup.js调用Lambda函数并设置cookie。

  • app / scripts / background.js调用AWS.config.credentials.get,并返回错误。

我使用它错了?

谢谢有关其他信息。

错误出现在background.js上的104行

Error appears on 104 line on background.js

AWS.config.credentials.get(function(){

和115行背景。 js

and 115 line on background.js

      dataset.synchronize(

而且,我的解释还不够.Facebook身份验证需要域名(例如http:// example.com)。但是,Google-Chrome-Ext没有域名。它有域名'镀铬的扩展:// XXXX XXXXXXXXXXXXXXXX。然后,我使用 https://oauth.io 。它代理任何身份验证并接受chrome-extension域。

And, My explaination was not enough. Facebook authentication needs the domain(ex. http :// example.com). However, Google-Chrome-Ext does not have domain. It has a domain 'chrome-extension://xxxxxxxxxxxxxxxxxxxx'. Then, I use https://oauth.io. It proxies any authentication and accepts chrome-extension domain.

Popup.js通过oauth.io sdk进行Facebook身份验证。它获取了一个facebook令牌,并提供给getOpenIdTokenForDeveloperIdentity。我认为facebook token.substr(0,14)是独一无二的。但是,如果错了,我会使用另一个唯一标识符(例如电子邮件地址。)

Popup.js does Facebook authentication through oauth.io sdk. It gets a facebook token, and gives to getOpenIdTokenForDeveloperIdentity. I think facebook token.substr(0,14) is unique. But, If it is wrong, I use another unique identifier(ex. email-address.)

对不起,我是错误。 AWS.config.credentials.get给出错误:

Sorry, I was wrong. AWS.config.credentials.get gives an Error:

Error: Invalid login token.

并且,dataset.synchronize显示此错误:

And, dataset.synchronize shows this Error:

Error: Missing required key 'IdentityId' in params


推荐答案

第一种方法,使用 CognitoIdentityCredentials ,很可能是您采取的最佳方法。我无法确切地发现导致错误的原因,但让我们尝试一些事情:

The first approach you have, using CognitoIdentityCredentials, is most likely the best approach for you to take. I can't spot exactly what's causing the error for you but lets try a couple things:


  1. 使用开发人员身份验证身份,您需要在初始化CognitoIdentityCredentials 的。您需要从对GetOpenIdTokenForDeveloperIdentity的调用中获取IdentityId值。但是,您不需要在Cookie中保留IdentityId值,因为 CognitoIdentityCredentials 将默认情况下,在浏览器的本地存储中缓存id。

  2. 至于您的登录地图:看起来您正在尝试使用开发人员身份验证身份。使用JavaScript SDK,使用密钥'cognito-identity.amazonaws.com'并确保该值是从后端调用返回的标记getOpenIdTokenForDeveloperIdentity

  1. When using Developer Authenticated Identities, you do need to specify the IdentityId when initializing CognitoIdentityCredentials. You need to get the IdentityId value from the call to GetOpenIdTokenForDeveloperIdentity. However, you shouldn't need to preserve the IdentityId value in a cookie as CognitoIdentityCredentials will cache the id by default in the browser's local storage.
  2. As for your Logins map: It looks like you're trying to use Developer Authenticated Identities. With the JavaScript SDK, use the key 'cognito-identity.amazonaws.com' and make sure the value is the token returned from your backend's call to getOpenIdTokenForDeveloperIdentity.

如果您在使用CognitoIdentityCredentials方法时仍有问题,请在此处回复更多信息例如,当您收到错误消息时正在调用的确切方法/代码,以及在调用CognitoIdentityCredentials构造函数之前的params输入的跟踪输出(即使用console.log('%o',..)) 。

If you continue to have problem using the CognitoIdentityCredentials approach, please reply here with some more info such as the exact method/code you're calling when you receive the error message, and the traced output (i.e. with console.log('%o',..)) of the params input just before your call to the CognitoIdentityCredentials constructor.

我仍然我需要确切地知道您收到错误的代码行,但根据提供的信息,我认为我仍然可以提供帮助...

I still need to know exactly which line of code you receive the error on, but based on the information provided I think I can still help...

根据我所看到的情况 background.js ,它看起来就像您尝试使用Developer Authenticated Identities提供程序初始化CognitoIdentityCredentials一样。这是我猜你收到错误的地方。

Based on what I see in background.js, it looks like you're trying to initialize CognitoIdentityCredentials using a Developer Authenticated Identities provider. This is where I'm guessing that you're receiving the error.

然而,在 Popup.js ,看起来你正在尝试用Facebook验证用户身份。如果您使用Facebook对用户进行身份验证,则应在使用Cognito时将facebook访问令牌传递到您的登录地图中。只需使用 graph.facebook.com 作为登录地图中的密钥和来自Facebook的访问令牌。有关如何执行此操作的更多详细信息,请参阅Amazon Cognito开发人员指南的 Facebook集成主题

However, in Popup.js, it looks like you're trying to authenticate the user with Facebook. If you're authenticating your users with Facebook, you should just pass the facebook access token into your Logins map when using Cognito. Just use graph.facebook.com as the key in the Logins map and the access token from Facebook. More detail on how to do this is in the Facebook Integration topic of the Amazon Cognito developer guide.

我们可以让开发人员身份验证身份为您服务,但在这种情况下,它看起来不适合您,因为您实际上没有对Lambda函数中的标识进行任何其他身份验证,而是您传递给<$ c $的唯一用户标识符c> getOpenIdTokenForDeveloperIdentity 操作似乎是facebook令牌,但由于令牌本身在用户会话之间即使对同一用户也会发生变化,因此这种方式并不好。通常,良好的唯一标识符是内部系统使用的电子邮件地址或用户ID。

We can get Developer Authenticated Identities to work for you, but in this case, it doesn't look like the right solution for you since you're not actually doing any additional authentication on the identity in your Lambda function and the unique user identifier that you're passing into the getOpenIdTokenForDeveloperIdentity operation appears to be the facebook token, which is not good by the way since the token itself will change between user sessions even for the same user. Usually a good unique identifier is an email address or a user id used by an internal system.

由于您最终尝试使用Facebook进行登录,而且Amazon Cognito已经 Facebook的内置集成,您要做的最好的事情是从Facebook获取访问令牌并直接将Facebook令牌传递给Cognito的登录地图。我不确定这是否适用于Auth.io(我只是不熟悉它),但只要Auth.io为您的JavaScript代码提供一个bonefide facebook令牌并且您添加相同的Facebook App ID Auth.io和Amazon Cognito的控制台都应该可以使用。但是,您提到要使用Auth.io来避免Facebook重定向到登录页面。我可能会弄错,但我很确定你是否正在使用 Facebook的JavaScript SDK 您不需要重定向页面。如果您正在进行 Facebook的手动构建登录流程,您应该只需要重定向页面

Since you're ultimately trying to use Facebook for login and Amazon Cognito has built-in integration for Facebook, the best thing for you to do is get an access token from Facebook and pass in the Facebook token to Cognito's login map directly. I'm not sure if this will work with Auth.io or not (I'm just not familiar with it), but as long as Auth.io gives your JavaScript code a bonefide facebook token and you add the same Facebook App ID to both Auth.io and Amazon Cognito's Console, it should work. However, you mentioned you want to use Auth.io to avoid Facebook doing a redirect to a landing page. I could be mistaken, but I'm pretty sure if you're using Facebook's JavaScript SDK you won't need a redirect page. You should only need the redirect page if you're doing Facebook's Manually Build a Login Flow.

这篇关于AWS Cognito - JavaScript中的开发人员身份验证身份(浏览器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆