Search code examples
javascriptangularjsnode.jspassport.jscryptojs

PassportJS - Getting payload data before it is passed to passport.authenticate as request parameter


There is a passport.js implementation which is being used for LDAP-auth which works. Now the next step is to encrypt the password on the client-side using Crypto-js as follows:

Client-side angular-js controller

$scope.authenticate = function () {      
  var auth = new login();
  auth.username = $scope.username;
  auth.password = CryptoJS.AES.encrypt($scope.password); //// HERE  

  auth.$save(function (response){
    console.log(response);
  },function(err){
    console.log(err);
  });
}

Server-side service

.....
.....
app.post('/login', passport.authenticate('ldapauth'), (req, res) => {

    console.log("req.user: ",req.user);
    req.session.username = req.user[ldap.username];
    req.session.userModel = req.user;
    res.status(200).send({"success": 'success'});
});
.....

On the server-side service before calling passport.authenticate with the request 'req' the aes encrypted password needs to be decrypted. How can that be implemented here? (The question is not about encryption but how to get data before it gets passed to passport.authenticate as request)


Solution

  • @Abhijay Ghildyal I don't think they understood your question. It is indeed possible to intercept the request before it gets passed to passport.authenticate(). What you'd want to do is to add this passage of code to your express.js or whichever file you did your express server implementation in. Also I am decrypting the request.body here instead of req.user since at that point of time the user is not yet logged in, however if it's different in your case then that's fine you can decrypt req.user the same way. (The variable app here is the name of your server i.e var app = express();)

    app.use(function(req, res, next) {
        if(req.url === '/login'){
            //CryptoJS.AES.decrypt() is Assumed to be the decrypter function here.
            req.body = CryptoJS.AES.decrypt(req.body);
            console.log(req.body); //To view decrypted body
        }
        next();
    });
    

    That is it. This middleware function will be reached first before the passport.authenticate() function. Just make sure if you're applying this to req.body you add these lines of codes first, after importing the bodyParser (bodyParser = require('body-parser');) before the passage above.

    app.use(bodyParser.urlencoded({
        extended: true
    }));
    app.use(bodyParser.json());