Code Monkey home page Code Monkey logo

passport's Introduction

passport banner

Passport

Passport is Express-compatible authentication middleware for Node.js.

Passport's sole purpose is to authenticate requests, which it does through an extensible set of plugins known as strategies. Passport does not mount routes or assume any particular database schema, which maximizes flexibility and allows application-level decisions to be made by the developer. The API is simple: you provide Passport a request to authenticate, and Passport provides hooks for controlling what occurs when authentication succeeds or fails.


Sponsors

Your app, enterprise-ready.
Start selling to enterprise customers with just a few lines of code. Add Single Sign-On (and more) in minutes instead of months.



Drag and drop your auth
Add authentication and user management to your consumer and business apps with a few lines of code.



Auth. Built for Devs, by Devs
Add login, registration, SSO, MFA, and a bazillion other features to your app in minutes. Integrates with any codebase and installs on any server, anywhere in the world.



API-first AuthN, AuthZ, and Fraud Prevention
The most powerful identity platform built for developers. Easily build and secure a modern auth flow with user & org management, multi-tenant SSO, MFA, RBAC, device fingerprinting, and more.


Status: Build Coverage Dependencies

Install

$ npm install passport

Usage

Strategies

Passport uses the concept of strategies to authenticate requests. Strategies can range from verifying username and password credentials, delegated authentication using OAuth (for example, via Facebook or Twitter), or federated authentication using OpenID.

Before authenticating requests, the strategy (or strategies) used by an application must be configured.

passport.use(new LocalStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function (err, user) {
      if (err) { return done(err); }
      if (!user) { return done(null, false); }
      if (!user.verifyPassword(password)) { return done(null, false); }
      return done(null, user);
    });
  }
));

There are 480+ strategies. Find the ones you want at: passportjs.org

Sessions

Passport will maintain persistent login sessions. In order for persistent sessions to work, the authenticated user must be serialized to the session, and deserialized when subsequent requests are made.

Passport does not impose any restrictions on how your user records are stored. Instead, you provide functions to Passport which implements the necessary serialization and deserialization logic. In a typical application, this will be as simple as serializing the user ID, and finding the user by ID when deserializing.

passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function (err, user) {
    done(err, user);
  });
});

Middleware

To use Passport in an Express or Connect-based application, configure it with the required passport.initialize() middleware. If your application uses persistent login sessions (recommended, but not required), passport.session() middleware must also be used.

var app = express();
app.use(require('serve-static')(__dirname + '/../../public'));
app.use(require('cookie-parser')());
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());

Authenticate Requests

Passport provides an authenticate() function, which is used as route middleware to authenticate requests.

app.post('/login', 
  passport.authenticate('local', { failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });

Strategies

Passport has a comprehensive set of over 480 authentication strategies covering social networking, enterprise integration, API services, and more.

Search all strategies

There is a Strategy Search at passportjs.org

The following table lists commonly used strategies:

Strategy Protocol Developer
Local HTML form Jared Hanson
OpenID OpenID Jared Hanson
BrowserID BrowserID Jared Hanson
Facebook OAuth 2.0 Jared Hanson
Google OpenID Jared Hanson
Google OAuth / OAuth 2.0 Jared Hanson
Twitter OAuth Jared Hanson
Azure Active Directory OAuth 2.0 / OpenID / SAML Azure

Examples

Related Modules

The modules page on the wiki lists other useful modules that build upon or integrate with Passport.

License

The MIT License

Copyright (c) 2011-2021 Jared Hanson <https://www.jaredhanson.me/>

passport's People

Contributors

alexanderweiss avatar amzotti avatar andrewagain avatar ashelley avatar brandwe avatar camshaft avatar daawesomep avatar danielsharvey avatar forbeslindesay avatar freewil avatar gologo13 avatar ircmaxell avatar jaredhanson avatar kulakowka avatar macrauder avatar matejkramny avatar matheushf avatar mjhea0 avatar murashki avatar pareek-naren avatar paroga avatar pgilad avatar rkusa avatar ryysud avatar thegoleffect avatar tschaub avatar woloski avatar wunderkind2k1 avatar ximex avatar ychebotaev 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  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

passport's Issues

Login failed handling

In passport we use authenticate connect/express middleware to handle login.

The problem is, when login failed, the only way now is to redirect back to login url directly without any message to the user.
I think it's better to have certain message for user to be aware or even further to notice the user his/her login account could be locked due to some reason.

It's possible to put a query parameter in the redirected url. But I think that would be a little bit ugly.

problem with middleware to check if i can go to some route

app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session({ secret: 'keyboard cat' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});

function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/')
}

app.get('/', routes.index);
app.get('/success', ensureAuthenticated, routes.success);
app.post('/login',
passport.authenticate('local', { successRedirect: '/success',
failureRedirect: '/',
failureFlash: 'Invalid credentials',
successFlash: 'Welcome'})
}
);

I think im doing this right but in ensureAuthenticated it tells me that isAuthenticated() == False, am i doing something wrong?

Serialization step fails

After authentication, I'm able to successfully create a new user, but when that user connects again, I get

Error: failed to serialize user into session - I'm just using the in memory store, and my serialize function is straight from the examples

passport.serializeUser(function(user, done) {
done(null, user._id); //using mongodb for user storage
});

failureFlash not working in Express 3

This might be a problem on my end. Passport seems to be working great in all aspects, except that the flash isn't populated by failureFlash on a redirect. Console.logs injected show that it's setting it, but by the time the redirect is complete, req.flash('error') returns an empty set. All other aspects of passport seem to be working fine otherwise. Any suggestions?

Facebook offline_access getting deprecated

Hello there,
as it stands from http://developers.facebook.com/roadmap/offline-access-removal/, the offline_access is deprecated since the 2nd of May. Here is my code:

passport.use(new FacebookStrategy({ clientID: FACEBOOK_APP_ID, clientSecret: FACEBOOK_APP_SECRET, callbackURL: "http://localhost:5000/auth/facebook/callback"}, function(accessToken, refreshToken, profile, done) {
console.log(refreshToken)
return done(null, profile);
});
}));

app.get('/auth/facebook',
passport.authenticate('facebook', { scope: 'offline_access' })
);

However the refreshToken give me 'undefined' even if I can authenticate. Is it a bug for the deprecation problem?

thanks,

n

Express3

so far : problems with flash and requiring a cookieParse secret

req.isAuthenticated() doesn't survive redirect

The isssue is similar to the one reported here #26
The problem is - I actually use sessions (with express 3).
The question is also posted here http://stackoverflow.com/questions/11473507/express-3-0-and-passport-authentication

My express3/passport0.1.12 config

app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('host', process.env.HOST || 'localhost');
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser(SITE_SECRET)); // SITE_SECRET is the const defined above in the code

app.use(express.session({
key: 'express.sid'
, store: SessionStore // SessionStore is defined as MemoryStore for dev enviroment
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});

app.get('/', routes.index);

app.post('/login', passport.authenticate('local', { failureRedirect: '/' }),
function(req, res) {
console.log(req.isAuthenticated()); // true
res.redirect('/users/' + req.user.id );
});

app.get('/users/:id', ensureAuthenticated, routes.user);

function ensureAuthenticated(req, res, next) {
console.log(req.isAuthenticated()); // false
if (req.isAuthenticated()) { return next(); }
res.redirect('/');
}

How to get two passport objects

Since passport returns an object (which is shared by any call to require('passport'), how would I go about getting two separate passport objects that can have separate configurations and initializations?

In other words something like:
Passport = require('passport);
pp1 = new Passport()
pp2 = new Passport()

Problem with cluster

I add cluster support to express3 example (from local strategy) and it stop working with passport

var numCPUs = require('os').cpus().length;
if(cluster.isMaster) {
for(var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', function(worker, code, signal) {
console.log('Worker ' + worker.id + ' died: ' + worker.process.pid);
});
} else {
console.log('Worker ' + cluster.worker.id + ' started: ' + cluster.worker.process.pid);
app.listen(3000);
}

(Press F5 several times if you logged in)

it also do not work with other strategies (I tested facebook and twitter). If I remove clusterization - everything works fine.

I've got node 0.8.6, npm 1.1.48 and express 3.0.0rc2

favicon

add favicon 16, 32 and 64 pixels.

Support out of band authentication

Some applications such as a SSO solution for tooling would greatly benefit from passport, but as it stands creating out of band strategies are a bit cumbersome:

https://gist.github.com/2877622

Would it be possible to have an option that would disable sending the response immediately on error and instead pass it to the next middleware with the info forwarding to the next function as it's error.

populating user field (mongoose) doesn't persist as session on req.user

I'm using Mongoose.js and populate a User field (companyRoles._company) on authentication:

UserSchema.static('authenticate', function(email, password, callback) {
this.findOne({ email: email })
.populate('companyRoles._company', ['name', '_id'])
.run(function(err, user) {
if (err) { return callback(err); }
if (!user) { return callback(null, false); }
user.verifyPassword(password, function(err, passwordCorrect) {
if (err) { return callback(err); }
if (!passwordCorrect) { return callback(null, false); }
return callback(null, user);
});
});
});

I verify that the field is populated to an object in the req.logIn callback:

//login post
app.post('/passportlogin', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err) }
if (!user) { return res.redirect('/passportlogin') }
req.logIn(user, function(err) {
if (err) { return next(err); }
console.log('req User');
console.log(req.user);
return res.redirect('/companies/' + user.companyRoles[0]._company._id);
});
})(req, res, next);
});

But when I redirect to /companies/{companyId} I find that companyRoles._company is an ID and no longer is populated.

app.get('/companies/:cid', function(req, res){
console.log('req.user in companies:cid');
console.log(req.user);
});

Thanks

authentication and autherization event logging

Is there anyway to hook into passportjs to listen for authentication and autherization events?

passport.on('error', function(data){
console.log("%s", data);
});

I would like to remove logging from the following code and place it more centrally.

function facebookConnect(accessToken, refreshToken, profile, done) {

    var logEntry = {
        accessToken:accessToken,
        refreshToken:refreshToken,
        profile:profile,
        email:profile.emails
    };

    logger.debug(logEntry);

    app.Account
        .findOne({ domain:profile.domain, id:profile.id}, function (err, account) {
            if (err) {
                logger.error('facebook authz error');
                return done(err);
            }

            if (account) {
                logger.error('facebook account found');
                return done(null, account);
            } else {
                logger.log('creating new account');
                var newAccount = new app.Account();
                newAccount.domain = profile.domain;
                newAccount.id = profile.id;
                newAccount.username = profile.displayName;

                newAccount.emails = profile.emails.map(function (email) {
                    return email.value;
                });

                newAccount.token = accessToken;
                newAccount.tokenSecret = refreshToken;


                return done(null, newAccount);

            }
        });

}

Thank you,

Pavel

deserializeUser called 10x

On login with in my app, I've noticed that deserializeUser is called 10x. Any ideas why this would be the case.
Any help would be greatly appreciated.

Thanks

Express/Passport Calls deserializeUser on response

First let me thank you for a great authentication framework, easy to use and implement custom strategies.

I have noticed using with express after a response is issued the deserialzeUser function is called causing an access to the store. A call was made to deserializeUser on request. I did more research and found in the express guide documentation, "Properties on req.session are automatically saved on a response". Is this why deserializeUser is called again? If so, is there a way to cache this information as to not hit the deserializeUser function again that also hits the database?

Thank you for your help, still newb wtih node.js, express etc..

Creating a strategy per request

I'd like to have different strategies assigned automatically based on the domain name used to access my application. More accurately, I'd like the same strategy with a different verify callback. Is there any way (that works across all strategy types) of modifying the verify callback (and other strategy settings) based on the domain name used?

"Error: failed to deserialize user out of session" unwanted on production

This is subjective but I believe a deserialization error from a bad session cookie/reset redis database/other regular production hiccup should not totally stonewall the unfortunate user with the problem. As things stand now, as soon as you get a deserialization error you're essentially blacklisted, and the error will be useless information to a typical user.

More desirable production behavior includes any of:

  1. Remove the session information and treat the user as a 'fresh' user who has not logged in
  2. Allow for a configuration option that can override this behavior (eg, gracefulFailure: true)
  3. Provide an override hook for handling failed deserializations, so the developer can at least override

google api refreshToken

I was trying to get refreshToken in "passport-google-oauth" example.
but the result was "undefined"

because of the "access_type" parameter, "passport-google-oauth" gave just only "id_token" parameter.

someone get same problem with me.
(https://groups.google.com/forum/#!searchin/oauth2-dev/id_token/oauth2-dev/2BjXHN3MMng/HP-sPVBhKAAJ)

bacause google changed their oauth endpoint,
(http://googlecode.blogspot.kr/2011/10/upcoming-changes-to-oauth-20-endpoint.html)
"passport-google-oauth" should be updated.

I added access type parameter in oauth2.js file in "passport-google-oauth\node_modules\passport-oauth\node_modules\oauth\lib\oauth2.js"

exports.OAuth2.prototype.getAuthorizeUrl= function( params ) {
var params= params || {};
params['client_id'] = this._clientId;
params['type'] = 'web_server';

// should add below params
params['access_type'] = 'offline';

return this._baseSite + this._authorizeUrl + "?" + querystring.stringify(params);
}

now I can get refreshToken :)

If the previous refresh token is not expired, you can not get a refresh token.
In this case, you have to get user consent again. For that you should add this params['approval_prompt'] = 'force' code also. but this code make user allow user consent every time.

Document how to establish sessions manually

Under "Custom Callback" in http://passportjs.org/guide/authenticate.html, the docs mention "… it becomes the application's responsibility to establish a session".

Since passport has already implemented this, it makes sense to just invoke it from the app.

The following code, adopted from in middleware/authenticate.js, seems to do the trick:

req.logIn(user, function (err) {
  if (err) {
    throw err;
  }

  // Session is established; redirect to destination or do something else
});

If this indeed correct, I think it's worthwhile to document it? Otherwise, is there a better way to do this?

Can't properly handle deserializeUser if the user can't be found

I am unable to deal with the case where the user's session has a user attached to it, but the user has been removed from the database. What I would like to do is simply remove the user from the session and require them to log in again (or create a new account).

However, there doesn't seem to be a way to access the request object from within deserializeUser() in order to call req.logout(). Furthermore, it seems that I can't even have a logout/ route handle this explicitly. Since deserializeUser() is called before the body of that request, if there is an error retrieving the user then I never reach the body of the method where I would be able to call req.logout().

express.static usage

Hi jared.

First of all i want to say that passport is a great auth library. It's simple yet powerful one. Keep up your good work.

Let me ask you something about passport in general. In connect/express application i'm using static route handler before your initialize/session handlers (code below) to reduce serialization overhead. Is it good or bad practise?

  app.use(express.logger());
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser());
  app.use("/public", express.static(__dirname + "/public")); // static route handler above others
  app.use(express.session({
    secret: "your secret",
    maxAge: new Date(Date.now() + 3600000),
    store: new mongoStore({ db: MongoDbConnection, collection: dbConfig.collection })
  }));
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);

Confusing documentation in passportjs.org/guide

Hey, I'm new to Node and Express and Passport, so I am muddling my way through and trying to get a site set up with authentication and sessions.

I'm looking at the authenticate page. The first example reads:

"authenticate()'s function signature is standard Connect middleware, which makes it convenient to use as route middleware."

app.post('/login', 
  passport.authenticate('local'),
  function(req, res) {
    // If this function gets called, authentication was successful.
    // `req.user` property contains the authenticated user.
  });

And the last example on that page reads:

app.get('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err) }
    if (!user) { return res.redirect('/login') }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      return res.redirect('/users/' + user.username);
    });
  })(req, res, next);
});

"In this example, note that authenticate() is called from within the route handler, rather than being used as route middleware. This gives the callback access to the req and res objects through closure."


I thought middleware was applied in a chain, passing the req/res objects down to whatever finally sends a response. But the first example looks to me like that is also calling authenticate() from within a route handler. Your configuration page has example code:

app.configure(function() {
  app.use(express.cookieParser());
  app.use(express.bodyParser());
  app.use(express.session({ secret: 'keyboard cat' }));
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);
  app.use(express.static(__dirname + '/../../public'));
});

This looks like the Express middleware chain to me, but you are not calling authenticate() anywhere.

So. Is there a way for me to authenticate each and every request somewhere in my chain of middleware, before it's passed to app.router? I want to check if the request came from an authenticated user in my routing functions, without calling authenticate() on a per-route basis.

Question for req.User

I managed to login through facebook and configured my app by copying from tutorials and example projects.

I have met a strange behaviour: My user object doesn't seem to be part of the request object. It feels like the user object gets lost after the login.

Can you please explain how the User object gets saved into my request object? I am using serialization and deserialization but I am not using express.DynamicHelpers like some people recommended here: http://stackoverflow.com/questions/11186174/passportjs-how-to-get-req-user-in-my-views/11187516#comment14711108_11187516

Would be really nice if you could enlighten me. Thanks

accept verify function as part of the options hash

This could be a far-reaching change but I think it would solve a problem that makes it hard to get started with Passport. It's possible to write quite a lot of JavaScript without having to pass both an options hash and a function as positional arguments to a function. When we do, novice and intermediate JavaScript programmers have to leave their comfort zone to format them. Here's what the code from the examples looks like:

passport.use(new GitHubStrategy({
    clientID: GITHUB_CLIENT_ID,
    clientSecret: GITHUB_CLIENT_SECRET,
    callbackURL: "http://127.0.0.1:3000/auth/github/callback"
  },
  function(accessToken, refreshToken, profile, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {

      // To keep the example simple, the user's GitHub profile is returned to
      // represent the logged-in user.  In a typical application, you would want
      // to associate the GitHub account with a user record in your database,
      // and return that user instead.
      return done(null, profile);
    });
  }
));

Having a line start indented four spaces from the previous space is something many developers aren't used to. This could be avoided by having the function be part of the options hash, much like jQuery's ajax function:

passport.use(new GitHubStrategy({
  clientID: GITHUB_CLIENT_ID,
  clientSecret: GITHUB_CLIENT_SECRET,
  callbackURL: "http://127.0.0.1:3000/auth/github/callback",
  verify: function(accessToken, refreshToken, profile, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {

      // To keep the example simple, the user's GitHub profile is returned to
      // represent the logged-in user.  In a typical application, you would want
      // to associate the GitHub account with a user record in your database,
      // and return that user instead.
      return done(null, profile);
    });
  }
}));

deserializeUser not being called

Not sure what I"m doing wrong, if anything. I have configured a LocalStrategy, and login seems to work fine, serializeUser gets called and works fine, but my req.user remains blank. req.session.passport is an empty object on subsequent requests, and putting a console.log statement in my deserializeUser logic shows that it's never called.

Here's the relevant code:

function authCallback(message, done){
return function(err, user){ // gets called and has a user and no errors
if(err){ console.error(err); return done(err);}
else if(!user) { return done(null, false, {message : message}); }
else {
return done(null, user);
}
}
}

passport.serializeUser(function(user,done){
console.log('serializing user' + user.id); // logs a user id successfully
done(null,user.id);
})

passport.deserializeUser(function(id, done){
console.log('deserializeUser: ' + id); // never gets called
User.findOne({_id : id}, done);
});

passport.use(new LocalStrategy(
function(username, password, done) {
User.authenticate(username, password, authCallback('Invalid username or password', done));
}
));

app.use(express.cookieParser(app.config.cookie_secret));
app.use(session_middleware); // req.session setup before passport
app.use(express.bodyParser());
app.use(express.methodOverride());

// auth stuff
app.use(passport.initialize());
app.use(passport.session());

app.use(app.router);

authenticate middleware with connect only?

Connect removed the router middleware (commit) and thus the ability to use authenticate as request middleware without using express.

Is there a way call authenticate inside the request handler while keeping the middleware chain intact? Or is there another router with request middleware capability? (I'm currently using dispatch, which is connect middleware but doesn't take request middleware.)

3 Tests failing

Environment

  • Snow Leopard
  • node v0.6.6
  • vows v0.6.1

Failing tests

 passport
    ✗ should create initialization middleware
    TypeError: Property 'length' of object function ok(value, message) {
  if (!!!value) fail(value, true, message, '==', assert.ok);
} is not a function
    at Object.<anonymous> (/Users/hunter/work/_libs/passport/test/index-test.js:24:14)
    at runTest (/usr/local/lib/node_modules/vows/lib/vows.js:132:26)
    at EventEmitter.<anonymous> (/usr/local/lib/node_modules/vows/lib/vows.js:78:9)
    at EventEmitter.<anonymous> (events.js:88:20)
    at EventEmitter.emit (/usr/local/lib/node_modules/vows/lib/vows.js:236:24)
    at Array.1 (/usr/local/lib/node_modules/vows/lib/vows/suite.js:168:45)
    at EventEmitter._tickCallback (node.js:192:40)

    ✗ should create session restoration middleware
    TypeError: Property 'length' of object function ok(value, message) {
  if (!!!value) fail(value, true, message, '==', assert.ok);
} is not a function
    at Object.<anonymous> (/Users/hunter/work/_libs/passport/test/index-test.js:29:14)
    at runTest (/usr/local/lib/node_modules/vows/lib/vows.js:132:26)
    at EventEmitter.<anonymous> (/usr/local/lib/node_modules/vows/lib/vows.js:78:9)
    at EventEmitter.<anonymous> (events.js:88:20)
    at EventEmitter.emit (/usr/local/lib/node_modules/vows/lib/vows.js:236:24)
    at Array.1 (/usr/local/lib/node_modules/vows/lib/vows/suite.js:168:45)
    at EventEmitter._tickCallback (node.js:192:40)

    ✗ should create authentication middleware
    TypeError: Property 'length' of object function ok(value, message) {
  if (!!!value) fail(value, true, message, '==', assert.ok);
} is not a function
    at Object.<anonymous> (/Users/hunter/work/_libs/passport/test/index-test.js:34:14)
    at runTest (/usr/local/lib/node_modules/vows/lib/vows.js:132:26)
    at EventEmitter.<anonymous> (/usr/local/lib/node_modules/vows/lib/vows.js:78:9)
    at EventEmitter.<anonymous> (events.js:88:20)
    at EventEmitter.emit (/usr/local/lib/node_modules/vows/lib/vows.js:236:24)
    at Array.1 (/usr/local/lib/node_modules/vows/lib/vows/suite.js:168:45)
    at EventEmitter._tickCallback (node.js:192:40)
✗ Errored » 105 honored ∙ 3 errored (0.027s)

passport with formaline

Have you guys ever tried to use passport with formaline forms?
It's like formaline dont let me use the bodyParser from Express and cant seem to get those two working. Any ideas?

cannot access req or res objects from authenticate callback

From looking through the code, the failureRedirect option appears to be the only way to respond to a failed authentication.
the callback function does not have access to req, and res objects.
Isn't there some way to make it possible to respond to a handle/respond to authentication failure from within the callback function?

initialization of strategies when app URL isn't known in advance

I am using passport successfully with express and the google, facebook and twitter strategies. However, I have one problem which I didn't see mentioned elsewhere and that is how I have to deal with the realm/returnURL or callbackURL if it isn't known in advance. (I think I saw something about relative URL support for OAuth2, but I don't think that covers all my cases; didn't work last time I tried). I would like this since it allows me to deploy the code everywhere without changing anything (facebook won't work since the url has to be the same in the app settings on their page, but google and twitter work fine).
First thing I tried was to create the strategies only upon the first request (use req.header('host') to get the URL), and this even works, but results in errors when logging out and logging back in (no problem when all cookies are cleared; something with the session?):

Error: no strategy registered under name: google
at Passport.authenticate (node_modules/passport/lib/passport/middleware/authenticate.js:143:35) 
at callbacks (node_modules/express/lib/router/index.js:272:11)
at param (node_modules/express/lib/router/index.js:246:11)
at pass (node_modules/express/lib/router/index.js:253:5)
at Router._dispatch (node_modules/express/lib/router/index.js:280:4)
 at Object.handle (node_modules/express/lib/router/index.js:45:10)
 at Context.next (node_modules/express/node_modules/connect/lib/http.js:204:15)
 at Context.<anonymous> (node_modules/passport/lib/passport/context/http/actions.js:64:8)
 at SessionStrategy.pass (native)
 at SessionStrategy.authenticate (node_modules/passport/lib/passport/strategies/session.js:51:10)

I guess the fact that I call passport.use(new ...Strategy...) after everything else is initialized doesn't work well??
What is the right approach to this problem? (For now, I use node's os.hostname() to determine if the code is running on the public server, in which case I know the url and can initialize as in all found passport examples; when the express server is started, and on development machines I use req.header('host') and initialize strategies upon the first request, since I can live with the above error on those, but it is a bit hackish to my taste :-)

Using OAuth for our own HTTP API?

If I get this right passport is for web applications (consumers) to let users log in with their service provider credentials like facebook, twitter etc.

But if I want to OAuth secure my own HTTP API for other consumers that is, being the service provider myself, how could I do that?

Passport is not for that use case?

Logout function does not always remove cookie on IE8

Strange bug this one, in IE8 only (IE9 is fine, so is Chrome & Safari on iPad).

To reproduce:
*log in
*navigat to a page in the app
*hit sign out => redirects to login
*Manually enter the last URL you were at => Access granted.

However, oddly this doesn't apply to all pages.

I guess this is related to how IE8 handles the delete session command. Is this your area or express/connect/node?

req.user does not survive a redirect

Hi, in my app I would like to redirect a user to another page after login:

app.post('/login', passport.authenticate('local', { failureRedirect: '/' }), function(req, res) {
  res.redirect('/editor');
});

the "editor" endpoint is protected against not authorized users:

app.get('/editor', ensureAuthenticated, function(req, res) {
    res.render( __dirname + '/views/editor.jade', { layout:false });        
});

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/')
}

On a breakpoint at res.redirect('/editor'); I see, that the request object was populated with all required information (req.user and req._passport.session.user), but after calling the redirect function this info seems to disappear. The ensureAuthenticated method redirects back to "/".

Here is my express configuration:

    app.use(express.cookieParser());
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(app.router);

Is something wrong with my code, or is it a bug?

Kind regards,
Artjom

Google OAuth example breaks when 'Deny Access'

Oauth 1.0 example breaks with error if I choose 'Deny Access' in the Google's grant access page.

failed to obtain access token (status: 400 data: The request token is invalid.)

Why it is not handled by failureRedirect handler ?
How to handle this error in the app and properly redirect ?

Duplicate of jaredhanson/passport-google-oauth#3
That forum seem to be inactive so I just posted it here.

Session storage through mongoose and passport

Hello, I'm writing because I can't seem to figure out how to get rid of connect-mongo from my application and simply just use passport session. The deserialize and serialize user methods don't seem to give me what I really need, a session ID. It seems that there needs to be a way to add a store to the passport session object, but I may be mistaken.

My question, where is a good spot to write to mongodb? serializeUser? If that's the spot, then I really don't have too much information besides the user object. This doesn't really adhere to the session store strategy that connect middleware asks for:

http://www.senchalabs.org/connect/middleware-session.html

Maybe ultimately I do need to have both connect-mongo and passport session, but it seems redundant.

Thanks for any help.

Chris

Flash messages not working with only successFlash or failureFlash booleans

This bug was discovered and confirmed through an exchange of late night tweets (of course!).

The current functions delegate.success and delegate.fail need patched to support boolean values provided through the authenticate function. We should also document this along with a snippet of info about passing a third argument to done() function callback with the flash object (e.g. done(err, user, { type: "success", "You have logged in" });). An example of this is found here in the basic login example.

delegate.success and delegate.fail provide a check for if (options.successFlash && info) { and if (options.failureFlash && challenge) { respectively -- and this conditional needs patched appropriately to support a default req.flash() function for boolean option successFlash and failureFlash values.

👍

Document how to create a strategy

Hi,

I'm trying to developp a WebID (http://webid.info/spec) strategy using my WebID node module (https://github.com/magnetik/node-webid).

As you can see in my demo (https://github.com/magnetik/node-webid-demo), the verification only require a X509 certificate in parameter :

        var verifAgent = new webid.VerificationAgent(certificate);
        verifAgent.verify(function (success, result) {

Maybe some documentation on how to developp a strategy on the wiki would be usefull.

Thanks

Document of authorize

I'm currently searching the way of multiple authentication. There is already a issue 11 though.

I found document about authorize describing

The application can continue to use the TwitterStrategy (under its default name twitter) for authentication.

and example code

passport.use(new TwitterStrategy({
    consumerKey: TWITTER_CONSUMER_KEY,
    consumerSecret: TWITTER_CONSUMER_SECRET,
    callbackURL: "http://www.example.com/auth/twitter/callback"
  },
  function(token, tokenSecret, profile, done) {
    User.findOrCreate(..., function (err, user) {
      if (err) { return done(err); }
      done(null, user);
    });
  }
));

In this case, third-party's account information is stored in Account schema. User schema isn't dealing with third-party data. The Account schema hold user's id. So I assume the last example code will be like this.

passport.use(new TwitterStrategy({
    consumerKey: TWITTER_CONSUMER_KEY,
    consumerSecret: TWITTER_CONSUMER_SECRET,
    callbackURL: "http://www.example.com/auth/twitter/callback"
  },
  function(token, tokenSecret, profile, done) {
    Account.find({
        domain: 'twitter.com',
        uid: profile.id
      }, 
      function(err, account) {
        if (err) { return done(err); }
        if (account) { 
          User.findById(account.uid,
             function(err, user){
               if (err) return done(err);
               return done(null, user);
             }
           );
           return;
        }                                                
        var user = new User();
        user.name = profile.name;
        user.save(function(err, user) {
          var account = new Account();
          account.domain = 'twitter.com';
          account.uid = profile.id;
          var tok = { kind: 'oauth', token: token, attributes: { tokenSecret: tokenSecret } };
          account.tokens.push(tok);
          account.userId = user.id;
          account.save(function(err, account) {
            if (err) return done(err);
            done(null, user);
          });
        });
      }
    );            
  }
));

I'm also wondering how I deal with tokens. Tokens are stored in session, right? The example is storing tokens into Account.
Once token is stored in database, I'll have to remove expired tokens from Account, and push new tokens. Is it right way not to store tokens in Account if I think it's cumbersome to deal with tokens?

I'm understanding there is no such thing as one right way of database planing. But I want to know the best practice of handling multi third-party account.

Error: passport.initialize() middleware not in use

I get this error when I try to authenticate with the google OAuth2 strategy, the relevant code can be found here.

Now, when I navigate to /auth/google, I get properly redirected and my debug shows that I receive the profile. But then, node stops with the error:


DEBUG: /home/scan/JavaScript/ponyfolder/node_modules/mongoose/lib/utils.js:436

DEBUG:         throw err;

DEBUG:         
DEBUG:       ^

DEBUG: Error: passport.initialize() middleware not in use
    at IncomingMessage.req.login.req.logIn (/home/scan/JavaScript/ponyfolder/node_modules/passport/lib/passport/http/request.js:30:30)
    at Context.module.exports.delegate.success (/home/scan/JavaScript/ponyfolder/node_modules/passport/lib/passport/middleware/authenticate.js:174:13)
    at Context.actions.success (/home/scan/JavaScript/ponyfolder/node_modules/passport/lib/passport/context/http/actions.js:21:25)
    at verified (/home/scan/JavaScript/ponyfolder/node_modules/passport-google-oauth/node_modules/passport-oauth/lib/passport-oauth/strategies/oauth2.js:133:18)
    at Promise.app.get.passport.authenticate.scope (/home/scan/JavaScript/ponyfolder/app/auth.coffee:34:16)
    at Promise.addBack (/home/scan/JavaScript/ponyfolder/node_modules/mongoose/lib/promise.js:128:8)
    at Promise.EventEmitter.emit (events.js:88:17)
    at Promise.emit (/home/scan/JavaScript/ponyfolder/node_modules/mongoose/lib/promise.js:66:38)
    at Promise.complete (/home/scan/JavaScript/ponyfolder/node_modules/mongoose/lib/promise.js:77:20)
    at cb (/home/scan/JavaScript/ponyfolder/node_modules/mongoose/lib/query.js:1392:32)

I have no idea where to go from there. First time using Mongoose, so perhaps I did something wrong there.

Using express 3 and mongoose 3.

Authenticate should set the req.user if successful

Hi Jared, I stumbled upon a little problem. I have this code here:

@app.post "/sessions", @passport.authenticate("local", failureRedirect: "/sessions/login"), (req, res) ->
    res.redirect @sessionRoutesPathHelper.profile(req.user.username)

which, upon successful authentication should redirect to the users profile page. This does not work though as the user object in req is only set in the next request, after the redirect.

I think it would be a good idea to set req.user to the user in authenticate before invoking the callback

Multiple "local" strategies

Hi

This is not so much a bug, but rather a question on if something can be achieved using the current implementation. Also, I'm not very proficient in passport or node, so please pardon me if I say something stupid.

Anyway, I'm trying to implement an kind of online "mini shopping mall", using express, sequelize over mysql and, ofc, passport. As usual, there's a table for customers but also a table for the several companies selling their stuff on the site.

My idea, if possible, is to have 2 LocalStrategies, one for each of the above mentioned user types. Of course, customers and sellers will have two completely different interfaces, so I was wondering if it possible to have two LocalStrategies plugged into passport, and then validate authentication based on each of them (so that if a customer tries to access the companies' backoffice pages, they get denied access).

I've checked another bug report talking about multiple strategies, but it seems to me that, once a user is logged in, passport just cares that he is authenticated, not the method he used. Also, i was left with the idea that strategies are accessed by identifier, so using two of the same type would be tricky/not possible.

Thanks in advance, and congratulations on your great work on passport
cheers

Some Error

I tried integrating passportjs by just copying the code from web , sorry i am really new to this stuffs.

passport.use(new TwitterStrategy({
consumerKey: TWITTER_CONSUMER_KEY,
consumerSecret: TWITTER_CONSUMER_SECRET,
callbackURL: "http://www.example.com/auth/twitter/callback"
},
function(token, tokenSecret, profile, done) {
User.findOrCreate(..., function (err, user) {
if (err) { return done(err); }
done(null, user);
});
}
));

" User.findOrCreate(..., function (err, user)"

What should be there instead for for dots.

Handle multiple authentication protocols

It would be super useful to be able to allow users to utilize multiple authentication strategies for the same account. Everyauth offers this but there is too much abstraction. However, I do like how you specify which auth protocols each user is using.

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.