0
# Core Authentication
1
2
Main authentication functionality providing strategy management, middleware creation, and request processing. This is the primary interface for integrating Passport into Express/Connect applications.
3
4
## Capabilities
5
6
### Authenticator Class
7
8
The core class providing all authentication functionality. The default export is a singleton instance, but you can create new instances using the constructor.
9
10
```javascript { .api }
11
/**
12
* Create a new Authenticator instance
13
* @returns {Authenticator} New authenticator instance
14
*/
15
function Authenticator();
16
17
// Default singleton instance
18
const passport = require("passport");
19
// passport is an instance of Authenticator
20
21
// Create new instance
22
const { Authenticator } = require("passport");
23
const customPassport = new Authenticator();
24
```
25
26
### Strategy Registration
27
28
Register and manage authentication strategies that define how authentication is performed.
29
30
```javascript { .api }
31
/**
32
* Register a strategy for later use when authenticating requests
33
* @param {string} [name] - Name of the strategy (optional, uses strategy.name if not provided)
34
* @param {Strategy} strategy - Authentication strategy instance
35
* @returns {Authenticator} Returns this for chaining
36
*/
37
passport.use(name, strategy);
38
passport.use(strategy);
39
40
/**
41
* Deregister a previously registered strategy
42
* @param {string} name - Name of the strategy to remove
43
* @returns {Authenticator} Returns this for chaining
44
*/
45
passport.unuse(name);
46
```
47
48
**Usage Examples:**
49
50
```javascript
51
const LocalStrategy = require("passport-local").Strategy;
52
const GoogleStrategy = require("passport-google-oauth20").Strategy;
53
54
// Register strategy with default name
55
passport.use(new LocalStrategy(
56
(username, password, done) => {
57
// Verify credentials
58
User.authenticate(username, password, done);
59
}
60
));
61
62
// Register strategy with custom name
63
passport.use("admin-local", new LocalStrategy(
64
(username, password, done) => {
65
// Admin-specific authentication logic
66
Admin.authenticate(username, password, done);
67
}
68
));
69
70
// Register OAuth strategy
71
passport.use(new GoogleStrategy({
72
clientID: process.env.GOOGLE_CLIENT_ID,
73
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
74
callbackURL: "/auth/google/callback"
75
},
76
(accessToken, refreshToken, profile, done) => {
77
// Handle OAuth profile
78
User.findOrCreate({ googleId: profile.id }, done);
79
}
80
));
81
```
82
83
### Initialize Middleware
84
85
Create initialization middleware that prepares Passport for incoming requests.
86
87
```javascript { .api }
88
/**
89
* Create initialization middleware
90
* @param {Object} [options] - Configuration options
91
* @param {string} [options.userProperty='user'] - Property name for authenticated user on req
92
* @param {boolean} [options.compat=true] - Enable compatibility layer for older strategies
93
* @returns {Function} Express/Connect middleware function
94
*/
95
passport.initialize(options);
96
```
97
98
**Usage Examples:**
99
100
```javascript
101
const express = require("express");
102
const app = express();
103
104
// Basic initialization
105
app.use(passport.initialize());
106
107
// With custom user property
108
app.use(passport.initialize({
109
userProperty: "currentUser"
110
}));
111
112
// Disable compatibility layer
113
app.use(passport.initialize({
114
compat: false
115
}));
116
```
117
118
### Authentication Middleware
119
120
Create middleware that authenticates requests using specified strategies.
121
122
```javascript { .api }
123
/**
124
* Create authentication middleware
125
* @param {string|string[]|Strategy} strategy - Strategy name(s) or instance(s)
126
* @param {Object} [options] - Authentication options
127
* @param {boolean} [options.session=true] - Save login state in session
128
* @param {boolean} [options.keepSessionInfo=false] - Preserve session info during login
129
* @param {string} [options.successRedirect] - URL to redirect after success
130
* @param {string} [options.failureRedirect] - URL to redirect after failure
131
* @param {boolean|string|Object} [options.successFlash=false] - Flash success messages
132
* @param {boolean|string|Object} [options.failureFlash=false] - Flash failure messages
133
* @param {boolean|string} [options.successMessage=false] - Store success message in session
134
* @param {boolean|string} [options.failureMessage=false] - Store failure message in session
135
* @param {boolean} [options.failWithError=false] - Pass errors to next middleware
136
* @param {string} [options.assignProperty] - Assign user to custom request property
137
* @param {boolean} [options.authInfo=true] - Include auth info in request
138
* @param {string} [options.successReturnToOrRedirect] - Redirect to returnTo URL or specified URL
139
* @param {Function} [callback] - Custom callback function
140
* @returns {Function} Express/Connect middleware function
141
*/
142
passport.authenticate(strategy, options, callback);
143
```
144
145
**Usage Examples:**
146
147
```javascript
148
// Basic form authentication
149
app.post("/login",
150
passport.authenticate("local", {
151
successRedirect: "/dashboard",
152
failureRedirect: "/login",
153
failureFlash: true
154
})
155
);
156
157
// API authentication without sessions
158
app.get("/api/users",
159
passport.authenticate("bearer", { session: false }),
160
(req, res) => {
161
res.json(req.user);
162
}
163
);
164
165
// Custom callback handling
166
app.post("/login", (req, res, next) => {
167
passport.authenticate("local", (err, user, info) => {
168
if (err) return next(err);
169
if (!user) {
170
return res.status(401).json({ error: info.message });
171
}
172
req.logIn(user, (err) => {
173
if (err) return next(err);
174
return res.json({ user: user });
175
});
176
})(req, res, next);
177
});
178
179
// Multiple strategy fallback
180
app.get("/api/protected",
181
passport.authenticate(["bearer", "basic"], { session: false }),
182
(req, res) => {
183
res.json({ message: "Access granted" });
184
}
185
);
186
187
// OAuth flow
188
app.get("/auth/google",
189
passport.authenticate("google", { scope: ["profile", "email"] })
190
);
191
192
app.get("/auth/google/callback",
193
passport.authenticate("google", {
194
successRedirect: "/dashboard",
195
failureRedirect: "/login"
196
})
197
);
198
```
199
200
### Authorization Middleware
201
202
Create middleware for third-party service authorization while preserving existing authentication.
203
204
```javascript { .api }
205
/**
206
* Create third-party service authorization middleware
207
* @param {string|string[]|Strategy} strategy - Strategy name(s) or instance(s)
208
* @param {Object} [options] - Authorization options (same as authenticate)
209
* @param {Function} [callback] - Custom callback function
210
* @returns {Function} Express/Connect middleware function
211
*/
212
passport.authorize(strategy, options, callback);
213
```
214
215
**Usage Examples:**
216
217
```javascript
218
// Connect Twitter account to existing user
219
app.get("/connect/twitter",
220
passport.authorize("twitter", { failureRedirect: "/account" })
221
);
222
223
app.get("/connect/twitter/callback",
224
passport.authorize("twitter", { failureRedirect: "/account" }),
225
(req, res) => {
226
// req.account contains Twitter account info
227
// req.user contains existing logged-in user
228
req.user.twitter = req.account;
229
req.user.save(() => {
230
res.redirect("/account");
231
});
232
}
233
);
234
```
235
236
### Session Middleware
237
238
Create middleware for session-based authentication restoration.
239
240
```javascript { .api }
241
/**
242
* Restore login state from session
243
* @param {Object} [options] - Session options
244
* @param {boolean} [options.pauseStream=false] - Pause request stream during deserialization
245
* @returns {Function} Express/Connect middleware function
246
*/
247
passport.session(options);
248
```
249
250
**Usage Examples:**
251
252
```javascript
253
const express = require("express");
254
const session = require("express-session");
255
const app = express();
256
257
// Complete session setup
258
app.use(session({
259
secret: "keyboard cat",
260
resave: false,
261
saveUninitialized: false
262
}));
263
264
app.use(passport.initialize());
265
app.use(passport.session());
266
267
// With stream pausing for body parsing
268
app.use(passport.session({
269
pauseStream: true
270
}));
271
```
272
273
### Framework Integration
274
275
Adapt Passport to work with different web frameworks (defaults to Connect/Express).
276
277
```javascript { .api }
278
/**
279
* Adapt authenticator to work with specific framework
280
* @param {Object} fw - Framework adapter object
281
* @returns {Authenticator} Returns this for chaining
282
*/
283
passport.framework(fw);
284
```
285
286
**Usage Examples:**
287
288
```javascript
289
// Custom framework adapter
290
const customFramework = {
291
initialize: (passport, options) => {
292
// Return framework-specific initialize middleware
293
return (req, res, next) => {
294
// Framework-specific initialization logic
295
next();
296
};
297
},
298
authenticate: (passport, name, options, callback) => {
299
// Return framework-specific authenticate middleware
300
return (req, res, next) => {
301
// Framework-specific authentication logic
302
};
303
}
304
};
305
306
passport.framework(customFramework);
307
```
308
309
## Error Handling
310
311
Passport uses a specific error class for authentication failures:
312
313
```javascript { .api }
314
/**
315
* Authentication error class
316
* @param {string} message - Error message
317
* @param {number} [status=401] - HTTP status code
318
*/
319
class AuthenticationError extends Error {
320
constructor(message, status);
321
name: "AuthenticationError";
322
message: string;
323
status: number;
324
}
325
```
326
327
Authentication errors can be handled through the `failWithError` option or custom callbacks:
328
329
```javascript
330
// Handle errors in error middleware
331
app.post("/login",
332
passport.authenticate("local", { failWithError: true }),
333
(req, res) => {
334
res.redirect("/dashboard");
335
},
336
(err, req, res, next) => {
337
if (err.name === "AuthenticationError") {
338
res.status(err.status).json({ error: err.message });
339
} else {
340
next(err);
341
}
342
}
343
);
344
```