EzDevInfo.com

passport-local

Username and password authentication strategy for Passport and Node.js.

Does the passport.js support ajax?

I want to make ajax login with the passport.js. I have the usual code for setting the passport.js:

//route
app.post('/api/auth/login', passport.authenticate('local-login', {
    successRedirect: '/',
    failureRedirect: '/login'
}));

//config strategy
passport.use('local-login', new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password',
    passReqToCallback: true
}, loginUser));

var loginUser = function(req, email, password, done) {

    UserRepo.getOne({
        'local.email': email
    }).done(function(user) {

            if (!user || !user.validPassword(password)) {
                return done(null, false, {
                    message: 'user or password is incorrect'
                });
            }

            return done(null, user);

        },
        function(err) {
            return done(err);
        });
};

This is my react component:

var Login = React.createClass({
  //...
  handleSubmit: function (e) {
        e.preventDefault();

        var email = this.state.email.trim();
        var password = this.state.password.trim();
        var data = {
            email: email,
            password: password
        };

        api.auth.login(data, function (result) {
            console.log(result);            
        });    
    },

    render: function () {
        return (
            <form className="login-form" onSubmit={this.handleSubmit}>
                <section>
                    <label>email</label>
                    <input name="email" type="text" />

                    <label>password</label>
                    <input name="password" type="password"  />
                </section>
                <section>
                    <input type="submit" value="send"/>
                </section>
            </form>
        );
    }
  //...
})

But, it doesn't work, because redirects (successRedirect and failureRedirect) do their work. If I delete failureRedirect I get 401 status. I understand that my code for passport for server side rendering and page refresh, but I cannot find any documentation for ajax login.


Source: (StackOverflow)

NodeJS|SailsJS|PassportJS AJAX Authentication: Making Successive Requests for Data

Making Successive Requests for Data

TL;DR

After authentication, I cannot request data from my app's Front-End -- but only through server-side views and Postman can I make subsequent requests for data after logging in, or by authenticating my user in Postman and then making the data request in my app.

First off, I'm a newbie on the server-side.

I've a SailsJS backend which I'm using for REST. Creating and authenticating a user, using LocalStrategy, works fine -- and really, even making subsequent requests for data works fine -- but not via AJAX from my app.

I can use Postman or server-side views to access data, such as /list; making requests after authentication in my app doesn't work -- UNLESS I jump back into Postman and login, then jump back to my app and remake the request.

I do notice that my set-cookie's in my app are different between the first authentication request and the request for /list.

If necessary, I can show some code, but this seems I'm missing a very high-level, basic concept in making authenticated AJAX requests.

EDIT: My front-end is on a different domain -- Sails runs on localhost:1337 while my UI runs on localhost:8100.

Here's what my /api/config/cors.js looks like:

module.exports.cors = {

  allRoutes: true,

  origin: '*',

  credentials: true,

  // methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD',

  // headers: 'content-type'

};

I'm using angular on the front-end, and the subsequent requests are using withCredentials: true -- do I need to add this to the login request too? Must I send the username/email along in the request also?

How do I allow all my subsequent requests for data authenticated after login?


Source: (StackOverflow)

Advertisements

how to send json as a response after passport authenticationin node.js

I am trying this git example.

Which works well when I integrated it with my project, but what I want to achieve is to send json as a response to the client/request, instead of successRedirect : '/profile' & failureRedirect : '/signup'.

Is it possible to send a json, or is there some other methods to get the same?

Any help will be appreciated,TU


Source: (StackOverflow)

Passport Session management when cookies are disabled

I am making a web app with AgularJS as my front-end and Sails(NodeJS + Express) as my backend. I am using passport (passport-local) for authentication and it all seemed to work great until I tested it in safari. I noticed that the sessions would always return null.

I was using passport session for authorization and I couldn't fetch the session variable using req.session.passport since it was empty. I figured out that I had cookies disabled in Safari. This would break my app's authorization. Is there a way to have session management which would work even if cookies are disabled in a browser?


Source: (StackOverflow)

Hapi.js API Authentication

I am trying to use hapi and the passport-local strategy. First I am trying to get 'static' users to work then I plan on pushing user info into a database. What I have below (as well as at https://github.com/RyanHirsch/hapi-auth-poc) will authenticate a user hitting the website as expected, but I can't figure out how to properly authenticate API requests. For testing I am simply trying to use cURL to send the GET along with username/password and not getting a successful login.

Where am I going wrong? How do I allow credential handling on API requests using hapi and passport?

var Hapi = require('hapi');
var LocalStrategy = require('passport-local').Strategy;

var config = {
    hostname: 'localhost',
    port: 8000,
    urls: {
        failureRedirect: '/login'
    },
    excludePaths: ['/public/']
};
var plugins = {
    yar: {
        cookieOptions: {
            password: "worldofwalmart",
            isSecure: false
        }
    },
    travelogue: config // use '../../' instead of travelogue if testing this repo locally
}

var server = new Hapi.Server(config.hostname, config.port);
server.pack.require(plugins, function (err) {
    if (err) {
        throw err;
    }
});

server.auth.strategy('passport', 'passport');

var USERS = {
    "van": "walmart"
};

var Passport = server.plugins.travelogue.passport;
Passport.use(new LocalStrategy(function (username, password, done) {

    // Find or create user here...
    // In production, use password hashing like bcrypt
    if (USERS.hasOwnProperty(username) && USERS[username] == password) {
        return done(null, { username: username });
    }

    return done(null, false, { 'message': 'invalid credentials' });
}));
Passport.serializeUser(function (user, done) {

    done(null, user);
});
Passport.deserializeUser(function (obj, done) {

    done(null, obj);
});

// routes
server.route({
    method: 'GET',
    path: '/',
    config: { auth: 'passport' }, // replaces ensureAuthenticated
    handler: function (request, reply) {

        // If logged in already, redirect to /home
        // else to /login
        reply().redirect('/home');
    }
});

server.route({
    method: 'GET',
    path: '/login',
    config: {
        handler: function (request, reply) {
            if (request.session._isAuthenticated()) {
                reply().redirect('/home');
            } else {
                var form = '<form action="/login" method="post"> <div> <label>Username:</label> <input type="text" name="username"/> </div> <div> <label>Password:</label> <input type="password" name="password"/> </div> <div> <input type="submit" value="Log In"/> </div> </form>';
                reply(form);
            }
        }
    }
});


server.route({
    method: 'GET',
    path: '/home',
    config: { auth: 'passport' },
    handler: function (request, reply) {
        // If logged in already, redirect to /home
        // else to /login
        reply("ACCESS GRANTED<br/><br/><a rel='nofollow' href='/logout'>Logout</a>");
    }
});

server.route({
    method: 'GET',
    path: '/api/home',
    config: {
        validate: {
            payload: {
                username: Hapi.types.String(),
                password: Hapi.types.String()
            }
        },
        auth: false,
        handler: function (request, reply) {
            // If logged in already, redirect to /home
            // else to /login
            Passport.authenticate('local')(request, function (err) {
                console.log("successful authentication?");
                if (err && err.isBoom) {}
                if(request.session._isAuthenticated()) {
                    reply({message: "logged in"});
                }
            });
            // reply({ "working" : "success" });
        }
    }
});

server.start(function () {
    console.log('server started on port: ', server.info.port);
});

Source: (StackOverflow)

User not defined in public page with sailsjs passport

I've used sails-generate-auth to add an authentication to my website. The authentication is working fine: I can only access public pages if I'm not authenticated.

My index page is public, its controller's policy is set to true:

/config/policies.js
'*': ['passport', 'sessionAuth'],

'auth': {
   '*': ['passport']
},
'IndexController' : true

Problem: In my layout I want to display either the login button or the username:

/views/layout.ejs
[....]
<% if ( user != undefined ){ %>
    <li><a rel='nofollow' href="/logout"><%= user.username %> <i class="fa fa-sign-out"></i></a></li> 
<% }else{ %>
    <li><a rel='nofollow' href="/login"></i>Login <i class="fa fa-sign-in"></i></a></li> 
<% } %>  
[...]

However, I can't acces the user variable on these public pages, I get

user not defined

I managed to display the username (ie access the user variable) only on views generated in restricted controllers.

====== New little problem:

On the login page, the variable user is defined, so the if statement is true and the user.name is displayed in the layer. However the user is not logged yet, and the result is that user.name shows "undefined":

screen of the problem

I tried:

<% if ((typeof user) != 'undefined' && (user.name != 'undefined')){ %>

but "undefined" still show in the layout. With this:

<% if ((typeof user) != 'undefined' && (typeof (user.name) != 'undefined')){ %>

The statement is never true and "Login" is displayed on every pages, even after login.

Any idea how to proceed ?


Source: (StackOverflow)

Passport not redirecting after authorization

I am running into a problem where when I try to login using passport, the page does not redirect. The authorization return true (correct username, password).

I'm pretty sure it lies somewhere within my validPassword function but i'm not sure exactly.

Login Route

app.get('/login', function (req, res) {
  res.render('login', {});
});

Login Post

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

User Prototype

User.prototype.validPassword = function(username, unhashedPassword) {
  async.waterfall([
    function (callback) {
      User.find({ "username" : username }, function (err, data) {
        if(err) return handleError(err);
        callback(null, data);
      });
    },
    function (data, callback) {
      var isGood = passwordHash.verify(unhashedPassword, data[0].password);
      callback(null, isGood);
    }
  ], function (err, result) {
    return result;
  });
};

Local Strategy

passport.use(new LocalStrategy(
  function(username, password, done) {
    var unhashedPassword = password;
    var passedUsername = username;
    User.findOne({ username: username }, function(err, user) {
      if (err) { return done(err); }
      if (!user) {
        return done(null, false, { message: 'Incorrect username.' });
      }
      if (!user.validPassword(passedUsername, unhashedPassword)) {
        return done(null, false, { message: 'Incorrect password.' });
      }
      return done(null, user);
    });
  }
));

There are no errors being printed out to my console so I'm slightly baffled right now. Is the isGood being returned in the wrong format maybe? Any help would be great.


Source: (StackOverflow)

Verification email with token in passport.js

I just looking for solution which makes verification email with token for my local autentification in passport.js Is there some plugin or component for node which can make me verification easyer? Or I have to do it myself?

My controller

exports.postSignup = function(req, res, next) {
  req.assert('email', 'Email is not valid').isEmail();
  req.assert('password', 'Password must be at least 4 characters long').len(4);
  req.assert('confirmPassword', 'Passwords do not match').equals(req.body.password);

  var errors = req.validationErrors();

  if (errors) {
    req.flash('errors', errors);
    return res.redirect('/signup');
  }

  var user = User.build({
    email: req.body.email,
    password: req.body.password,
  });

  User
  .find({ where: { email: req.body.email } })
  .then(function(existingUser){
    if (existingUser) {
      req.flash('errors', { msg: 'Account with that email address already exists.' });
      return res.redirect('/signup');
    }

    user
    .save()
    .complete(function(err){
      if (err) return next(err);
      req.logIn(user, function(err){
        if (err) return next(err);
        res.redirect('/');
      });
    });
  }).catch(function(err){
    return next(err);
  });
};

Thanks for any opinion!


Source: (StackOverflow)

Auth/Session not working on one page in Sails with Passport

I have used passport to manage authentication in Sails. It is working bar one odd issue. If I check for a user in order to modify the nav bar

<ul class="nav navbar-nav navbar-right">
            {{#if user}}
                <li>{{ user.username }}</li>
                <li><a rel='nofollow' href="/logout">Logout</a></li>
                User!
            {{else}}
                <li><a rel='nofollow' href="/login">Login</a></li>
            {{/if}}
        </ul>

The log in and go to / There is nothing there. When I go to /login or /logout, both of which use the same template and share the code above, I get both conditions being met.

screenshot

Any ideas?


Source: (StackOverflow)

NodeJS and Passport signup not working - no error

I have published the current version on github: https://github.com/rcbgit/boiler

The user seems to be "logging in". At least the successful redirect happens with valid username/pw and the failure redirect happens with a bad combo. The problem I'm having is that I don't know how to store the user information after the login or validate a page against it (restrict access). I created a basic 'Auth' service that stores the user information but i'm not sure how to use it properly.

I'm also having trouble figuring out how to handle messages back from the server such as "Username already exists!".

Any advice is appreciated!


Source: (StackOverflow)

How, with passport.js's passport-local or other Node.js tools can I have the equivalent of full CRUD?

I've looked at the documentation in passport.js and the passport-local strategy seems markedly incomplete.

If you have a populated base of Users who have their passwords in whatever form, then from that it's plain from the docs at http://passportjs.org/docs/username-password how to let people try to log in, get a useful failure message (and, from a usability perspective, nicely inform which one it was of a username or password that didn't match), and if they've given valid credentials, log in.

However, there is a sort of CRUD set of basic functionality surrounding username-password authentication. Often it is desired for people to be able to create their own accounts; also if they have forgotten their passwords, they should be able to request a "reset password" link and be able to get to the point of being able to log in without having a plaintext password emailed to them. All of this is a bit of a chore, but it is a base that needs to be covered like various applications need CRUD to be covered.

The documentation I've read about passport-local doesn't discuss this, and what I was looking for looked like a way with Mongoose to manually reinvent this quasi-CRUD side of username-password authentication. I don't know if this a limitation of passport-local or the docs.

If I want to have routine features for a public website with accounts that people can create for themselves, and I'm already using Express.js and (negotiably) Passport.js, what are my options?

Thanks,


Source: (StackOverflow)

Passport throwing "undefined is not a function"

This is my first time using passport.

I keep getting this error when I try to launch my app:

passport.use(new LocalStrategy(Account.authenticate()));
             ^
TypeError: undefined is not a function
    at Object.<anonymous> (/Users/drewwyatt/Sites/JS/Node/MWInternal/app.js:38:14)

Here's the (relevant) portions of app.js

var express = require('express');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').LocalStrategy;

var app = express();
var connectionString = '***************';


// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

// passport config
var Account = require('./models/account');
passport.use(new LocalStrategy(Account.authenticate()));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());

mongoose.connect(connectionString);

var routes = require('./routes');

...

/models/account.js

var mongoose = require('mongoose'),
    Schema = mongoose.Schema
    passportLocalMongoose = require('passport-local-mongoose');

var Account = new Schema({
    email: String,
    password: String
});

Account.plugin(passportLocalMongoose);

module.exports = mongoose.model('Account', Account);

What am I missing?


Source: (StackOverflow)

Passport local strategy done callback does not pass error json message

I am trying to pass a JSON message when authentication fails, using done callback in the LocalStrategy, but all I get is 401 and "Unauthorized" string in the response.

var express = require('express');
var bodyParser = require('body-parser');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

var app = express();
app.use(bodyParser.json());
app.use(passport.initialize());

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

var strategy = new LocalStrategy({ usernameField: 'email' },
    function (email, password, done) {
        if (email === 'test@gmail.com' && password === 'pass') {
            return done(null, { email: 'test@gmail.com' });
        } else {
            // never get this json object on the client side when posting invalid credentials
            return done(null, false, { message: 'invalid email or password' });
        }
    }
);

passport.use(strategy);

app.post('/login', passport.authenticate('local'), function(req, res) {
    console.log(req.user);
    res.json(req.user);
});


app.get('/', function(req, res) {
    res.json({ message: 'hello!' });
});

var server = app.listen(3000, function() {
    console.log('api is listening on ', server.address().port);
});

package.json

{
  "name": "passport_example",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.13.3",
    "express": "^4.13.3",
    "passport": "^0.2.2",
    "passport-local": "^1.0.0"
  }
}

What am I doing wrong?


Source: (StackOverflow)

Can you authenticate with Passport without redirecting?

I have the following working code to authenticate through the passport-local strategy:

  app.post('/api/login', passport.authenticate('local-login', {
    successRedirect : '/api/login/success',
    failureRedirect : '/api/login/error',
    failureFlash : true
  }));
  app.get('/api/login/error', function(req, res) {
    res.send(401, {error: req.flash('loginMessage')});
  });
  app.get('/api/login/success', function(req, res) {
    res.send(200, {user: req.user});
  });

However, ideally I want to handle the errors and success messages from one express route, and not redirect to two extra routes.

Is this possible? I tried using a 'custom callback' but that seemed to error out on serializing users for some reason.


Source: (StackOverflow)

Passport "Hello World" always fails

I have the following:

import {Router} from 'express';
import passport from 'passport';
import {Strategy} from 'passport-local';
import pg from 'pg';
import {pgUri} from '../environment';

let loginRouter = Router();

passport.use(new Strategy((username, password, done) => done(null, true)));
//{
//    pg.connectAsync(pgUri)
//        .then(([client, release]) => {
//            return client.queryAsync('select * from users where "user" = $1::TEXT', [username])
//                .finally(release);
//        })
//        .tap(result => console.log(result.rows))
//        .then(result => done(null, true));
//}));

loginRouter.get('/', (request, response) => response.render('login'));
loginRouter.post('/', passport.authenticate('local', {successRedirect: '/',
                                                      failureRedirect: '/login'}));

export default loginRouter;

It's an express route file that defines the simplest possible authentication scheme. The above always redirects back to /login, indicating a failure.

What I've tried

  • Changing failureRedirect to /loginFailed really redirects there. So the login does fail.
  • Breakpoints and console.logs inside the function body do not get hit.
  • Calling done with done(null, {foo: "bar"}) instead of true changes nothing.

Worth noting

  • I'm using babel for ES6 support, but since this is the only part failing, and the breakpoints I can set (before passport.use) show expected values for all variables, I don't think that's the problem.
  • The .get() route works as expected, displaying the form.

I have this in my bootstrap phase:

app.use(session({
    secret: "some-secret",
    resave: true,
    saveUninitialized: true
}));

app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser((user, done) => done(null, {foo: "bar"}));

passport.deserializeUser((user, done) => done(null, {foo: "bar"}));

Here's the form I'm using (directly copied from the passport example)

<form action="/login" method="post">
    <div>
        <label>Username:</label>
        <input type="text" name="username"/>
    </div>
    <div>
        <label>Password:</label>
        <input type="password" name="password"/>
    </div>
    <div>
        <input type="submit" value="Log In"/>
    </div>
</form>

I have no idea what went wrong here. Would appreciate any help.


Source: (StackOverflow)