Passport local returns error 400 bad request with Angular

前端 未结 4 2223
庸人自扰
庸人自扰 2021-02-12 12:18

I am trying to integrate passport to my code\'s login form. Client side calling server side works as it should until i call passport.authenticate in the request, 400 Bad Request

相关标签:
4条回答
  • 2021-02-12 12:43

    In my case (Express 4.0), I wasn't using body-parser

    0 讨论(0)
  • 2021-02-12 12:44
    passport.use(new LocalStrategy(
        {
            usernameField: 'email',
            passwordField: 'password'
        },
        function (email, password, done) {
            db.collection('User').findOne({ email: email }, async function (err, user) {
                console.log('user requested password caught in passport', password);
                if (err) { return done(err); }
                if (!user) { return done(null, false); }
                const matchPassword = await comparePassword(password, user.password);
                if (!matchPassword) { return done(null, false); }
                return done(null, user);
            });
        }
    ));
    
    0 讨论(0)
  • 2021-02-12 12:46

    This error also comes from trying to access the HTML DOM elements without using body-parser

    body-parser is a module that let's you traverse the html document tree to read response especially in case of input fields

    Use -

    var parser = require('body-parser');
    var urlencodedParser = parser.urlencoded({extended : false});
    
    
        app.post("/authenticate", urlencodedParser, passport.authenticate('local'), function (request, response)
        {           
            response.redirect('/');                      
        });
    
    0 讨论(0)
  • 2021-02-12 12:49

    Bad Request was thrown by passport for missing access on username and password.

    It is checking body and URL query for fields username and password. If either is falsy the request is rejected with status 400.

    On creating your LocalStrategy you may pass set of options in additional argument to constructor choosing differently named fields using options usernameField and/or passwordField. In your particular case this would look like this:

    passport.use(new LocalStrategy(
        {usernameField:"user-email", passwordField:"user-password"},
        function(username, password, done) {
            return done(null, false, {message:'Unable to login'})
        }
    ));
    
    0 讨论(0)
提交回复
热议问题