Giter VIP home page Giter VIP logo

react-cognito's Introduction

React Cognito

You can now use Amazon Cognito to handle authentication and authorization for your mobile and web applications. This is particularly useful for serverless single-page applications (SPAs). SPAs can be hosted in S3 buckets and use AWS services such as API Gateway, Lambda, S3, DynamoDB and others without requiring a separate server.

This Javascript package provides a set of React components and supporting code to make integrating with Cognito very easy, if you are using React and Redux.

Full documentation for this package is available.

This package is available on npm.

AWS Amplify

NOTE: AWS have now released AWS Amplify, which might be more suitable for your needs than react-cognito.

Introduction

This library should be installed using npm, and depends on React, Redux, React Router, and of course the underlying AWS packages.

In a nutshell this library allows you to write all of your own forms and UI components, but abstracts out all of the interfacing with Cognito, and determining which parts of UI should be rendered.

Redux State

This package depends entirely on Redux to manage client-side state. As well as storing important state variables there is also a client-side state machine that helps you display the correct UI depending on the state of the user with respect to their authentication status.

All state is stored in redux under the key cognito. in there you can find:

user

This is either null or a valid CognitoUser object. You are unlikely to need to use this yourself, and it is located by components using the context.

state

This is a string indicating the client-side state. See State Machine below.

error

If errors are encountered from the Cognito API they are stored here, and then exposed as appropriate to UI components. This means most error handling is transparent and automatic for you.

userPool

The CognitoUserPool object, used to create users.

attributes

This contains all the user's Cognito attributes, if you've chosen to fetch them at login (the default).

creds

A CognitoIdentityCredentials object, used to authenticate against a Federated User Pool. Contains no secret material.

config

The configuration provided by the application, used to contact Cognito.

react-cognito's People

Contributors

dibell avatar kbrown avatar kbrown-axio avatar nokrosis avatar rynocouse avatar tcchau avatar winjer avatar

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

react-cognito's Issues

How can i attach Group using react-cognito

Hi ,

I was unable to attach a role to user.

I used the below code

let store = createStore(reducers, window.REDUX_DEVTOOLS_EXTENSION && window.REDUX_DEVTOOLS_EXTENSION());

config.group = 'Admin'; // Uncomment this to require users to be in a group 'admins'
setupCognito(store, config);

Please help

user-not-attached-group

Accessing PropTypes via the main React package is deprecated

Hi

I get this warning:
lowPriorityWarning.js:40 Warning: Accessing PropTypes via the main React package is deprecated, and will be removed in React v16.0. Use the latest available v15.* prop-types package from npm instead. For info on usage, compatibility, migration and more, see https://fb.me/prop-types-docs

I assume its just changing from:

import React, { PropTypes } from 'react';

to:

import React from 'react'; import PropTypes from 'prop-types';

Insufficient privilege error when logging in

I am using you example code, when I try to login a user that is already verified I get the following error "Insufficient privilege".
I can create new users and change password but not log in.

Stale Token

I'm having trouble with stale auth tokens. I'm sending the signInUserSession.idToken.jwtToken as an Authorization header in all of my fetch requests, but it appears that the token expires fairly quickly and is only refreshed on page reload. This is an issue when the webapp is left open and idle and then a fetch request is made without reloading the page.

Is there something I've missed in the setup, or some function I've overlooked that will refresh the token? I didn't see anything about this in the docs. If anyone could offer up any solutions or insight it would be greatly appreciated.

Edit: Figured it out by checking out the amazon-cognito-identity-js docs.

Build Error in application

ERROR in assets/app.js from UglifyJs
Unexpected token: operator (>) [../node_modules/react-cognito/src/actions.js:6,0][assets/app.js:55718,21]

Error when middleware included with redux-immutable-state-invariant

I'm new to front end development, so hopefully I'm not wasting anyones time with this.

When I add the following to my createStore and add middleware like below

import {createStore, applyMiddleware} from 'redux';
import rootReducer from '../reducers';
import reduxImmutableStateInvariant from 'redux-immutable-state-invariant';
import thunk from 'redux-thunk';

export default function configureStore(initialState) {

  return createStore(
    rootReducer,
    initialState,
    applyMiddleware(thunk, reduxImmutableStateInvariant())
  );
}

It causes the following error

Invariant Violation: A state mutation was detected between dispatches, in the path cognito.user.pool.client.api.operations.addCustomAttributes.input.defaultValue. This may cause incorrect behavior. (http://redux.js.org/docs/Troubleshooting.html#never-mutate-reducer-arguments)

Is this something I can ignore? the error disappears when I change applyMiddleware to

applyMiddleware(thunk)

Errors in console when password is invalid

Why there is uncaught error in console when using wrong password?

bundle.js:16431 Uncaught (in promise) Error: Incorrect username or password. at Request.extractError (bundle.js:16431) at Request.callListeners (bundle.js:19408) at Request.emit (bundle.js:19380) at Request.emit (bundle.js:18017) at Request.transition (bundle.js:17356) at AcceptorStateMachine.runTo (bundle.js:22839) at bundle.js:22851 at Request.<anonymous> (bundle.js:17372) at Request.<anonymous> (bundle.js:18019) at Request.callListeners (bundle.js:19418) at Request.emit (bundle.js:19380) at Request.emit (bundle.js:18017) at Request.transition (bundle.js:17356) at AcceptorStateMachine.runTo (bundle.js:22839) at bundle.js:22851 at Request.<anonymous> (bundle.js:17372) at Request.<anonymous> (bundle.js:18019) at Request.callListeners (bundle.js:19418) at callNextListener (bundle.js:19398) at EventEmitter.onEnd (bundle.js:14556) at EventEmitter../node_modules/events/events.js.EventEmitter.emit (bundle.js:36627) at features.constructor.finishRequest (bundle.js:15196) at XMLHttpRequest.<anonymous> (bundle.js:15111)

Thanks

setupCognito causes state mutation error when passing applyMiddleware to createStore

Issue
setupCognito doesn't seem to play nicely with Redux's applyMiddleware, resulting in a Redux state mutation error.

Steps to reproduce:

  1. Import applyMiddleware from redux.
  2. Call createStore, passing a call to applyMiddleware (which can be passed any middleware).
  3. Call setupCognito.

Symptom
This results in the following error:

Uncaught Error: A state mutation was detected between dispatches, in the path cognito.userPool.client.api.operations.addCustomAttributes.input.defaultValue. This may cause incorrect behavior. (http://redux.js.org/docs/Troubleshooting.html#never-mutate-reducer-arguments)
at invariant (browser.js:40)
at index.js:53
at Object.dispatch (index.js:14)
at setupCognito (react-cognito.js:1191)
at index.js:16

The error seems triggered by the call to setupCognito.

Federated Identities

Does this module incorporate the federated identities capabilities of Cognito or just User Pools?

auth via Google, Facebook

Hello, I use react-cognito to work with auth state, and it is very useful, easy to use. Excellent! But I didn't find anything about auth via google/facebook. Do you plan to implement it?

What can you suggest for now to work with this? I could implement it with javascript sdk, provided by aws cognito documentation, but it is complicated because I am already have cognito reducer from react-cognito lib, and creating new one for managing state of autho via google/facebook. I don't like such splitting :(

Cannot set up react-cognito with non-default policy

Suppose I don't require email verification.

/**

  • sets up react-cognito with default policies.
    */
    const setupCognito = (store, config) => {
    store.dispatch(Action.configure(config));
    enable(store, emailVerificationRequired);
    enable(store, identityPoolLogin);
    };

How am I supposed to set non-default policy?

BUG - performLogin called multiple times

If you dispatch multiple actions when cognito.state is LOGGING_IN, performLogin is going to be called a number of times equal to the number of actions dispatched.

This happens because the enable function is subscribed to the store and it runs every time an action is dispatched. The, identityPoolLogin is going to be called multiple times and the validation state.cognito.state === CognitoState.LOGGING_IN can be true for a few milliseconds, thus performing login multiple times

React 16.0.0

Hi all, sorta new to this whole game here. My project has react and react-dom at 16.0.0 but this package seems to specify 15.0.0

https://github.com/isotoma/react-cognito/blob/master/package.json

When I try to install this on my project, I get:

$ npm install react-cognito -s
[email protected] /Users/me/Development/app/react/app-web
├── UNMET PEER DEPENDENCY [email protected]
├── [email protected]
└── UNMET PEER DEPENDENCY [email protected]

Is 16.0.0 supported? and what's the proper way to resolve this?

Thanks!

Error Unable to verify secret hash for client

Hi I tried to register user and i will get this error can you describe me what i should to do:
POST https://cognito-idp.eu-west-2.amazonaws.com/ 400 (Bad Request)
ERROR Unable to verify secret hash for client 2###############t

SOLUTION
unchecked Generate client secret
image

Expired session and refreshing / CognitoState

After 1 hour (configurable in user pool) tokens expire yet CognitoState.LOGGED_IN remains true.

This necessitates complicated logic in the app, i.e checking cognito.user.signInUserSession.idToken.payload.exp at each PrivateRoute change and calls to private APIs, and subsequently attempting a refresh if the checks fail.

Would it be possible for react-cognito to auto-refresh tokens and update CognitoState if the refresh fails?

Examples don't build

$ git clone [email protected]:isotoma/react-cognito
...
$ npm run examples

> [email protected] examples ./react-cognito
> babel --plugins transform-es2015-modules-umd src --ignore __tests__ examples/src --out-file examples/htdocs/dist/bundle.js

Error: ENOENT: no such file or directory, open 'examples/htdocs/dist/bundle.js'
    at Object.fs.openSync (fs.js:557:18)
    at Object.fs.writeFileSync (fs.js:1214:33)
    at output ./react-cognito/node_modules/babel-cli/lib/babel/file.js:92:10)
    at walk (./react-cognito/node_modules/babel-cli/lib/babel/file.js:154:5)
    at files (./react-cognito/node_modules/babel-cli/lib/babel/file.js:160:7)
    at module.exports ./react-cognito/node_modules/babel-cli/lib/babel/file.js:188:5)
    at Object.<anonymous> (./react-cognito/node_modules/babel-cli/lib/babel/index.js:130:1)
    at Module._compile (module.js:573:32)
    at Object.Module._extensions..js (module.js:582:10)
    at Module.load (module.js:490:32)

node 7.1.0, babel-cli 6.22.2 (babel-core 6.22.1)

Inconsistent login state vs guard(ed) routes

Guarded routes are validated by checking:

state.cognito.user !== null

However Dashboard on example app depends on:

state.cognito.state = CognitoState.LOGGED_IN

If a user logs in, the session data and user is saved in local storage.
If the browser is closed and reopened, on entering the app, COGNITO_CONFIGURE action is fired which has the following code:

const configure = (state, action) => {
  // surprise side-effect!
  AWSCognito.config.region = action.config.region;
  const pool = new CognitoUserPool({
    UserPoolId: action.config.userPool,
    ClientId: action.config.clientId,
  });
  const user = pool.getCurrentUser();
  return Object.assign({}, state, {
    config: action.config,
    userPool: pool,
    user,
  });
};

When calling const user = pool.getCurrentUser(); cognito recovers the user from local storage, turning state.cognito.user !== null however, state.cognito.state is not updated to CognitoState.LOGGED_IN which turns the app on an undesired state:

  1. On one side, the user is presented the Login Form as if it was not logged-in, because state.cognito.state !== CognitoState.LOGGED_IN

  2. By the other side, the user CAN access guarded routes since state.cognito.user !== null

I think CognitoState should be updated accordingly if const user = pool.getCurrentUser(); has a valid user/session, or else what solution do you suggest to handle these states?

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.