menu

Questions & Answers

Passport.js "Missing credentials"

I use Passport for my app and I can't log in or start a session. I guess, that 'passport.authenticate('local', ...)' doesn't invoke my LocalStrategy.

I tried to locate the issue and wrote three console.log's. The first console.log(err, user, info) logs 'null, false, { Missing credentials }', when the 'passport.authenticate('local', ...' function is called. The second console.log('test1') never logs, because user is false. And the third console.log('test2') never logs too, because LocalStrategy might never get called.

app.js

const express = require('express');
const app = express();
require('dotenv').config();

const { mongoose } = require('./db/mongoose');
const { User } = require('./db/model/user.model');

const bcrypt = require('bcrypt');

const bodyParser = require('body-parser');
app.use(bodyParser.json());

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', 'http://localhost:4200');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    res.header('Access-Control-Allow-Credentials', 'true');
    next();
});

const session = require('express-session');
app.use(session({
    name: 'passport-session',
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false,
    cookie: {
        maxAge: 36000000,
        httpOnly: false,
        secure: false,
    }
}));

const passport = require('passport');
require('./passport-config');
app.use(passport.initialize());
app.use(passport.session());

app.post('/login', function (req, res, next) {
    passport.authenticate('local', function(err, user, info) {
        if(err) return res.send(err);
        console.log(err, user, info)
        if(!user) return res.send(info);
        console.log('test1')
        req.logIn(user, function(err) {
            if(err) return res.send(err);
            return res.send(true);
        })
    })(res, req, next);
});

app.get('/auth', (req, res) => {
    if(req.isAuthenticated()) res.send(true);
    else res.send(false);
})

app.get('/logout', (req, res) => {
    req.logout();
})

app.post('/register', async (req, res) => {
    let name = req.body.name;
    let password = await bcrypt.hash(req.body.password, 10);

    try {
        let newUser = new User({
            name,
            password,
            cart: [],
            equipment: [],
            points: 100,
        });
        await newUser.save();
        res.send(true);
    } catch {
        res.send(false)
    }
})

app.listen(3000, () => {
    console.log('Server is listening on port 3000');
})

passport-confiq.js

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

const { User } = require('./db/model/user.model');

passport.use('local', new LocalStrategy({
    usernameField: 'name',
    passwordField: 'password',
},
    function(username, password, done) {
        console.log('test2')
        User.findOne({ name: username }, function(err, user) {
            if(err) return done(err);
            if(!user) return done(null, false, { message: 'Name ist ungültig.' });
            if(!user.validPassword(password)) return done(null, false, { message: 'Passwort ist ungültig.' });
            return done(null, user);
        })
    }
))

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

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

I tried different approaches to setup my Passport and checked a typical mistakes, like e.g. to parse the request body and so on.

I hope someone has an idea, what I'm missing.

Comments:
2023-01-07 20:33:54
passport-confiq.js is your file actually called that? If so, that is why
2023-01-07 20:33:54
yes, my file is called like that
Answers(0) :