Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually call passport for authentication

I develop a restful nodeJS API protected by a oauth2 authentication using passport.

  var express = require('express');
    var passport = require('passport');
    var port = process.env.PORT || 8080;
    var app = express();

    app.use(passport.initialize());

    // Create our Express router
    var router = express.Router();
    var creatureController = require('./controllers/creature');

    router.route('/creature').get(passport.authenticate('accessToken', {session: false}), creatureController.getProfile);

In this case, the route is protected and it requires to send a valid token in order to access to the route.

I want to find a way to authenticate my "users" manually, by calling a function, which take the username and password of the user I want to authenticate.

like image 839
Bob Avatar asked Jun 20 '15 10:06

Bob


People also ask

How does Passport authenticate local work?

The local authentication strategy authenticates users using a username and password. The strategy requires a verify callback, which accepts these credentials and calls done providing a user.

What is Passport authentication?

Passport is a popular, modular authentication middleware for Node. js applications. With it, authentication can be easily integrated into any Node- and Express-based app. The Passport library provides more than 500 authentication mechanisms, including OAuth, JWT, and simple username and password based authentication.


1 Answers

Passport exposes a req.login() function that can be used to login the user manually.

app.post('/login', function (req, res, next) {
    var user = User.findOrCreate(req.body);
    // … your authentication or whatever
    req.login(user, function(err){
        if(err) return next(err);
        res.redirect('/home');
    });
});
like image 179
laggingreflex Avatar answered Oct 05 '22 20:10

laggingreflex