authentication through passport and mysql in nodejs

Sivvio Source

I'm trying to develop an authentication component through node using passport. We are using a relational db, namely mysql, but I'm having issues hitting the endpoint and actually authenticate the user.

I have 2 files:

app.js

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

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

app.post('/login',
  passport.authenticate('local', { failureRedirect: '/error' }),
  function(req, res) {
    res.redirect('/success?username='+req.user.username);
});

and passport.js

var LocalStrategy = require('passport-local').Strategy;
var db = require('./db'); //where the db instance is exported

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

// used to deserialize the user
passport.deserializeUser(function (id, done) {
    db.query("select * from user where id = " + id, function (err, rows) {
        done(err, rows[0]);
    });
});
passport.use(new LocalStrategy(
    function (username, password, done) {
        db.query("select * from user where username= " + username, function (err, rows) {
            done(err, rows[0]);
            console.log(rows)
        });
    }
));

According to the documentation, this is the right way of doing it, but obviously I must be doing something wrong because this is the error message I get when I try to do a post request with the username and password object:

2:8888/login:1 OPTIONS http://localhost:8888/login 404 (Not Found) localhost/

:1 Failed to load http://localhost:8888/login: Response for preflight has invalid HTTP status code 404.

Any suggestions? Thank you all

node.jspassport.jspassport-local

Answers

answered 3 months ago UchihaItachi #1

Prima facie, it looks like This is an issue for corsas your express app is not serving a response to the preflight request. Please install the npm module cors.

npm install --save cors

Then make the following changes to app.js .

var passport = require('./passport');
//Added lines
var cors = require('cors');
app.use(cors());
//Added lines end
app.use(passport.initialize());
app.use(passport.session());

app.post('/login',
  passport.authenticate('local', { failureRedirect: '/error' }),
  function(req, res) {
    res.redirect('/success?username='+req.user.username);
});

There are other ways around it too, but I think it is the most simple.

comments powered by Disqus