GithubHelp home page GithubHelp logo

kndt84 / passport-cognito Goto Github PK

View Code? Open in Web Editor NEW
77.0 4.0 30.0 394 KB

Passport strategy for AWS Cognito User Pools

Home Page: https://www.npmjs.com/package/passport-cognito

License: MIT License

JavaScript 100.00%

passport-cognito's Introduction

Build Status dependencies Status npm

passport-cognito

Passport strategy for Cognito User Pools not for Cognito Identity.

This module lets you authenticate using Cognito User Pools in your Node.js applications. By plugging into Passport, Cognito User Pools authentication can be easily and unobtrusively integrated into any application or framework that supports Connect-style middleware, including Express.

Install

$ npm install passport-cognito

Usage

Configure Strategy

var CognitoStrategy = require('passport-cognito')

passport.use(new CognitoStrategy({
    userPoolId: 'ap-northeast-1_eSjqLfqKc',
    clientId: 'vtvg02tr21zmxvspyvawtv09b',
    region: 'ap-northeast-1'
  },
  function(accessToken, idToken, refreshToken, user, cb) {
    process.nextTick(function() {
      ...
      cb(null, user);
    });
  }
));

Authenticate Requests

To authenticate a user, send username and password to server-side by POST request like the following.

// Browser
$.ajax({
  type: "POST",
  url: '/auth/cognito',
  data: { username: username, password: password }
})

Then the strategy receive username and password as a req object. In detail, req.body.username and req.body.password should not be undefined. Then, call authenticate method as express middleware.

// Server
app.post('/auth/cognito',
  passport.authenticate('cognito', {
    successRedirect: '/',
    failureRedirect: '/login'
}));

FAQ

How to get session expiration ?

You can get session object by adding a variable to argument vector. Then, by executing getExpiration method, session expiration is retrieved.

var CognitoStrategy = require('passport-cognito')

passport.use(new CognitoStrategy({
    userPoolId: 'ap-northeast-1_eSjqLfqKc',
    clientId: 'vtvg02tr21zmxvspyvawtv09b',
    region: 'ap-northeast-1'
  },
  function(accessToken, idToken, refreshToken, user, session, cb) {
    process.nextTick(function() {
      user.expiration = session.getIdToken().getExpiration();
      ...
      cb(null, user);
    });
  }
));

passport-cognito's People

Contributors

andyatryonsoft avatar bancalets avatar chgrp-hung avatar dependabot[bot] avatar gmadar avatar kndt84 avatar nitsanavni avatar piercus 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

Watchers

 avatar  avatar  avatar  avatar

passport-cognito's Issues

Login screen

I have configured it in one of loopback server supporting passport authentication. However, when i hit auth/cognito i get 404. It works for another cognito library and google.
Am i missing something?

Improper Authorization

NPM Audit failure

All versions of passport-cognito are vulnerable to Improper Authorization. The package fails to properly scope the variables containing authorization information, such as access token, refresh token and ID token. This causes a race condition where simultaneous authenticated users may receive authorization tokens for a different user. This would allow a user to take actions on another user's behalf.

newPassword2

Hi,

On Line 142 there is a:
console.log('newPassword2'...)

Would it be possible to comment this line out please?

Also is there a way to pass the password value into the function rather than explicit req.body.password?

The flow is

  1. user enters username/password
  2. server detects (err.412) and redirects to "Change Password" - the temporary password is saved on session
  3. user enters newpassword
  4. server gets the password from session and authenticates with password & newpassword

Currently I have to set the initial password onto the form inside hidden field (in plain text). I guess its not a big deal since its not leaking the real password.

Cheers,
Paul

Express JS Sample

Hi,

Thanks for coding this up!
I noticed earlier you said you would add an Express example; this is my first time using Passport/Express and I'd love to see an example of Express+Passport Cognito.

Thanks

Is it possible to integrate the passport-cognito into Nest.js?

Hi, Is it possible to integrate the passport-cognito into Nest.js by using PassportStrategy and AuthGuard? I found the JwtStrategy worked only for Auth0 and would like to customize a CognitoStrategy extends PassportStrategy(Strategy), something like following in TypeScript:

import { Strategy } from 'passport-cognito';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, Logger } from '@nestjs/common';

@Injectable()
export class CognitoStrategy extends PassportStrategy(Strategy) {
  private readonly logger = new Logger(CognitoStrategy.name);

  constructor() {
    super( // please help here...);
  }

  async validate(payload: any) {
    this.logger.log('payload: ', payload);
    return payload;
  }
}

Thanks a lot

RefreshToken?

function(accessToken, idToken, refreshToken, user, session, cb) {
process.nextTick(function() {
user.expiration = session.getIdToken().getExpiration();
...
cb(null, user);
})

--> How can I use the RefreshToken if the user.expiration is true...

Cannot read property 'username' of undefined

The example on the README is throwing an error:

 $.ajax({
            type: "post",
            url: 'http://localhost:3000/auth/cognito',
            data: { username: "myname", password: "mypass" }
        })


TypeError: Cannot read property 'username' of undefined
    at CognitoStrategy.authenticate (/mypath/node_modules/passport-cognito/lib/strategy.js:76:26)
    at attempt (/mypath/node_modules/passport/lib/middleware/authenticate.js:361:16)
    at authenticate `

req.body is null in authenticate()

CognitoStrategy.prototype.authenticate = function(req, options) {

  var user = {};
  var username = req.body.username;
  var password = req.body.password;

Authenticate behind corporate proxy

Hi,

I have a nodejs/express app thats working great from home or deployed on EB. Great library thanks!

However at work behind our corporate proxy authentication requests seem to be timing out. AWS seem to provide a simple solution here: http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/node-configuring-proxies.html
and https://aws.amazon.com/blogs/developer/using-the-aws-sdk-for-javascript-from-behind-a-proxy/

As I'm kind of new to NodeJS I'm wondering how to pass this config when creating the CognitoStrategy object. Is it possible as I would like the option to run from my localhost?

Thanks,
Paul

ReferenceError: navigator is not defined

I am getting this error from inside the cognito module:

at CognitoUser.authenticateUserInternal (/var/app/current/node_modules/amazon-cognito-identity-js/lib/CognitoUser.js:383:19)

It looks like Amazon wrote these modules assuming they will run in a browser.

I worked around this by adding global.navigator = {} just before calling passport.use(new CognitoStrategy(...)). Not thrilled about adding a global, but it works.

Figured I'd post this here in case anyone else stumbles upon this.

Setting user field on request

Hi there,
I was wondering if this library automatically sets the user field on the express request object for an authenticated request? Thanks.

Not authenticating

When I make a post request, nothing happens. It goes to failure redirect url. but nothing happens.
Included log here and there to find failure point but it just doesnt move at all

Upgrade momentjs

The momentjs version being used has an know ReDoS issue.

Please, consider to upgrade to 2.20.1

FORCE_CHANGE_PASSWORD

When I added a new test user on Cognito, it's status is "FORCE_CHANGE_PASSWORD".
I think, because of that, when I try to login, it's always failing.

I have the standard standard code but put in my two pages:

app.post('/auth/cognito',
  passport.authenticate('cognito', {
    successRedirect: 'http://localhost:8081/home.html',
    failureRedirect: 'http://localhost:8081/login.html'
}));

Based on what I read here: https://docs.aws.amazon.com/cognito/latest/developerguide/using-amazon-cognito-identity-user-pools-javascript-example-authenticating-admin-created-user.html
thought maybe something like the code below might work, but it hasn't yet:

app.post('/auth/cognito',
  passport.authenticate('cognito', {
    successRedirect: 'http://localhost:8081/home.html',
    failureRedirect: 'http://localhost:8081/login.html',
    newPasswordRequired: 'http://localhost:8081/newpass.html'
}));

I'm logging the URLS and post/parms as follows,
so it looks the redirect is working to the login.html page only:

08/16/2019 14:39:35: POST: Request URL:/auth/cognito
{ username: 'Test1', password: 'b#*5arNdESHrqtBk' }
08/16/2019 14:39:35: GET: Request URL:/login.html

Is there some other error we can send back to the client on the AJAX call that tell us what the issue is, for example, that he needs to change his password? Is there any type of console.log I can do in the code above to help debug further?

Any idea where to find code to change the password in NodeJS? That would be outside of Passport correct?

Thanks,
Neal

support passReqToCallback option

Is it possible to implement the passReqToCallback passport behaviour ?

passport.use(new CognitoStrategy({ userPoolId: 'ap-northeast-1_eSjqLfqKc', clientId: 'vtvg02tr21zmxvspyvawtv09b', region: 'ap-northeast-1', passReqToCallback: true }

The verify function signature would change.

Minimal expressjs sample?

I'm trying to put together a minimal sample but I'm not sure how the passport-cognito is supposed to go. Apologies in advance, I'm used to Auth0 which have spoiled me with fully-working starter code. Do you know of any sample code that uses passport-cognito?

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.