I decided to use Passport.js in order to perform authentication for my web app and set up sessions. I also want to implement Google, Twitter, Facebook, etc login, and as I'm offering an API I want to offer OAuth too. That's why I choosed using Passport.
The problem is that it's not working for my hashed stored passwords. I use SHA1 for storing passwords when I receive a POST /signup. But when using Passport, which handles the POST /login it will always evaluate to false even I use the same algorithm which actually gives the same hashed password.
This is my hashing code:
var crypto = require('crypto')
var hashString = function(string) {
return crypto.createHash('sha256').update(string).digest('base64')
}
I use it for hashing passwords when a signup is required.
My Passport.js config looks exactly like this:
var passport = require('passport')
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var LocalStrategy = require('passport-local').Strategy;
var hashString = require('../passport/hashStrings')
app.use(session({ secret: 'somSecret' }));
app.use(passport.initialize());
app.use(passport.session());
var Schema = mongoose.Schema
var userCredential = new Schema({
mail: String,
password: String
}, {
collection: 'users'
})
var userCredentials = mongoose.model('users', userCredential)
app.use(session({
clear_interval: 900,
cookie: { maxAge: 2 * 60 * 60 * 1000 },
store: new MongoStore({
db : mongoose.connection.db
})
}));
passport.serializeUser(function(user, done) {
done(null, user);
})
passport.deserializeUser(function(user, done) {
done(null, user);
})
passport.use(new LocalStrategy(function(mail, password, done) {
process.nextTick(function() {
userCredentials.findOne({
'email': email,
}, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false);
}
if (user.password != hashString(password)) {
return done(null, false);
}
return done(null, user);
});
});
}))
So this line:
if (user.password != hashString(password)) {...
I actually try to compare the retrieved user's password (which is already hashed) with the one provided at the request which I hash then. I've already tested and no matter I try different valid stored user-password combinations, it's always evaluating false.
I even made a console.log(hashString(password)) and the function is returning the same stored hash in the DB.
What am I doing wrong? What's the correct way to do this?