[Fixed] Error: Unknown authentication strategy "local" while trying to signin

Issue

I have been building this project from a tutorial. The signup functionality works fine but the login feature doesn’t work. Whenever I try logging in a registered user using postman the error I get is

Error: Unknown authentication strategy "local"

In the other posts on stack overflow, I didn’t find a solution to this error. Passport, passport-local and passport-jwt are all installed so that shouldn’t be the issue. I would really appreciate any sort of help.

passport.js

require('dotenv').config();
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const JWTStrategy = require('passport-jwt').Strategy;
const User = require('./models/User');

// Environment variables
const STRATEGY_KEY = process.env.STRATEGY_KEY;

const cookieExtractor = req => {
    let token = null;

    // Retrieve the token from cookies
    if (req && req.cookies) {
        token = req.cookies['access_token'];
    }

    return token;
};

const jwtOptions = {
    jwtFromRequest: cookieExtractor,
    secretOrKey: STRATEGY_KEY,
};

// Authorization for protected routes
passport.use(
    new JWTStrategy(jwtOptions, (payload, done) => {
        User.findById({ _id: payload.sub }, (err, user) => {
            // Check for error
            if (err) return done(err, false);

            // Check if user exists
            if (user) return done(null, user);

            return done(null, false);
        });
    })
);

// Local strategy using username and password
passport.use(
    new LocalStrategy((username, password, done) => {
        User.findOne({ username }, (err, user) => {
            // Error while fetching the user from database
            if (err) return done(err);

            // No such user exists
            if (!user) return done(null, false);

            // Check if entered password matches
            user.comparePassword(password, done);
        });
    })
);

routes.js

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

const router = express.Router();     


const STRATEGY_KEY = process.env.STRATEGY_KEY;

const signToken = userID => {
    return jwt.sign(
        {
            iss: STRATEGY_KEY,
            sub: userID,
        },
        STRATEGY_KEY,
        {
            expiresIn: '1h',
        }
    );
};

router.post(
    '/signin',
    passport.authenticate('local', { session: false }),
    (req, res) => {
        if (req.isAuthenticated()) {
            const { _id, username, email } = req.user;
            const token = signToken(_id);
            res.cookie('access_token', token, {
                httpOnly: true,
                sameSite: true,
            });
            res.status(200).json({
                isAuthenticated: true,
                user: {
                    username,
                    email,
                },
            });
        }
    }
);

module.exports = router;

Solution

So after many hours of debugging, the solution I found to this problem was that I didn’t import passport.js file in routes.js file, which I was not expecting since that import stays there ideal not doing anything, not being part of any code(exceot the import) but I was wrong. The passport configuration we make in that file is imported under the hood even though it doesn’t take part in any further lines of that file.

Leave a Reply

(*) Required, Your email will not be published