passport. initialize() is a middle-ware that initialises Passport. Middlewares are functions that have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle.
In this route, passport. authenticate() is middleware which will authenticate the request. By default, when authentication succeeds, the req. user property is set to the authenticated user, a login session is established, and the next function in the stack is called.
Passport is a popular, modular authentication middleware for Node. js applications. With it, authentication can be easily integrated into any Node- and Express-based app.
Follow the example to avoid the out-of-order middleware hell that express makes it so easy to enter. Straight from the docs. Note how yours does not match this exactly.
var app = express();
app.use(require('serve-static')(__dirname + '/../../public'));
app.use(require('cookie-parser')());
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('express-session')({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
In my case (same error message) I've forgotten to add the passport initializations at all:
app.configure(function () {
...
app.use(passport.initialize());
app.use(passport.session());
});
UPDATE: Only working up to express version 3, version 4 does not support app.configure() anymore
In my case the error was because I was trying to promisify req.login
without binding this
to req
, so when the function was called it could not find passport
settings.
The solution is binding req.login.bind(req)
before passing it to promisify
if you are using Node v8.
What has helped me also was to put routes AFTER cookies config:
// init Cookies:
app.use(
cookieSession({
maxAge: 30 * 24 * 60 * 60 * 1000,
keys: [keys.cookieKey]
})
);
app.use(passport.initialize());
app.use(passport.session());
// init routes
const authRoutes = require("./routes/authRoutes")(app);
Peter Lyons answer helped me to solve it, but i solved it in abit different way.
app.use(
cookieSession({
maxAge: 30 * 24 * 60 * 60 * 1000,
keys: [keys.cookieKey],
}),
);
app.use(passport.initialize());
app.use(passport.session());
Have a look at my GitHub repo for the whole code and not only the code snippet here.
In my case (same error message), I was developing a custom strategy and I don't need to use a session. I just forgot to add session: false
in my route authenticate
middleware.
app.post('/api/public/auth/google-token',
passport.authenticate('google-token', {
session: false
}),
function (req: any, res) {
res.send("hello");
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With