How to handle unauthorized requests using nodejs / passport

According to the documentation , if I handle authentication requests like this, I could capture successful attempts.

app.post('/login', passport.authenticate('local'), function(req, res) { // If this function gets called, authentication was successful. // `req.user` contains the authenticated user. res.redirect('/users/' + req.user.username); }); 

But, as the documentation says,

By default, if authentication fails, Passport will respond with an unauthorized status of 401, and no additional route handlers will be called. If authentication succeeds, the next handler will start and the req.user property will be set for the authenticated user.

How can I process an authorization attempt without user intervention?

I know that I can process it using special middleware, but is there a better way?

+5
source share
1 answer

You should take a look at the Custom Callback section in your passport documents , which explains how to override the built-in authentication request processing behavior. You can write a custom callback that will serve as a server for the done function that you call from Strategy.

 app.get('/login', function(req, res, next) { /* look at the 2nd parameter to the below call */ passport.authenticate('local', function(err, user, info) { if (err) { return next(err); } if (!user) { return res.redirect('/login'); } req.logIn(user, function(err) { if (err) { return next(err); } return res.redirect('/users/' + user.username); }); })(req, res, next); }); 

Look at the second parameter for the passport.authenticate call, which will execute the function that you are calling from the local strategy.

See the done function called in the code below, which is determined by the local strategy for the passport. You can call the executed function with various available parameters, such as err , user , info , set from the strategy in accordance with the response to the API call or the db operation. these parameters will be processed by the function definition described above in the passport.authenticate call.

 passport.use(new LocalStrategy( function(username, password, done) { /* see done being invoked with different paramters according to different situations */ 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); }); } )); 
+10
source

Source: https://habr.com/ru/post/1204173/


All Articles