Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unknown authentication strategy "local"

I'm trying to authenticate users on my website and I got this error

Unknown authentication strategy 'local-login'

I've tried changing the name of the strategy, also I've read other threads in SO but didn't find a solution.

// Passport
module.exports = function(passport) {
    passport.serializeUser(function(user, done) {
    done(null, user.id);
});

passport.deserializeUser(function(id, done) {
    connection.query('SELECT * FROM `users` WHERE `id` = ' + connection.escape(id), function(err, rows) {
        done(err, rows[0]);
    });
});

passport.use('local-login', new LocalStrategy({
    usernameField : 'username',
    passwordField : 'password'
},
function(req, username, password, done) {
    connection.query('SELECT * FROM `users` WHERE `username` = ' + connection.escape(username), function(err, rows) {
        if(err)
            return done(err);
        if(!rows.length) {
            return done(null, false, req.flash('loginMessage', 'Invalid username or password. Please try again.'));
        }
        if(!(rows[0].password == password))
            return done(null, false, req.flash('loginMessage', 'Invalid username or password. Please try again.'));

        return done(null, rows[0]);
    });
  }));
}

// Express Router
app.use(sessionMiddleware);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use('/static', express.static('./static'));

app.post('/login/auth', passport.authenticate('local-login', {
    successRedirect: '/dashboard',
    failureRedirect: '/',
    failureFlash: true
}));
like image 242
GhoSTBG Avatar asked Feb 17 '26 10:02

GhoSTBG


1 Answers

First check your installation with:

npm install passport passport-local --save

Then import passport like below:

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;

before your app.use() methods:

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

Then use it as follows. (No need to give 'local-login' as a first argument)

passport.use(new LocalStrategy({
    usernameField : 'username',
    passwordField : 'password'
}, (req, username, password, done) => {
     // Your logic here...
       ...
       .. 
  }));
}

Finally in your router:

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

More info: passport-local

like image 70
gokcand Avatar answered Feb 20 '26 02:02

gokcand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!