Coder Social home page Coder Social logo

amazon-archives / amazon-cognito-auth-js Goto Github PK

View Code? Open in Web Editor NEW
424.0 47.0 232.0 1 MB

The Amazon Cognito Auth SDK for JavaScript simplifies adding sign-up, sign-in with user profile functionality to web apps.

License: Apache License 2.0

JavaScript 100.00%

amazon-cognito-auth-js's Introduction

Amazon Cognito Auth SDK for JavaScript

NOTE: We have discontinued developing this library as part of this GitHub repository. You can still reach us by creating an issue on the AWS Amplify GitHub repository or posting to the Amazon Cognito Identity forums.

Read more about OAuth flows with Amplify JS


You can now use Amazon Cognito Auth to easily add sign-in and sign-out to your mobile and web apps. Your user pool in Amazon Cognito is a fully managed user directory that can scale to hundreds of millions of users, so you don't have to worry about building, securing, and scaling a solution to handle user management and authentication.

For more information about this new feature, see Amazon Cognito User Pools App Integration and Federation GA Release.

We welcome developer feedback on this project. You can reach us by creating an issue on the GitHub repository or posting to the Amazon Cognito Identity forums:

Introduction

The Amazon Cognito Auth SDK for JavaScript simplifies adding sign-up, sign-in with user profile functionality to web apps.

Instead of implementing a UI for sign-up and sign-in, this SDK provides the UI via a hosted page. It supports sign-up, sign-in, confirmation, multifactor authentication, and sign-out.

Setup

There are two ways to install the Amazon Cognito Auth SDK for JavaScript and its dependencies, depending on your project setup and experience with modern JavaScript build tools:

  • Download the JavaScript libraries and include them in your HTML, or

  • Install the dependencies with npm and use a bundler like webpack.

Install using separate JavaScript files

This method is simpler and does not require additional tools, but may have worse performance due to the browser having to download multiple files.

Download the following JavaScript file for the required library and place it in your project:

  1. The Amazon Cognito Auth SDK for JavaScript, from /dist/amazon-cognito-auth.min.js

Optionally, to use other AWS services, include a build of the AWS SDK for JavaScript.

Include all of the files in your HTML page before calling any Amazon Cognito Auth SDK APIs:

<script src="/path/to/amazon-cognito-auth.min.js"></script>
<!-- optional: only if you use other AWS services -->
<script src="/path/to/aws-sdk-2.6.10.js"></script>

Using NPM and Webpack

The following is a quick setup guide with specific notes for using the Amazon Cognito Auth SDK for JavaScript with Webpack, but there are many more ways it can be used. See the Webpack site, and in particular the configuration documentation

Note that webpack expects your source files to be structured as CommonJS (Node.js-style) modules (or ECMAScript 2015 modules if you are using a transpiler such as Babel.) If your project is not already using modules you may wish to use Webpack's module shimming features to ease migration.

  • Install Node.js on your development machine (this will not be needed on your server.)
  • In your project add a package.json, either use npm init or the minimal, which means your repository is private:
{
"private" : true
}
  • Install the Amazon Cognito Auth SDK for JavaScript and the Webpack tool into your project with npm (the Node Package Manager, which is installed with Node.js):
> npm install --save-dev webpack json-loader
> npm install --save amazon-cognito-auth-js
  • Create the configuration file for webpack, named webpack.config.js:
module.exports = {
  // Example setup for your project:
  // The entry module that requires or imports the rest of your project.
  // Must start with `./`!
  entry: './src/entry',
  // Place output files in `./dist/my-app.js`
  output: {
    path: 'dist',
    filename: 'my-app.js'
  },
  module: {
    loaders: [
      {
        test: /\.json$/,
        loader: 'json'
      }
    ]
  }
};
  • Add the following into your package.json
{
  "scripts": {
    "build": "webpack"
  }
}
  • Build your application bundle with npm run build

Configuration

The Amazon Cognito Auth SDK for JavaScript requires three configuration values from your AWS Account in order to access your Cognito User Pool:

  • An User Pool App Client Id (required): e.g. <TODO: add ClientId>
    • When creating the App, if the generate client secret box was checked, for /oauth2/token endpoint which gets the user's tokens, the client must pass its client_id and client_secret in the authorization header. For more info, please reference here.
  • An App Web Domain (required): e.g. <TODO: add App Web Domain>
    • When you click the Domain name tab, you can create a domain name there and save it for record.
  • Scope Array (required): ['<TODO: your scope array here, try "phone", "email", ...>'], e.g.['phone', 'email', 'profile','openid', 'aws.cognito.signin.user.admin'] (to get more info about scope, please reference "scope" section of our doc)
    • When you click the App settings tab, you can select the identity provider which you want to use on your App.
    • In the sign in and sign out URLs tab, you can set the Callback URLs and Sign out URLs. (both are required)
    • Under the OAuth2.0 tab, you can select the OAuth flows and scopes enabled for this app. (both are required)
  • IdentityProvider (Optional): Pre-selected identity provider (this allows to automatically trigger social provider authentication flow).e.g. Facebook
  • UserPoolId (Optional): e.g. <TODO: add UserPoolId>
  • AdvancedSecurityDataCollectionFlag (Optional): boolean flag indicating if the data collection is enabled to support cognito advanced security features. By default, this flag is set to true.
  • Storage (Optional): Storage provider used to store session data. By default, it uses localStorage if available or an in-memory structure.
  • LaunchUri (Optional): A function called to launch an Uri. By default it uses window.location in browsers, and the Linking class in react native.

The AWS Console for Cognito User Pools can be used to get or create these values.

Note that the various errors returned by the service are valid JSON so one can access the different exception types (err.code) and status codes (err.statusCode).

Usage

The usage examples below use the unqualified names for types in the Amazon Cognito Auth SDK for JavaScript. Remember to import or qualify access to any of these types:

// When using loose Javascript files:
var CognitoAuth = AmazonCognitoIdentity.CognitoAuth;

// Modules, e.g. Webpack:
var AmazonCognitoIdentity = require('amazon-cognito-auth-js');
var CognitoAuth = AmazonCognitoIdentity.CognitoAuth;

// ES Modules, e.g. transpiling with Babel
import {CognitoAuth} from 'amazon-cognito-auth-js';

Use case 1. Registering an auth with the application. You need to create a CognitoAuth object by providing a App client ID, a App web domain, a scope array, a sign-in redirect URL, and a sign-out redirect URL: (Identity Provider, UserPoolId and AdvancedSecurityDataCollectionFlag are optional values)

/*
  TokenScopesArray
  Valid values are found under:
  AWS Console -> User Pools -> <Your user pool> -> App Integration -> App client settings
  Example values: ['profile', 'email', 'openid', 'aws.cognito.signin.user.admin', 'phone']

  RedirectUriSignOut 
  This value must match the value specified under:
  AWS Console -> User Pools -> <Your user pool> -> App Integration -> App client settings -> Sign out URL(s)
*/
var authData = {
	ClientId : '<TODO: add ClientId>', // Your client id here
	AppWebDomain : '<TODO: add App Web Domain>',
	TokenScopesArray : ['<TODO: add scope array>'], // e.g.['phone', 'email', 'profile','openid', 'aws.cognito.signin.user.admin'],
	RedirectUriSignIn : '<TODO: add redirect url when signed in>',
	RedirectUriSignOut : '<TODO: add redirect url when signed out>',
	IdentityProvider : '<TODO: add identity provider you want to specify>', // e.g. 'Facebook',
	UserPoolId : '<TODO: add UserPoolId>', // Your user pool id here
	AdvancedSecurityDataCollectionFlag : '<TODO: boolean value indicating whether you want to enable advanced security data collection>', // e.g. true
        Storage: '<TODO the storage object>' // OPTIONAL e.g. new CookieStorage(), to use the specified storage provided
};
var auth = new AmazonCognitoIdentity.CognitoAuth(authData);

Also you can provide onSuccess callback and onFailure callback:

auth.userhandler = {
	onSuccess: function(result) {
		alert("Sign in success");
		showSignedIn(result);
	},
	onFailure: function(err) {
		alert("Error!");
	}
};

You can also set state parameter:

auth.setState(<state parameter>);

Use case 2. Sign-in using getSession() API:

auth.getSession();

For the cache tokens and scopes, use the parseCognitoWebResponse(Response) API, e.g. the response is the current window url:

var curUrl = window.location.href;
auth.parseCognitoWebResponse(curUrl);

Typically, you can put this part of logic in the onLoad(), e.g.:

function onLoad() {
	var auth = initCognitoSDK();
	var curUrl = window.location.href;
	auth.parseCognitoWebResponse(curUrl);
}

Use case 3. Sign-out using signOut():

auth.signOut();

Important to know

By default, the SDK uses implicit flow(token flow), if you want to enable authorization code grant flow, you need to call useCodeGrantFlow(). For example, please check our sample index.html, in that file, you need to uncomment "auth.useCodeGrantFlow()".
Also, when you meet some problems using our SDK, please make sure you downloaded the lastest version directly from Github repo.

Change Log

v1.3.3

  • Use window.crypto if available (#224)

v1.3.2

  • Add arrow function babel transform for ES build (#187)

v1.3.1

  • Fix transpiling (#185)

v1.3.0

  • Add support for react native (#182)
  • Call onFailure for code flow too (#135)
  • useCodeGrantFlow calls xhr.open twice (throws 'Cannot open, already sending') (#74)

v1.2.4

  • To add newest /es and /lib folders.

v1.2.3

  • To add exporting cookieStorage in index.js.

v1.2.2

  • To update with dist/ build files from update of last version.

v1.2.1

  • To add Cookie storage and Storage as an option.

v1.2.0

  • To merge in fixing tokens being empty strings when refreshing the browser of a single page application.

v1.1.9

  • To sync with NPM version.

v1.1.8

  • Remove parseCognitoWebResponse() onFailure() callback to make sure sample APP works correctly.

v1.1.7

  • Merged in library files.

v1.1.6

  • Added support for avoiding a bug exists when sign in with Google or facebook and parse the web response.

v1.1.5

  • Added parseCognitoWebResponse() onFailure() callback and fixed the CognitoAuth.getCurrentUser() returning undefined when using implicit grant flow.

v1.1.4

  • Removed the dependency on the CognitoIdentityServiceProvider service from the AWS SDK for JavaScript.

v1.1.3

  • Updated doc and uploaded es folder.

v1.1.2

  • Added isUserSignedIn() API method and support for developers to set state parameter. Also uploaded lib folder.

v1.1.1

  • Bug fix, username should be updated when caching tokens and scopes.

v1.1.0

  • Added support for Cognito Advanced Security.

v1.0.1

  • With multiple bug fixes.

v1.0.0

  • GA release. In this GA service launch, we made this feature generally available.

v0.9.0:

  • Public beta release. Developer preview.

amazon-cognito-auth-js's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

amazon-cognito-auth-js's Issues

Sample index.html issues

It seems that the sample and SDK are not in alignment as to case of the following parameters. The sample code uses PascalCase and the SDK is expecting camelCase.

Fails
TokenScopesArray : '<TODO: your scope array here>',
RedirectUriSignIn : '<TODO: your redirect url when signed in here>',
RedirectUriSignOut : '<TODO: your redirect url when signed out here>'

Works
tokenScopesArray : '<TODO: your scope array here>',
redirectUriSignIn : '<TODO: your redirect url when signed in here>',
redirectUriSignOut : '<TODO: your redirect url when signed out here>'

Working sample of Authorization code grant flow?

Can amazaon provide an sample of Authorization code grant flow?

I tried to use google to login Cognito User Pool but token endpoint returns 'invalid_client'
When I returned client id and client secret of google in header and encrypted with base64, the endpoint returned "internal error" error message.

I am stumped here. Thanks

Confused about Cognito documentation

Reading the Getting Started with Cognito hosted UI doc http://docs.aws.amazon.com/cognito/latest/developerguide/getting-started.html. In it it says one can directly access the Conito Auth API by using for example "https://.auth..amazoncognito.com/authorize?" endpoint. In the page there is a link to read more about Amazon Cognito Auth API Reference. But the documentation on AUTHORIZATION Endpoint says to use a different longer URL "The /oauth2/authorize endpoint signs the user in." Are these two the same end point or the Getting Started doc is linking to a different API doc?

Missing lib folder in NPM package

I'm not able to use the npm package when using CommonJS or ES2015 modules (get a "module not found" error). It looks like the /lib folder is missing from the node_modules folder.

I've tested this on NPM Runkit and it seems to experience the same problem: https://npm.runkit.com/amazon-cognito-auth-js

Is this something that was missed when publishing the package?

Attribute required during google authentication

I have a Cognito user pool where email and phone number are required attributes.
When using oauth code grant flow for google authentication, the oauth callback receives error message "attributes required: phone_number"

The gmail account has phone number and I also map google attribute phoneNumbers to Phone Number user pool attribute.

Please advise how to resolve the error. Thanks.

Connie

how to set state parameter in the callback URL?

I have a SPA and would like to pass back the route information so that user can redirect to the route where they intend to access before undergo authentication.

I found from the aws documentation http://docs.aws.amazon.com/cognito/latest/developerguide/authorization-endpoint.html saying i can pass the state value back to the client:

"state
An opaque value the clients adds to the initial request. The authorization server includes this value when redirecting back to the client.

This value must be used by the client to prevent CSRF attacks.

Optional but strongly recommended."

parseCognitoWebResponse with useCodeGrantFlow() only works on Chrome

On Safari and Firefox the makePOSTRequest at the end of getCodeQueryParameter inside parseCognitoWebResponse always fails with "error": "invalid_grant". This causes an infinite loop of parseCognitoWebResponse constantly requesting new code tokens.

Oddly it works fine on Chrome but fails on the other browsers.

Suggestion: Improve documentation

Being used to working with APIs from a competitor I must say that Amazon has a long way to go when it comes to documenting their APIs and services.

After reading AWS Cognito API documentation for the last 4 weeks, scratching my head, I stumbled upon this project which seemed like a step in the right direction. How about making this project a "guiding star" when it comes to how its features are documented?

You could start by documenting how to get this project up and running by specifying every little detail from A-Z, incl. configuration of AWS Cognito, the user pool, federated identity pool etc.

[ts] Cannot find module 'amazon-cognito-auth-js'.

Hi Team,

I am trying to use "amazon-cognito-auth-js" inside my angular2 web application. Executed the following steps to add the dependencies.

  1. npm install --save amazon-cognito-auth-js
  2. import {CognitoAuth} from 'amazon-cognito-auth-js';

I see that the dependencies are updated in package.json. This is how it look inside my package.json file.

"amazon-cognito-auth-js": "^1.0.0",
"amazon-cognito-identity-js": "^1.19.0",
"aws-sdk": "^2.6.0",

Web app is generated using angualr cli. But while building the application i am receiving the following error.
"[ts] Cannot find module 'amazon-cognito-auth-js'."

Can someone help me to resolve this?

Regards,
Sarath

Webpack sample

Pls create a webpack sample app similar to the amazon-cognito-identity-js SDK
(amazon-cognito-identity-js/examples/babel-webpack/). I have few issues using this SDK in a VueJS app so I must have used the library wrongly. A sample will help clarify my mistakes.

how to set state parameter in the callback URL?

I have a SPA and would like to pass back the route information so that user can redirect to the route where they intend to access before undergo authentication.

I found from the aws documentation http://docs.aws.amazon.com/cognito/latest/developerguide/authorization-endpoint.html saying i can pass the state value back to the client:

and i tried this but didn't work

{
  ClientId: '*************************',
  AppWebDomain: '***********.auth.ap-northeast-1.amazoncognito.com',
  TokenScopesArray: ['email openid profile'],
  RedirectUriSignIn: `https://*****/cognitocallback?STATE=dashboard`,
  RedirectUriSignOut: `https://*****`
}

i can find auth.getSession() the only api to sign-in user. Please suggest how to do it for this library? Many thanks

*I am sorry that i asked the same question before but got closed immediately.

Credentials are not cleared on signOut()

Hi Team,

It appears that clearCachedTokensScopes() does not work as intended, because it references this.username and that parameter is undefined. When instantiating CognitoAuth, this.username is set to this.getLastUser() (and this is the only place it is set automatically*). However, by that time the last user is not yet set because cacheTokensScopes() is called only after parseCognitoWebResponse(). As a result, the user session is not cleared at all (except for, ironically, the value of LastAuthUser), and other people logging in on the same device can potentially steal the user tokens. Also, this pollutes localStorage over time as the old tokens are not removed in a multi-user environment.

I suggest we should call this.getCurrentUser() instead of this.username in clearCachedTokensScopes() to ensure that the current user is referenced correctly. Alternatively (even better), we should update this.username after cacheTokensScopes().

*Currently, to work around that without patching CognitoAuth, we must explicitly call auth.setUser(auth.getCurrentUser()) in our onSuccess() callback, which is a bit silly.

Thank you

TokenScopesArray? What goes here?

TokenScopesArray : '<TODO: your scope array here>',

I am assuming valid entries are the same from the App Client Settings

TokenScopesArray : ['phone', 'email', 'profile','openid', 'aws.cognito.signin.user.admin'],

Client secret

Although the documentation is clear "The Amazon Cognito JavaScript SDK does not use the app client secret" I dont understand why dont add the header "Authorization" in the function getCodeQueryParameter(httpRequestResponse) (amazon-cognito-auth.js) when the user configure its sdk with "client secret". This not solve the problem?

SyntaxError: Unexpected token: name (CognitoIdentityServiceProvider) [./enhance.js:18,0]

The library is not in the NPM Registry, as indicated in the documentation, so installing from github, with the command:
npm install --save https://github.com/aws/amazon-cognito-auth-js.git

package.json shows as a dependency:
"amazon-cognito-auth-js": "git+https://github.com/aws/amazon-cognito-auth-js.git"

If you reference the library in application, as the documentation outlines:
import {CognitoAuth} from 'amazon-cognito-auth-js';

Module not found: Error: Cannot resolve module 'amazon-cognito-auth-js'

This appears to be because there is no /lib directory, so, let't do a build...

cd node_modules/amazon-cognito-auth-js/
npm install
npm run build

ERROR in amazon-cognito-auth.min.js from UglifyJs
SyntaxError: Unexpected token: name (CognitoIdentityServiceProvider) [./enhance.js:18,0]

parseCognitoWebResponse() does not parse error responses

Hi Team,

It appears that if redirect from the hosted page produces an error (normally through error and error_description query parameters), parseCognitoWebResponse() would still treat it as a "success", at least when dealing with tokens. Indeed, at the end of getTokenQueryParameter() we see:
https://github.com/aws/amazon-cognito-auth-js/blob/5b365426b2eef2ef27914f7a275e72dea5e302cb/src/CognitoAuth.js#L294-L296
So to treat an error, we must also parse the hash for error and/or error_description in our onSuccess callback, even though it's supposed to get a valid session. It would be more appropriate to call the onFailure callback with that error instead.

Would you accept a PR on the matter?

Thanks

Integrating with vue.js webpack

Hi,

I've installed npm install --save https://github.com/aws/amazon-cognito-auth-js/tarball/master
I am having this webpack.base.conf.js file. But it still complaints that file amazon-cognito-auth-js can't be found :( Maybe some obvious issue with my configuration?

module.exports = {
  entry: {
    app: './src/main.js'
  },
  output: {
    path: config.build.assetsRoot,
    filename: '[name].js',
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      '@': resolve('src')
    }
  },
  module: {
    rules: [
      {
        test: /\.(js|vue)$/,
        loader: 'eslint-loader',
        enforce: 'pre',
        include: [resolve('src'), resolve('test')],
        options: {
          formatter: require('eslint-friendly-formatter')
        }
      },
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test')]
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  }
}

how to add parameters in callback url

#44

@jonasao @yuntuowang

Hi,

I am trying to migrate our current OAuth2 server to AWS Cognito, but encounter the following issue.

When my app request authorisation code, it will add some parameters to the callback url. Let's say the callback url like:

https://open.bot.tmall.com/oauth/callback?skillid=123&token=456

Then the authorization endpoint will be:

https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize?
response_type=code&
client_id=ad398u21ijw3s9w3939&
redirect_uri=https://open.bot.tmall.com/oauth/callback?skillid=123&token=456&
state=STATE&
scope=openid+profile+aws.cognito.signin.user.admin

This will not work as the url is not valid with two question marks. So our app will encode the redirect url. and the authorization endpoint will be:

https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize?
response_type=code&
client_id=ad398u21ijw3s9w3939&
redirect_uri=https%3A%2F%2Fopen.bot.tmall.com%2Foauth%2Fcallback%3Fskillid%3D123%26token%3D456&
state=STATE&
scope=openid+profile+aws.cognito.signin.user.admin

Then comes my question:
how to set the callback url in AWS Management portal?

signout feature

Hi,

I am doing a simple test via the sample web page:
https://github.com/aws/amazon-cognito-auth-js/tree/master/sample

I noticed that I am getting an error on signout. Signout is basically redirecting to a url of the following format:

https://<domain>.auth.us-east-1.amazoncognito.com/logout?logout_uri=<logouturl>&client_id=<client_id>

And then I get an error stating:

Required String parameter 'redirect_uri' is not present

I assume the redirect is used to clear the cookies, but it seems to be failing. I tried playing with this a bit by changing logout_uri to redirect_uri but couldn't get it to redirect back to my logout uri.

Introduce opt-in to remember user devices?

Hi Team,

It looks like currently the 'opt-in' setting to remember user devices is ignored, as there's no dialog to confirm it. Are there plans to add it to the UI?

Edit: 'Always' remembering browser clients doesn't seem to work with SRP-based authentication either.

Thanks

Permit identity provider (name or id) in CognitoAuth.getCognitoConstants()

Are you up for pull requests? I would like to specify an Identity name or id in the getCognitoConstants() method and have the user skip the identity provider selection process (cognito hosted UI) and instead make sure the /authorize endpoint routes directly to a specified identity_provider login as detailed in the authorization endpoin docs.

It would probably be one line of code really in that method as well as the method that builds the FQDN.

aws-cognito-sdk.min.js not compatible with the same from amazon-cognito-identity-js

If I want to use amazon-cognito-identity-js as well as amazon-cognito-auth-js, then this plan fails because the two aws-cognito-sdk.min.js are not compatible with each other.

Uncaught TypeError: Cannot set property '__esModule' of undefined
    at amazon-cognito-identity.min.js:sourcemap:17
    at Array.forEach (<anonymous>)
    at Object.t.exports (amazon-cognito-identity.min.js:sourcemap:17)
    at t (amazon-cognito-identity.min.js:sourcemap:17)
    at t.__esModule (amazon-cognito-identity.min.js:sourcemap:17)
    at amazon-cognito-identity.min.js:sourcemap:17
    at amazon-cognito-identity.min.js:sourcemap:17
    at amazon-cognito-identity.min.js:sourcemap:17
(anonymous) @ amazon-cognito-identity.min.js:sourcemap:17
t.exports @ amazon-cognito-identity.min.js:sourcemap:17
t @ amazon-cognito-identity.min.js:sourcemap:17
t.__esModule @ amazon-cognito-identity.min.js:sourcemap:17
(anonymous) @ amazon-cognito-identity.min.js:sourcemap:17
(anonymous) @ amazon-cognito-identity.min.js:sourcemap:17
(anonymous) @ amazon-cognito-identity.min.js:sourcemap:17

Using amazon-cognito-auth-js features with my own custom UI?

Hi,

I have already started implementing a login/registration using Amazon Cognito Identity SDK for JavaScript.
I have my own custom designed UI, which is self hosted.

My question is: can I connect my UI directly to some functions in the amazon-cognito-auth-js without using the already made hosted UI?

For example, I would like to use amazon-cognito-auth-js to handle some security issues, and to handle user sessions & cookies.

I've already started implementing a security handlers (to prevent, CSRF, SQL INJECTION, XSS...) & cookies handling mechanism myself, but my guess is that the AWS team did a better job than me... therefore I prefer to switch to the amazon-cognito-auth-js implementation, if possible.

Any help or guidance will be highly appreciated,
Thanks!

Neta L.

'amazon-cognito-auth-js' is not in the npm registry.

Hello Team,

Running command npm install --save amazon-cognito-auth-js

returns 404:

npm ERR! node v6.10.2
npm ERR! npm v3.10.10
npm ERR! code E404

npm ERR! 404 Registry returned 404 for GET on https://registry.npmjs.org/amazon-cognito-auth-js
npm ERR! 404
npm ERR! 404 'amazon-cognito-auth-js' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.
npm ERR! Please include the following file with any support request:
npm ERR! /Users/xxxxx/Documents/cognitjs_test_npm/npm-debug.log

LOG (npm-debug.log):

0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node',
1 verbose cli '/usr/local/bin/npm',
1 verbose cli 'install',
1 verbose cli '--save',
1 verbose cli 'amazon-cognito-auth-js' ]
2 info using [email protected]
3 info using [email protected]
4 verbose config Skipping project config: /Users/xxxxx/.npmrc. (matches userconfig)
5 silly loadCurrentTree Starting
6 silly install loadCurrentTree
7 silly install readLocalPackageData
8 silly fetchPackageMetaData amazon-cognito-auth-js
9 silly fetchNamedPackageData amazon-cognito-auth-js
10 silly mapToRegistry name amazon-cognito-auth-js
11 silly mapToRegistry using default registry
12 silly mapToRegistry registry https://registry.npmjs.org/
13 silly mapToRegistry data Result {
13 silly mapToRegistry raw: 'amazon-cognito-auth-js',
13 silly mapToRegistry scope: null,
13 silly mapToRegistry escapedName: 'amazon-cognito-auth-js',
13 silly mapToRegistry name: 'amazon-cognito-auth-js',
13 silly mapToRegistry rawSpec: '',
13 silly mapToRegistry spec: 'latest',
13 silly mapToRegistry type: 'tag' }
14 silly mapToRegistry uri https://registry.npmjs.org/amazon-cognito-auth-js
15 verbose request uri https://registry.npmjs.org/amazon-cognito-auth-js
16 verbose request no auth needed
17 info attempt registry request try #1 at 8:51:11 AM
18 verbose request id f29fef7b0628a2db
19 http request GET https://registry.npmjs.org/amazon-cognito-auth-js
20 http 404 https://registry.npmjs.org/amazon-cognito-auth-js
21 verbose headers { 'content-type': 'application/json',
21 verbose headers 'cache-control': 'max-age=0',
21 verbose headers 'content-length': '2',
21 verbose headers 'accept-ranges': 'bytes',
21 verbose headers date: 'Fri, 09 Jun 2017 06:51:13 GMT',
21 verbose headers via: '1.1 varnish',
21 verbose headers age: '0',
21 verbose headers connection: 'keep-alive',
21 verbose headers 'x-served-by': 'cache-lhr6337-LHR',
21 verbose headers 'x-cache': 'MISS',
21 verbose headers 'x-cache-hits': '0',
21 verbose headers 'x-timer': 'S1496991074.540145,VS0,VE375',
21 verbose headers vary: 'Accept-Encoding' }
22 silly get cb [ 404,
22 silly get { 'content-type': 'application/json',
22 silly get 'cache-control': 'max-age=0',
22 silly get 'content-length': '2',
22 silly get 'accept-ranges': 'bytes',
22 silly get date: 'Fri, 09 Jun 2017 06:51:13 GMT',
22 silly get via: '1.1 varnish',
22 silly get age: '0',
22 silly get connection: 'keep-alive',
22 silly get 'x-served-by': 'cache-lhr6337-LHR',
22 silly get 'x-cache': 'MISS',
22 silly get 'x-cache-hits': '0',
22 silly get 'x-timer': 'S1496991074.540145,VS0,VE375',
22 silly get vary: 'Accept-Encoding' } ]
23 silly fetchPackageMetaData Error: Registry returned 404 for GET on https://registry.npmjs.org/amazon-cognito-auth-js
23 silly fetchPackageMetaData at makeError (/usr/local/lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:302:12)
23 silly fetchPackageMetaData at CachingRegistryClient. (/usr/local/lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:280:14)
23 silly fetchPackageMetaData at Request._callback (/usr/local/lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:210:14)
23 silly fetchPackageMetaData at Request.self.callback (/usr/local/lib/node_modules/npm/node_modules/request/request.js:187:22)
23 silly fetchPackageMetaData at emitTwo (events.js:106:13)
23 silly fetchPackageMetaData at Request.emit (events.js:191:7)
23 silly fetchPackageMetaData at Request. (/usr/local/lib/node_modules/npm/node_modules/request/request.js:1048:10)
23 silly fetchPackageMetaData at emitOne (events.js:96:13)
23 silly fetchPackageMetaData at Request.emit (events.js:188:7)
23 silly fetchPackageMetaData at IncomingMessage. (/usr/local/lib/node_modules/npm/node_modules/request/request.js:969:12)
23 silly fetchPackageMetaData error for amazon-cognito-auth-js { Error: Registry returned 404 for GET on https://registry.npmjs.org/amazon-cognito-auth-js
23 silly fetchPackageMetaData at makeError (/usr/local/lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:302:12)
23 silly fetchPackageMetaData at CachingRegistryClient. (/usr/local/lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:280:14)
23 silly fetchPackageMetaData at Request._callback (/usr/local/lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:210:14)
23 silly fetchPackageMetaData at Request.self.callback (/usr/local/lib/node_modules/npm/node_modules/request/request.js:187:22)
23 silly fetchPackageMetaData at emitTwo (events.js:106:13)
23 silly fetchPackageMetaData at Request.emit (events.js:191:7)
23 silly fetchPackageMetaData at Request. (/usr/local/lib/node_modules/npm/node_modules/request/request.js:1048:10)
23 silly fetchPackageMetaData at emitOne (events.js:96:13)
23 silly fetchPackageMetaData at Request.emit (events.js:188:7)
23 silly fetchPackageMetaData at IncomingMessage. (/usr/local/lib/node_modules/npm/node_modules/request/request.js:969:12)
23 silly fetchPackageMetaData pkgid: 'amazon-cognito-auth-js',
23 silly fetchPackageMetaData statusCode: 404,
23 silly fetchPackageMetaData code: 'E404' }
24 silly rollbackFailedOptional Starting
25 silly rollbackFailedOptional Finishing
26 silly runTopLevelLifecycles Finishing
27 silly install printInstalled
28 verbose stack Error: Registry returned 404 for GET on https://registry.npmjs.org/amazon-cognito-auth-js
28 verbose stack at makeError (/usr/local/lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:302:12)
28 verbose stack at CachingRegistryClient. (/usr/local/lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:280:14)
28 verbose stack at Request._callback (/usr/local/lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:210:14)
28 verbose stack at Request.self.callback (/usr/local/lib/node_modules/npm/node_modules/request/request.js:187:22)
28 verbose stack at emitTwo (events.js:106:13)
28 verbose stack at Request.emit (events.js:191:7)
28 verbose stack at Request. (/usr/local/lib/node_modules/npm/node_modules/request/request.js:1048:10)
28 verbose stack at emitOne (events.js:96:13)
28 verbose stack at Request.emit (events.js:188:7)
28 verbose stack at IncomingMessage. (/usr/local/lib/node_modules/npm/node_modules/request/request.js:969:12)
29 verbose statusCode 404
30 verbose pkgid amazon-cognito-auth-js
31 verbose cwd /Users/xxxxx/Documents/cognitjs_test_npm
32 error Darwin 16.5.0
33 error argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "--save" "amazon-cognito-auth-js"
34 error node v6.10.2
35 error npm v3.10.10
36 error code E404
37 error 404 Registry returned 404 for GET on https://registry.npmjs.org/amazon-cognito-auth-js
38 error 404
39 error 404 'amazon-cognito-auth-js' is not in the npm registry.
40 error 404 You should bug the author to publish it (or use the name yourself!)
41 error 404 Note that you can also install from a
42 error 404 tarball, folder, http url, or git url.
43 verbose exit [ 1, true ]

Feature Request - Adding OAuth Flow-Authorizetioon Code Grant

Hi:
Thanks for everyone's efforts and comments to help me to get this release running as OAuth2 implicit grant.

For application security concern, I would hope the team can release an example with demonstrating Oauth2 authorization code grant with OpenID connect for authentication , plus excluding attributes ( ClientId ,AppWebDomain,TokenScopesArray,RedirectUriSignIn, RedirectUriSignOut ) out of client side javascript as much as possible, for example , hiding them into lambda code for events such as sign in, sign out, registration , registration verification.

If the team knew such example already existed, please advise me in thread. Thanks again.

Ming Qin

Throw Uncaught TypeError when login with Facebook and Google

If user signout and login again, it will throw this exception. It work fine when user login first time, but it will fail if a user already signup.

VM1423 aws-cognito-sdk.js:11656 Uncaught TypeError: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.
at fromObject (VM1423 aws-cognito-sdk.js:11656)
at from (VM1423 aws-cognito-sdk.js:11505)
at new Buffer (VM1423 aws-cognito-sdk.js:11482)
at Object.decode64 [as decode] (VM1423 aws-cognito-sdk.js:7825)
at t.getUsername (VM1424 amazon-cognito-auth.min.js:33)
at t.cacheTokensScopes (VM1424 amazon-cognito-auth.min.js:81)
at t.getTokenQueryParameter (VM1424 amazon-cognito-auth.min.js:81)
at t.parseCognitoWebResponse (VM1424 amazon-cognito-auth.min.js:81)

Support FORCE_CHANGE_PASSWORD state

The sign in fails if an user is created by admin and the user status is FORCE_CHANGE_PASSWORD.

Would like to allow admin to created users as well.

CognitoAuth username is empty in code grant flow

When using token flow, CognitoAuth property username returns a string of uuid. When using code grant flow, username is empty or undefined. Is this expected?

Which CognitoAuth properties or methods should I use to check if a user has signed in?

AWS Cognito hosted UI - Facebook API v2.11 breaks login

Currently developing an authentication solution using AWS Cognito with userpool and hosted UI for login, where the user may choose between Facebook, Google and username/password login options.

Until today we have been using a Facebook app based on Facebook API v2.10, which have been working perfectly.

I have created a new Facebook app for my company, based on Facebook API v2.11 with the intention of replacing the existing Facebook app used when authenticating users via AWS Cognito.

These two apps have the exact same configuration, unfortunately the latter will not work!

When using the Facebook app that uses API v2.11, the situation is as follows:
The user chooses to use Facebook as identity provider in the AWS Cognito hosted UI. Clicking the Facebook button returns an error message, stating that the user is not logged on instead of attempting to log on the user or give the user a chance to accept this Facebook app.

If the user is already logged on and chooses to use Facebook as identity provider, the user is presented with an error message stating that the client's redirect URL is wrong, and authentication fails. (This can't be the case since this Facebook app has the exact same configuration as the one using Facebook API v2.10.)

Facebook app ID and secret are both updated in AWS Cognito identity provider settings to match the ones for the Facebook app using Facebook API v2.11 - unfortunately this is not helping.

Anyone sharing the same experience?

Please release fixes recently merged

I see that a PR was merged fixing code grant flow recently, but there are no new versions actually released via npm. Please make a 1.0.1 with current fixes!

Also, there was an issue importing your module. Same happens in a new react app using create-react-app. Please review package.json and ensure that your index.js is referenced properly.

How to store idToken and how to retrieve it?

Hi!

Is there a method with amazon-cognito-auth-js, similar to the one using amazon-cognito-identity-js, to store the data of the current logged in user and retrieve the idToken of this user?

Using amazon-cognito-identity-js, it is possible to make it this way:

Storing user data:

const userPool = new CognitoUserPool({
      UserPoolId: config.cognito.USER_POOL_ID,
      ClientId: config.cognito.APP_CLIENT_ID
    });
    const user = new CognitoUser({ Username: email, Pool: userPool });
    const authenticationData = { Username: email, Password: password };
    const authenticationDetails = new AuthenticationDetails(authenticationData);

    return new Promise((resolve, reject) =>
      user.authenticateUser(authenticationDetails, {
        onSuccess: result => resolve(),
        onFailure: err => reject(err)
      })
    );

Retrieving the idToken of the current user logged in:

const userPool = new CognitoUserPool({
    UserPoolId: config.cognito.USER_POOL_ID,
    ClientId: config.cognito.APP_CLIENT_ID
  });
  var currentUser = userPool.getCurrentUser();
  currentUser.getSession(function(err, session) {
    var idToken = session.getIdToken().getJwtToken();
  });

Thank you very much!
Guillaume

React Native implementation

Do you have any sample on how to use/implement authenticating with facebook using this library in react native?

Authorization code grant flow not working

If I turn off "Implicit grant" in my Cognito App client and leave only "Authorization code grant" then login fails and I get login#error_description=unauthorized_client&state=...&error=invalid_request.

If I turn on "Implicit grant" then the login works but I don't get a refresh token so I have to login every hour.

Code Auth - getCodeQueryParameter(httpRequestResponse)

I have an issue with Code Auth method. While parsing response it can't establish a session, it constantly requests a new code.

I receive a code in format: domain/page?code=<code_value>

From the Code it splits the url using the following regex: /#(.+)/ which cannot extract code value because it is not after poundsign, it's after questionmark.

No System.js or Angular.io support out of the box

It'd be nice to have some docs about how to use this in angular with System.Js. It is not clear to me if only with this project are we able to get a yes/no authentication, or we need to install additional packages, like the aws-sdk package.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.