Issue: Unrecognized security method called "local" (Express & Passport)

I'm currently attempting to implement passport authentication within my express application.

router.get('/register', (req, res) => {
  res.render('register');
});

router.post('/register', function(req, res, next) {
  var username = req.body.username;
  var password = req.body.password;

  User.findOne({ username: username }, function(err, user) {

    if(err) { return next(err); }
    if(user) {
      req.flash('error', 'User already exists');
      return res.redirect('/register');
    }

    var newUser = new User({
      username: username,
      password: password
    });
    newUser.save(next);
  });
}, passport.authenticate('local', {
  successRedirect: '/',
  failureRedirect: '/register',
  failureFlash: true
}));

Although signing up a test user seems to work, I keep encountering the following error:

Error: Unknown authentication strategy "local"

Do you have any advice or suggestions on how to resolve this issue?

Answer №1

If you haven't set up Passport to utilize the passport-local strategy yet, don't worry! You just need to follow a few steps - import it, instantiate it, and then tell Passport to put it into action. Check out this example below:

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

passport.use(new LocalStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function (err, user) {
      if (err) { return done(err); }
      if (!user) { return done(null, false); }
      if (!user.verifyPassword(password)) { return done(null, false); }
      return done(null, user);
    });
  }
));

router.post('/signup', function(req, res, next) {
  var username = req.body.username;
  var password = req.body.password;

  User.findOne({ username: username }, function(err, user) {

    if(err) { return next(err); }
    if(user) {
      req.flash('error', 'User already exists');
      return res.redirect('/signup');
    }

    var newUser = new User({
      username: username,
      password: password
    });
    newUser.save(next);

    passport.authenticate('local', { failureRedirect: '/signup' }),
     function(req, res) {
      res.redirect('/');
    });
  });
});

To learn more about the plugin, refer to the documentation here. Additionally, have a look at this sample app that demonstrates the authentication strategy here.

Answer №2

Consider implementing a callback function following the use of local instead of transmitting an object. You can utilize the following approach:

    router.post("/register", function(req, res){
      var newUser = new User({username: req.body.username});
      User.register(newUser, req.body.password, function(err, user){
          if(err){
              req.flash("error", err.message); //for instance, if the username is already taken or no username provided
              res.redirect("/register");
          } else {
            passport.authenticate("local")(req, res, function(){
                res.redirect("/");
              });
            }
        });
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Asynchronous handling of Three.JS geometry operations

I've been developing a browser-based game that retrieves terrain data from a remote server. My current implementation involves creating a PlaneGeometry with 100x100 segments based on the received data. However, when the terrain is added to the game ...

Is it possible for setInterval to trigger restarts in Apache?

Although I am not a professional coder, I have been teaching myself by experimenting with code snippets. I enjoy playing around with coding experiments as a way to gain experience. I attempted to load PHP into a div, which worked fine. However, when I tri ...

Displaying MySQL data on an HTML page with Node.js

Hello there, I recently started delving into Node.js for the first time. My current project involves fetching data from MySQL and displaying it on my HTML page. However, when I try to access my website at http://localhost:3000/index.html, I encounter an er ...

Observables waiting inside one another

I've encountered an issue where I need to return an observable and at times, within that observable, I require a value from another observable. To simplify my problem, let's consider the following code snippet: public dummyStream(): Observabl ...

What are the steps to fully eliminate a passport/express session?

I have attempted the following: req.session.destroy(); req.logout(); req.logOut(); After logging out, I verify by checking req.isAuthenticated() It returns false. However, when I navigate to /login again, it automatically logs me in with the same user ...

"Connection issue: SpringBoot application in Docker unable to reach Mongo database running in a

I created a Spring Boot Application using MongoDB on brew services. Initially, connecting to the database was as simple as updating the application.properties file in Spring Boot with: spring.data.mongodb.uri=mongodb://localhost:27017/db When I tried cha ...

Accessing location information using jQuery from Google's Geocoding API

Recently, I've been delving into the realm of Google Maps Geocoding and attempting to comprehend how to decipher the JSON data that it transmits back. This snippet showcases what Google's response looks like: { "results" : [ { ...

Is it better to have multiple event handlers in one process, or should they be distributed among

My Node.js API applications all follow a similar model. In each application, there is an HTTP server (express) that listens to requests and queues insert requests. There is also an event handler that monitors this queue, currently in mongodb but could be ...

An illustration of a basic subquery in MongoDB

Here is the given data: > db.parameters.find({}) { "_id" : ObjectId("56cac0cd0b5a1ffab1bd6c12"), "name" : "Speed", "groups" : [ " 123", "234" ] } > db.groups.find({}) { "_id" : "123", "name" : "Group01" } { "_id" : "234", "name" : "Group02" } { "_id ...

Increase the value of a nested field in MongoDB if it already exists, or create the nested field

In my document, I need to either increase the value of a nested field or create the entire nested field structure if it does not exist. Here is an example of the structure of my document: Doc1 { _id:ObjectId(), myField: { nested:{ x: 5, y: ...

Leveraging Three.js Raycaster for a seamless PDF download functionality

Is there a way to trigger a PDF download when clicking on a 3D object in a Three.js scene? Below is an example of how I have set up the Raycaster: var raycaster; var mouse = { x: 0, y: 0 }; init(); function init() { raycaster = new THREE.Raycaster() ...

nggrid encountered an error due to an unknown provider: GridServiceProvider, which is linked to GridService and HomeController

I followed the ng-grid tutorial found at After completing all the steps, I encountered the following error in the console: Error: [$injector:unpr] Unknown provider: gridServiceProvider <- gridService <- homeController http://errors.angularjs.org/1 ...

The call signatures for `node-fetch -- typeof import("[...]/node-fetch/index")'` are not properly defined

Originated from this source: https://github.com/node-fetch/node-fetch#json ... my personal code: const fetch = require('node-fetch'); async function doFetch() { const response = await fetch('https://api.github.com/users/github'); ...

What is the best way to differentiate between a JSON object and a Waterline model instance?

Note: I have posted an issue regarding this on the Waterline repo, but unfortunately, I have not received a simpler solution than my current workaround. Within my User model, along with default attributes such as createdDate and modifiedDate, I also have ...

Leverage the Power of AngularJS to Harness Local

I am currently developing an application using AngularJS. However, I have encountered an issue when trying to use localstorage. Here is my code snippet: var id = response.data[0].id; var email = response.data[0].email; localStorage.setItem('userId&ap ...

Dealing with validations in a personalized aid

Recently, I've been exploring CodeceptJs and have found it quite easy to work with. Currently, I'm utilizing it with NightmareJs for testing a gallery that retrieves data from an interface via JSONP to create a list of images enclosed in <div& ...

Storing information in a PHP database

I have created two pop-up divs on my website. Initially, the first div - div1, is displayed and it contains dropdown menus. Inside this div1, there is a button called Next which, when clicked, closes the first div and opens the second div; div2. Div2 consi ...

sliding to the right gets jammed

I am encountering a peculiar issue with Multi-page slide functionality. Whenever I attempt to switch pages, the new page gets stuck on the left before sliding out into position. Feel free to test this problem using my JSFiddle This is the JQuery code that ...

Having trouble displaying the Chrome context menu for a specific Chrome extension

I've read through several posts on this topic, but I'm still struggling to identify the issue with my implementation of the Chrome contextMenu API. I simply copied the code from a tutorial on Chrome APIs, and though there are no errors, the menu ...

Preventing access to websites on mobile devices: A step-by-step guide

Ensure an error page is shown when the website is accessed on a mobile device. I've attempted the following: @media only screen (max-device-width : 768px) { html,body { display: none; } } as well as: if( /Android|webOS|iPhone|iPad|iPod|BlackB ...