Lecture Notes Of Class 14: Authentication
with Passport.js
Objective:
Learn how to implement authentication in Node.js using Passport.js.
Overview
In this class, we will
cover how to integrate authentication into a Node.js application using the
Passport.js library. Passport.js is a flexible and modular authentication
middleware for Node.js. It allows you to authenticate requests using various
strategies like local username/password authentication, OAuth, and more.
Lab Tasks:
1.
Install and configure Passport.js in
an Express app.
2.
Implement local authentication
(username and password).
1. What is Passport.js?
Passport.js is a Node.js
authentication middleware that helps authenticate users in web applications. It
supports various strategies for authentication (like username/password, Google
OAuth, Facebook, etc.) and works seamlessly with Express.js. Passport simplifies
authentication and manages sessions for you.
Some key points to
remember about Passport.js:
- Middleware:
Passport.js acts as middleware between your Express routes.
- Strategies:
Passport provides multiple authentication strategies.
- Modular:
You can use Passport for various authentication methods in one app (like
local, JWT, OAuth).
- Session
Management: Passport integrates with Express's
session middleware to keep the user logged in across requests.
2. Install and Configure
Passport.js
Step 1: Set up an Express
Application
Before starting with
Passport.js, ensure you have a basic Express app ready. If you don't have one,
create one by following these steps:
1.
Create a new project folder.
bash
CopyEdit
mkdir passport-example
cd passport-example
2.
Initialize a Node.js project.
bash
CopyEdit
npm init -y
3.
Install Express.
bash
CopyEdit
npm install express
4.
Create a basic server
(in a file called app.js):
javascript
CopyEdit
const express = require('express');
const app = express();
const PORT = process.env.PORT
|| 3000;
app.get('/', (req, res)
=> {
res.send('Welcome to Passport.js Example!');
});
app.listen(PORT, () =>
{
console.log(`Server is running on port ${PORT}`);
});
Step 2: Install
Passport.js and Other Dependencies
To use Passport.js for
local authentication, you need to install the following packages:
1.
Install Passport.js.
bash
CopyEdit
npm install passport
2.
Install Express Session
(to handle user sessions).
bash
CopyEdit
npm install
express-session
3.
Install Passport Local Strategy
(for username and password authentication).
bash
CopyEdit
npm install
passport-local
4.
Install bcryptjs
(for password hashing).
bash
CopyEdit
npm install bcryptjs
3. Configure Passport.js
for Local Authentication
Once you have installed
the necessary packages, follow these steps to configure Passport.js in your
Express app.
Step 1: Create Passport
Configuration File
Create a new file named passport-config.js
to set up Passport.js and the local strategy.
javascript
CopyEdit
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcryptjs');
// Mock user data for the
sake of simplicity
const users = [
{ id: 1, username: 'john', password: '$2a$10$tpYXb4yxZad5Vlf1vA2I5uqT/bthFfLS5DCIt2acm9P8lm31j0T7S'
} // password: 'password123'
];
// Function to find a
user by username
function findUserByUsername(username)
{
return users.find(user => user.username
=== username);
}
// Passport Local
Strategy
module.exports = function(passport)
{
passport.use(new LocalStrategy((username,
password, done) => {
const user = findUserByUsername(username);
if (!user) {
return done(null, false, { message: 'No
user with that username' });
}
// Compare hashed passwords using bcrypt
bcrypt.compare(password, user.password, (err,
isMatch) => {
if (err) throw err;
if (isMatch) {
return done(null, user);
} else {
return done(null, false, { message: 'Password
incorrect' });
}
});
}));
// Serialize user into session (stores user
in session)
passport.serializeUser((user, done) => {
done(null, user.id);
});
// Deserialize user from session (retrieves
user based on session id)
passport.deserializeUser((id, done) => {
const user = users.find(user => user.id
=== id);
done(null, user);
});
};
In this file:
- LocalStrategy
is used to authenticate users based on their username and password.
- bcrypt.compare
is used to compare the plain text password with the hashed password stored
in the "users" array.
Step 2: Set up Express
and Passport Middleware
Update your app.js to
configure the session and Passport.js middleware.
javascript
CopyEdit
const express = require('express');
const passport = require('passport');
const session = require('express-session');
const passportConfig = require('./passport-config');
// Import the passport config file
const app = express();
const PORT = process.env.PORT
|| 3000;
// Middleware
app.use(express.urlencoded({
extended: false })); // Parse form data
app.use(express.json()); //
Parse JSON data
// Set up session
middleware
app.use(session({
secret: 'secretKey', // This should be a
random string for security
resave: false,
saveUninitialized: true,
}));
// Initialize Passport.js
passportConfig(passport);
// Call passport config function
app.use(passport.initialize());
app.use(passport.session());
// Persist login sessions
// Routes for login
app.get('/', (req, res)
=> {
res.send('Welcome to Passport.js Example!');
});
app.get('/login', (req,
res) => {
res.send('<form method="POST"
action="/login"><input type="text"
name="username" placeholder="Username"><input
type="password" name="password"
placeholder="Password"><button
type="submit">Login</button></form>');
});
// Handle login POST
request
app.post('/login',
passport.authenticate('local', {
successRedirect: '/dashboard',
failureRedirect: '/login',
failureFlash: false,
}));
// Dashboard route (for
authenticated users)
app.get('/dashboard', (req,
res) => {
if (!req.isAuthenticated()) {
return res.redirect('/login');
}
res.send(`Hello ${req.user.username}, welcome
to your dashboard!`);
});
// Start the server
app.listen(PORT, () =>
{
console.log(`Server is running on port ${PORT}`);
});
In the code above:
- The
/login route renders a simple login form.
- The
/login POST route authenticates the user using Passport's local strategy.
- If
authentication is successful, the user is redirected to the /dashboard.
- If
authentication fails, the user is redirected back to the /login page.
4. Test the Application
1.
Start your server by running:
bash
CopyEdit
node app.js
2.
Open your browser and go to http://localhost:3000/login.
Try logging in using the username john and the password password123.
3.
If successful, you should be redirected to
the /dashboard, where you can see a welcome message.
4.
If you enter incorrect credentials, you'll
be redirected back to the login page.
5. Conclusion
In this class, we learned
how to:
1.
Install and configure Passport.js in an
Express.js application.
2.
Implement local authentication using
Passport.js with username and password.
3.
Set up session management to persist user
login sessions across requests.
This basic authentication
mechanism is the foundation for building more complex authentication systems
with Passport.js, such as adding user registration, handling password reset, or
integrating with third-party authentication providers (like Google or Facebook).
Next Steps:
- Explore
other authentication strategies available in Passport.js, such as JWT
(JSON Web Tokens) or OAuth.
- Learn
how to hash and securely store user passwords using libraries like bcrypt.
4o mini
You said:
Write 10 assignments with
solution and explanation in detail on above concept
ChatGPT said:
ChatGPT
Assignments on
Authentication with Passport.js
Below are 10 assignments
with solutions and detailed explanations on implementing authentication using
Passport.js. These assignments range from basic to intermediate concepts and
allow students to understand the flow of authentication, session management,
and error handling.
Assignment 1: Set Up an
Express Application
Task:
Create a simple Express application with the necessary setup to install
Passport.js.
Solution:
bash
CopyEdit
mkdir passport-setup
cd passport-setup
npm init -y
npm install express
passport express-session passport-local
Explanation:
- We
start by creating a new project folder and initializing a Node.js project.
- After
initializing, we install the required dependencies: Express (web
framework), Passport.js (authentication middleware), and express-session
(for session management).
Assignment 2:
Implementing Basic Authentication Routes
Task:
Implement basic login routes in Express using Passport.js.
Solution:
javascript
CopyEdit
// app.js
const express = require('express');
const passport = require('passport');
const session = require('express-session');
const LocalStrategy = require('passport-local').Strategy;
const app = express();
app.use(express.urlencoded({
extended: false }));
app.use(express.json());
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: true
}));
passport.use(new LocalStrategy((username,
password, done) => {
if (username === 'user' && password
=== 'password') {
return done(null, { username });
} else {
return done(null, false, { message: 'Incorrect
credentials' });
}
}));
passport.serializeUser((user,
done) => {
done(null, user.username);
});
passport.deserializeUser((username,
done) => {
done(null, { username });
});
app.use(passport.initialize());
app.use(passport.session());
app.get('/login', (req,
res) => {
res.send('<form method="POST"
action="/login"><input name="username" /><input
name="password" type="password" /><button
type="submit">Login</button></form>');
});
app.post('/login',
passport.authenticate('local', {
successRedirect: '/dashboard',
failureRedirect: '/login'
}));
app.get('/dashboard', (req,
res) => {
if (!req.isAuthenticated()) {
return res.redirect('/login');
}
res.send(`Welcome, ${req.user.username}!`);
});
app.listen(3000, () =>
{
console.log('Server running on port 3000');
});
Explanation:
- This
assignment creates a login route where users can submit their username and
password.
- If
the credentials are correct (username: user, password: password), the user
is redirected to /dashboard. If incorrect, they are sent back to the login
page.
Assignment 3: Add Error
Handling for Authentication
Task:
Add error handling to display a message if authentication fails.
Solution:
javascript
CopyEdit
app.post('/login',
passport.authenticate('local', {
successRedirect: '/dashboard',
failureRedirect: '/login',
failureFlash: true
}));
// Handle the flash
message in the login route
app.get('/login', (req,
res) => {
let message = req.flash('error');
res.send(`<form method="POST"
action="/login">${message ? `<p>${message}</p>` : ''}<input
name="username" /><input name="password"
type="password" /><button
type="submit">Login</button></form>`);
});
Explanation:
- The
failureFlash option is enabled to show error messages if authentication
fails.
- The
error message is displayed in the login form if the user enters incorrect
credentials.
Assignment 4: Secure the
Dashboard Route
Task:
Make sure the dashboard page is accessible only to authenticated users.
Solution:
javascript
CopyEdit
app.get('/dashboard', (req,
res) => {
if (!req.isAuthenticated()) {
return res.redirect('/login');
}
res.send(`Welcome, ${req.user.username}!`);
});
Explanation:
- The
/dashboard route checks if the user is authenticated using req.isAuthenticated().
- If
not authenticated, it redirects to the login page. Otherwise, it shows the
welcome message.
Assignment 5: Create a
Mock User Database
Task:
Create a mock user database in the application to verify the login credentials.
Solution:
javascript
CopyEdit
const users = [{ id: 1, username:
'user', password: 'password' }];
passport.use(new LocalStrategy((username,
password, done) => {
const user = users.find(u => u.username
=== username);
if (!user) return done(null, false, { message:
'User not found' });
if (user.password === password) {
return done(null, user);
} else {
return done(null, false, { message: 'Incorrect
password' });
}
}));
Explanation:
- The
users array is used to mock a user database.
- The
LocalStrategy checks if the username exists in the array and if the
password matches.
Assignment 6: Hashing
Passwords with bcrypt
Task:
Use bcrypt to hash passwords before saving them to the database (mocked users
in this case).
Solution:
javascript
CopyEdit
const bcrypt = require('bcryptjs');
const users = [
{ id: 1, username: 'user', password: bcrypt.hashSync('password',
10) }
];
passport.use(new LocalStrategy((username,
password, done) => {
const user = users.find(u => u.username
=== username);
if (!user) return done(null, false, { message:
'User not found' });
bcrypt.compare(password, user.password, (err,
isMatch) => {
if (err) return done(err);
if (isMatch) {
return done(null, user);
} else {
return
done(null, false, { message: 'Incorrect password' });
}
});
}));
Explanation:
- Passwords
are hashed using bcrypt.hashSync(), and then compared using bcrypt.compare()
in the authentication process.
- This
ensures that passwords are stored securely (hashed) and compared securely
(hashed comparison).
Assignment 7: Implement
Logout Functionality
Task:
Implement a route for logging out the user.
Solution:
javascript
CopyEdit
app.get('/logout', (req,
res) => {
req.logout((err) => {
if (err) return next(err);
res.redirect('/');
});
});
Explanation:
- The
/logout route uses req.logout() to end the session and redirect the user
to the home page or login page.
Assignment 8: Add User
Registration Functionality
Task:
Create a registration route where users can sign up by providing a username and
password.
Solution:
javascript
CopyEdit
app.post('/register', (req,
res) => {
const { username, password } = req.body;
// Hash the password before saving
const hashedPassword = bcrypt.hashSync(password,
10);
users.push({ id: users.length + 1, username, password:
hashedPassword });
res.redirect('/login');
});
Explanation:
- The
/register route allows users to register by sending a username and
password.
- Passwords
are hashed with bcrypt before saving the user.
Assignment 9: Create a
User Profile Page
Task:
Create a user profile page that shows the logged-in user's information.
Solution:
javascript
CopyEdit
app.get('/profile', (req,
res) => {
if (!req.isAuthenticated()) {
return res.redirect('/login');
}
res.send(`Profile of ${req.user.username}:
<br>Username: ${req.user.username}`);
});
Explanation:
- The
/profile route checks if the user is authenticated.
- If
authenticated, it displays the user's profile, including their username.
Assignment 10: Handle
Session Expiry and Redirect to Login
Task:
Set an expiry time for the session and redirect the user to the login page if
the session expires.
Solution:
javascript
CopyEdit
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 } // Session expires
after 1 minute
}));
app.get('/dashboard', (req,
res) => {
if (!req.isAuthenticated()) {
return res.redirect('/login');
}
res.send(`Welcome, ${req.user.username}!`);
});
Explanation:
- The
cookie.maxAge option in the session middleware sets the session expiry
time (in milliseconds).
- After
the session expires, the user will be redirected to the login page.
These assignments allow
students to learn, implement, and practice core concepts of user authentication
in Node.js using Passport.js, providing them with hands-on experience in
securing applications.
4o mini
You said:
write 50 MCQs for the
concept above with explanation
ChatGPT said:
ChatGPT
Here are 50
multiple-choice questions (MCQs) related to implementing authentication with
Passport.js in Node.js, along with explanations for the answers:
1. What is Passport.js
used for in a Node.js application?
a) Database management
b) Authentication middleware
c) Front-end routing
d) Session management
Answer:
b) Authentication middleware
Explanation: Passport.js is a middleware used to handle user
authentication in Node.js applications.
2. Which of the following
strategies does Passport.js support out of the box?
a) Local strategy
b) JWT strategy
c) OAuth2 strategy
d) All of the above
Answer:
d) All of the above
Explanation: Passport.js supports various authentication strategies
including Local, JWT, and OAuth2 out of the box.
3. How do you install
Passport.js in a Node.js application?
a) npm install passport
b) npm install passport-auth
c) npm install express-passport
d) npm install passport-local
Answer:
a) npm install passport
Explanation: The correct command to install Passport.js is npm install
passport.
4. What is the purpose of
passport.serializeUser()?
a) To initialize
Passport.js
b) To store user data in the session
c) To encrypt the password
d) To store session data in the database
Answer:
b) To store user data in the session
Explanation: passport.serializeUser() is used to store user data in the
session after successful authentication.
5. What does the passport.deserializeUser()
function do?
a) Encrypts the user data
b) Retrieves the user data from the session
c) Authenticates the user
d) Logs out the user
Answer:
b) Retrieves the user data from the session
Explanation: passport.deserializeUser() is used to retrieve the user
data from the session on subsequent requests.
6. Which module is
commonly used with Passport.js to manage sessions?
a) express-session
b) jsonwebtoken
c) cookie-parser
d) express-authorization
Answer:
a) express-session
Explanation: Passport.js relies on express-session to handle sessions in
a Node.js application.
7. What is the purpose of
passport.authenticate('local') in an Express route?
a) To log in the user
b) To initialize Passport.js
c) To check if the user is authenticated
d) To register a new user
Answer:
a) To log in the user
Explanation: passport.authenticate('local') is used to authenticate a
user using the local strategy (username and password).
8. Which strategy would
you use with Passport.js to authenticate users using only a username and
password?
a) OAuth
b) Local
c) JWT
d) Google
Answer:
b) Local
Explanation: The Local strategy is used for username and password
authentication.
9. What method would you
use to hash passwords before storing them in the database?
a) bcrypt.hashSync()
b) crypto.encrypt()
c) passport.hash()
d) passport.encrypt()
Answer:
a) bcrypt.hashSync()
Explanation: bcrypt.hashSync() is used to hash passwords before storing
them securely in the database.
10. What does the req.isAuthenticated()
method return?
a) True if the user is
authenticated
b) False if the user is authenticated
c) The user’s profile
d) The session data
Answer:
a) True if the user is authenticated
Explanation: req.isAuthenticated() returns true if the user is
authenticated and false otherwise.
11. What does passport.authenticate('local',
{ successRedirect: '/dashboard' }) do?
a) Redirects the user to
the login page
b) Redirects the user to the dashboard on successful login
c) Logs the user out
d) Authenticates the user using the JWT strategy
Answer:
b) Redirects the user to the dashboard on successful login
Explanation: This line authenticates the user and redirects them to the /dashboard
route if successful.
12. Which package is
required to use bcrypt for hashing passwords?
a) bcryptjs
b) bcrypt-nodejs
c) password-hash
d) express-bcrypt
Answer:
a) bcryptjs
Explanation: bcryptjs is the most commonly used package for hashing
passwords in Node.js.
13. How can you log the
user out using Passport.js?
a) req.logout()
b) passport.logout()
c) req.endSession()
d) passport.logoutUser()
Answer:
a) req.logout()
Explanation: req.logout() is the method used to log the user out in a
Passport.js application.
14. Which middleware is
required to handle session management with Passport.js?
a) express-session
b) cookie-parser
c) session-manager
d) passport-session
Answer:
a) express-session
Explanation: express-session is the middleware that handles session
management, which is required to use Passport.js for authentication.
15. How do you store
user-specific data in the session?
a) Using passport.serializeUser()
b) Using passport.deserializeUser()
c) Using session.storeData()
d) Using session.set()
Answer:
a) Using passport.serializeUser()
Explanation: passport.serializeUser() is used to store user-specific
data in the session after successful authentication.
16. What is the role of passport.deserializeUser()
in maintaining the session?
a) It serializes the user
data
b) It retrieves the user data from the session
c) It checks if the user is authenticated
d) It stores the user data in the session
Answer:
b) It retrieves the user data from the session
Explanation: passport.deserializeUser() is responsible for retrieving
user data from the session.
17. What is a flash
message in the context of Passport.js?
a) A message that appears
after authentication failure
b) A session cookie
c) A success message after registration
d) A password reset token
Answer:
a) A message that appears after authentication failure
Explanation: Flash messages are used to display error or success
messages to the user after an authentication attempt.
18. Which of the
following is a common mistake when setting up Passport.js in an Express
application?
a) Forgetting to use express-session
middleware
b) Forgetting to call passport.initialize()
c) Using the wrong hashing algorithm
d) All of the above
Answer:
d) All of the above
Explanation: All of these are common mistakes when setting up
Passport.js in a Node.js application.
19. How can you make sure
that the user is redirected to the login page if they are not authenticated?
a) Use req.isAuthenticated()
to check authentication
b) Use passport.authenticate()
c) Use express-session
d) Use cookie-parser
Answer:
a) Use req.isAuthenticated() to check authentication
Explanation: req.isAuthenticated() can be used to check if the user is
authenticated, and if not, redirect them to the login page.
20. Which of the
following is NOT a Passport.js authentication strategy?
a) JWT
b) Local
c) OAuth2
d) BasicAuth
Answer:
d) BasicAuth
Explanation: BasicAuth is not a built-in strategy for Passport.js. It
uses strategies like Local, OAuth2, and JWT.
21. In which of the
following scenarios would you use passport.authenticate('local')?
a) Logging in with Google
b) Logging in with Facebook
c) Authenticating with username and password
d) Authenticating with JWT tokens
Answer:
c) Authenticating with username and password
Explanation: passport.authenticate('local') is used for username and
password authentication.
22. What does bcrypt.compare()
do?
a) Hashes the password
b) Compares a plain password to a hashed password
c) Encrypts the password
d) Validates the user's session
Answer:
b) Compares a plain password to a hashed password
Explanation: bcrypt.compare() is used to compare a plain password with a
hashed password stored in the database.
23. What is the failureRedirect
option used for in passport.authenticate()?
a) Redirects the user to
a different page if authentication fails
b) Redirects the user to the login page if authentication succeeds
c) Redirects the user to a success page
d) Redirects the user to the dashboard
Answer:
a) Redirects the user to a different page if authentication fails
Explanation: The failureRedirect option specifies the URL to which the
user is redirected if authentication fails.
24. Which of the
following is a valid session configuration in express-session?
a) cookie.maxAge =
3600000
b) session.maxAge = 3600000
c) cookie.age = 3600000
d) express.session.age = 3600000
Answer:
a) cookie.maxAge = 3600000
Explanation: cookie.maxAge is used to define the expiration time for the
session cookie in milliseconds.
25. What is the purpose
of passport-jwt strategy?
a) To authenticate users
using a JSON Web Token
b) To authenticate users with Google
c) To validate user email addresses
d) To hash passwords
Answer:
a) To authenticate users using a JSON Web Token
Explanation: passport-jwt strategy is used to authenticate users using
JSON Web Tokens (JWT).
26. How do you
authenticate a user in an Express route after using Passport.js?
a) passport.authenticate('local')
b) passport.authenticate('jwt')
c) passport.login()
d) passport.validate()
Answer:
a) passport.authenticate('local')
Explanation: passport.authenticate('local') is used to authenticate a
user using the local strategy.
27. How do you protect a
route so that only authenticated users can access it?
a) By using req.isAuthenticated()
b) By using passport.authenticate()
c) By using passport.session()
d) By using express-session
Answer:
a) By using req.isAuthenticated()
Explanation: req.isAuthenticated() checks if the user is authenticated
before allowing access to the route.
28. How do you handle
errors during authentication in Passport.js?
a) By using try-catch
blocks
b) By using passport.authenticate() with failureFlash option
c) By using express-error-handler
d) By using error.stack
Answer:
b) By using passport.authenticate() with failureFlash option
Explanation: You can handle errors during authentication by using the failureFlash
option in passport.authenticate() to show error messages.
29. Which method would
you use to validate a user’s credentials in Passport.js?
a) LocalStrategy
b) passport.authenticate()
c) passport.validateUser()
d) passport.checkCredentials()
Answer:
a) LocalStrategy
Explanation: LocalStrategy is used to define how Passport.js validates
the user’s credentials.
30. What type of data is
typically stored in the session during Passport.js authentication?
a) The user’s email
address
b) The user’s hashed password
c) The user’s ID or minimal identifying data
d) The user’s profile picture
Answer:
c) The user’s ID or minimal identifying data
Explanation: Passport.js typically stores minimal identifying data, such
as the user’s ID, in the session.
31. How can you add
Google authentication to your Passport.js setup?
a) By using passport-google-oauth
b) By using passport-google-auth
c) By using passport-oauth2
d) By using passport-local-google
Answer:
a) By using passport-google-oauth
Explanation: passport-google-oauth is used to set up Google OAuth
authentication in a Passport.js application.
32. What would you use to
implement JWT-based authentication in Passport.js?
a) passport-jwt
b) passport-bearer
c) passport-token
d) passport-json
Answer:
a) passport-jwt
Explanation: passport-jwt strategy is used to authenticate users with
JSON Web Tokens (JWT).
33. Which of the
following is a correct way to redirect a user after successful login?
a) res.redirect('/profile')
b) passport.redirect('/profile')
c) passport.authenticate('local')
d) `res.sendRedirect('/profile')
Answer:
a) res.redirect('/profile')
Explanation: You use res.redirect() to send the user to a different
route after successful login.
34. What strategy does
Passport.js use to authenticate a user with Facebook?
a) passport-facebook
b) passport-oauth
c) passport-facebook-oauth
d) passport-oauth2
Answer:
a) passport-facebook
Explanation: The passport-facebook strategy is used to authenticate
users with Facebook.
35. How can you validate
a user’s email during registration?
a) By using Passport.js
built-in methods
b) By using a custom validation function
c) By using express-validator
d) By using mongoose-validator
Answer:
b) By using a custom validation function
Explanation: Email validation is typically handled by writing custom
validation logic or using libraries like express-validator.
36. What is the main
advantage of using Passport.js?
a) Simplifies front-end
routing
b) Handles multiple authentication strategies
c) Generates session cookies
d) Manages databases efficiently
Answer:
b) Handles multiple authentication strategies
Explanation: Passport.js supports a wide range of authentication
strategies, making it flexible and easy to implement various methods of
authentication.
37. What is the role of
the successRedirect option in Passport.js authentication?
a) It redirects the user
after successful authentication
b) It redirects the user if authentication fails
c) It redirects to the login page
d) It redirects the user to a different website
Answer:
a) It redirects the user after successful authentication
Explanation: The successRedirect option is used to specify the URL to
which the user is redirected after successful authentication.
38. How can you handle
multiple strategies in Passport.js?
a) By chaining passport.authenticate()
b) By using passport.use() for each strategy
c) By creating separate middleware for each strategy
d) By using passport.redirect()
Answer:
b) By using passport.use() for each strategy
Explanation: You use passport.use() to configure multiple authentication
strategies in Passport.js.
39. Which method do you
use to set up Passport.js in your Express application?
a) passport.initialize()
b) passport.configure()
c) passport.start()
d) passport.setup()
Answer:
a) passport.initialize()
Explanation: You need to call passport.initialize() to initialize
Passport.js in your Express app.
40. What happens if the
user is authenticated successfully using Passport.js?
a) A session is created
for the user
b) The user's credentials are encrypted
c) A JWT token is generated
d) The user is logged out
Answer:
a) A session is created for the user
Explanation: If authentication is successful, Passport.js creates a
session for the user to persist their login state.
41. Which of the
following methods helps check if a user is logged in or not?
a) passport.isAuthenticated()
b) req.isAuthenticated()
c) req.checkAuth()
d) passport.check()
Answer:
b) req.isAuthenticated()
Explanation: req.isAuthenticated() is used to check if a user is
authenticated.
42. How do you specify
which data should be saved in the session?
a) passport.serializeUser()
b) passport.deserializeUser()
c) passport.saveSession()
d) passport.storeData()
Answer:
a) passport.serializeUser()
Explanation: passport.serializeUser() is used to determine which data
should be saved in the session.
43. Which of the
following is a key feature of Passport.js?
a) It handles user roles
b) It only supports password-based authentication
c) It supports multiple authentication methods
d) It automatically validates form inputs
Answer:
c) It supports multiple authentication methods
Explanation: One of the key features of Passport.js is that it supports
multiple authentication methods, such as local login, social login, and JWT.
44. What happens if the
user provides incorrect login credentials?
a) The session expires
b) An error is thrown
c) The user is redirected to a failure page
d) The application crashes
Answer:
c) The user is redirected to a failure page
Explanation: If the credentials are incorrect, Passport.js redirects the
user to a failure page (using failureRedirect).
45. How do you protect
routes from unauthenticated access?
a) By using middleware
like isLoggedIn()
b) By using passport.authenticate()
c) By using express-session
d) By using passport-check()
Answer:
a) By using middleware like isLoggedIn()
Explanation: You can create a middleware function, like isLoggedIn(), to
ensure that only authenticated users can access protected routes.
46. What is the default
session cookie expiration time in Passport.js?
a) 1 hour
b) 24 hours
c) 1 week
d) No expiration time
Answer:
a) 1 hour
Explanation: By default, Passport.js uses a session cookie that expires
after 1 hour.
47. What does the failureRedirect
option do in Passport.js?
a) Redirects to a failure
route when authentication fails
b) Redirects to a success route
c) Logs the user out
d) Shows an error message
Answer:
a) Redirects to a failure route when authentication fails
Explanation: The failureRedirect option is used to specify a URL to
which the user is redirected if authentication fails.
48. What type of storage
is typically used for session data in Passport.js?
a) Local storage
b) Session storage
c) In-memory storage
d) Cookie storage
Answer:
c) In-memory storage
Explanation: By default, Passport.js uses in-memory storage for session
data, but you can configure other stores like databases.
49. How do you configure
a custom authentication strategy in Passport.js?
a) By using passport.createStrategy()
b) By defining your own strategy
c) By calling passport.use() with custom logic
d) By using passport.custom()
Answer:
b) By defining your own strategy
Explanation: You can create a custom authentication strategy by defining
your own strategy and using passport.use() to register it.
50. How do you log out a
user in Passport.js?
a) passport.logout()
b) passport.logoutUser()
c) req.logout()
d) req.session.destroy()
Answer:
c) req.logout()
Explanation: To log out a user, you use req.logout(), which removes the
user's session from the application.

No comments:
Post a Comment