Search code examples
node.jsexpresspassport.jspassport-local

Bad request while using passport in express


While integrate passport to my code's login form. Everything is working fine until i call passport.authenticate in the request, 400 Bad Request was returned. What i am doing wrong?

Strategy

passport.use('local.login',new LocalStrategy({
    usernameField: 'Email',
    passwordField: 'Password',
},function (email,done) {
    Schema.Users.findOne({'Email': email},function (err,user) {
        if(err) {
            return done(err);
        }
        if(user==null) {
            return done(null,false,{ message: 'Incorrect username.' })
        }
        if(user.Password!==Password) {
            //console.log('Wrong password');
            return done(null,false,{ message: 'Wrong password' })
        }
        return done(null,user);
    })
}));

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

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

Inside login.js

router.post('/x',passport.authenticate('local.signup',{
    successRedirect: '/success',
    failureFlash: '/failure'
}));

app.js

let login = require('./login.js');
app.use('/login',login);

HTML

<form action="http://localhost:8080/login/x" method="post">
    <div class="row">
        <div class="col s6">
            <label for = "email"></label>
            <input id = "Email" type="email" placeholder="Email" name="Email">
        </div>
        <div class="col s6">
            <label for = "Password"></label>
            <input id = "Password" type="Password" placeholder="Password" name="Password">
        </div>
    </div>
    <button class="waves-effect waves-light btn" type="submit">Log In</button
</form>

Solution

  • Let's summarise it guys.

    First, make sure if you're using any json parser in you express middleware. Body-parser looks depricated, so hust make sure you have this line in your code: app.use(express.json()).

    Second, sometimes people get 400 from passport.authenticate because of credentials. So make sure your axios requests from frontend to backend has this {withCredentials: true} as a parameter.

    And finally, make sure to use "username" and "password" spelled exactly like this in your userSchema, in your frontend input names, and in your strategy options. I used passport-local-mongoose, and looks like there's no need to configure local strategy, cause it use "username" and "password" by default. Try any of this, 99% you'll be able to authenticate user and finally move on. Later, you'll find a way to specify "username" and "password" to be different, but for now I'm sure, your primary mission is to unstack)