Passport is an Express-compatible authentication middleware for Node.js. It provides a simple, unobtrusive way to authenticate requests through an extensible set of 'strategies' (plugins) for various authentication methods like username/password, OAuth, or OpenID. It focuses solely on authentication, allowing developers to make application-level decisions about database schemas and routing. The current stable version is 0.7.0, and it is actively maintained.
npm install passportVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to set up Passport with Express and a 'local' authentication strategy. It includes user serialization/deserialization for session management, a mock user database, and basic login/profile routes to show authentication in action. Users can access a protected profile route after logging in.
Install the appropriate `passport-strategy-name` package(s) and register them with `passport.use(new Strategy(...))`.
Install `express-session` and ensure `app.use(session(...))`, `app.use(passport.initialize())`, and `app.use(passport.session())` are called in your Express app middleware chain.
Define `passport.serializeUser((user, done) => { done(null, user.id); });` and `passport.deserializeUser((id, done) => { /* fetch user by id */ done(null, user); });`Ensure `passport.use(new MyStrategy({ name: 'my-strategy' }, ...))` is called, and then use `passport.authenticate('my-strategy', ...)`.Always call `done()` with the appropriate arguments. `done(null, false)` indicates failed login (e.g., bad credentials), `done(err)` for system errors, and `done(null, user)` for successful authentication.
Add `app.use(passport.initialize());` before any routes or other Passport middleware.
Implement `passport.serializeUser((user, done) => { done(null, user.id); });` (replace `user.id` with a unique identifier for your user).Implement `passport.deserializeUser((id, done) => { /* find user by id from your database */ done(null, user); });`Ensure `passport.use(new LocalStrategy(...))` (or the equivalent for your chosen strategy) is called after importing the strategy and before `passport.authenticate()` is used.
Ensure the user is properly authenticated, `passport.deserializeUser` is correctly implemented and fetching a user, and check `req.isAuthenticated()` before accessing `req.user`.
No dependency data recorded yet.