Authentication and Authorization in JS Answers


0:00
0:00

Node.js Authentication & Authorization Answers

Basic Node.js Authentication & Authorization Answers

#QuestionAnswerExamples
1What is Authentication?Verifying the identity of a user (Who are you?)Logging in with username/password, social login (Google, Facebook)
2What is Authorization?Determining what an authenticated user is allowed to do (What can you do?)Checking if a user has an 'admin' role to access an admin panel
3How do you securely store passwords?Hashing the password using a one-way cryptographic function (with salt)Using libraries like bcrypt or argon2
4What is a Salt?A unique random string added to a password before hashingPrevents rainbow table attacks
5What is a Session?A server-side object used to store information about a user's stateStoring user ID and login status on the server, often using session cookies
6What is a JWT (JSON Web Token)?A secure method for transmitting information between parties as a JSON objectContains claims (information) about the user, signed by the server
7How do you generate a JWT?Using a library like jsonwebtokenjwt.sign({ userId: 1, username: 'alice' }, 'secretKey');
8How do you verify a JWT?Using a library like jsonwebtoken with the same secret keyjwt.verify(token, 'secretKey', (err, decoded) => { ... });
9Where do you store a JWT on the client-side?Typically in localStorage, sessionStorage, or HTTP-only cookieslocalStorage.setItem('token', token);
10What is the difference between Session and JWT?Sessions are server-side state; JWT is stateless (token contains user info)Sessions require server storage; JWT can be passed directly in the request
11How do you implement authentication middleware?A function that checks for a valid token or session before allowing a requestapp.use('/protected', authenticateMiddleware, routeHandler);
12What is Passport.js?A popular authentication middleware for Node.jsSupports various strategies (local, JWT, OAuth, etc.)
13What is bcrypt?A library for hashing passwords (using salting and iteration)bcrypt.hash('password', 10, (err, hash) => { ... });
14Should you ever store plain-text passwords in a database?NO! Always hash them.Store the hashed value, not the original password.
15What is the importance of HTTPS for authentication?Encrypts communication between the client and serverProtects credentials (passwords, tokens) from eavesdropping

Intermediate Node.js Authentication & Authorization Answers

#QuestionAnswerExamples
1What is Role-Based Access Control (RBAC)?Assigning permissions to roles (e.g., 'admin', 'editor', 'viewer') and assigning users to rolesAn 'admin' role can delete users; an 'editor' role can edit posts.
2How do you implement RBAC in Node.js?Checking the user's role in middleware or route handlersif (req.user.role === 'admin') { /_ allow / } else { / deny _/ }
3What is Attribute-Based Access Control (ABAC)?Granting permissions based on attributes of the user, resource, and environmentOnly a user who owns a document can edit it.
4What is OAuth 2.0?An authorization framework that allows third-party applications to access user resources securely"Login with Google", "Login with Facebook" flows
5What is OpenID Connect (OIDC)?An identity layer built on top of OAuth 2.0, providing identity verificationAllows users to prove their identity using a third-party provider (e.g., Google)
6What is a Refresh Token?A long-lived token used to obtain new access tokens without requiring the user to log in againStored securely and often sent in HTTP-only cookies
7What is an Access Token?A short-lived token used to access protected resourcesTypically sent in the Authorization header (Authorization: Bearer <token>)
8How do you handle token expiration?Setting an exp claim in the JWT and using refresh tokens to get new access tokensjwt.sign({ ... }, 'secret', { expiresIn: '1h' }); Use refresh token when access token expires.
9What is the purpose of express-session?Middleware for managing HTTP sessions in Express applicationsapp.use(session({ secret: 'my-secret', resave: false, saveUninitialized: false }));
10What is CSRF (Cross-Site Request Forgery)?An attack that tricks a user into performing unwanted actions on a website where they are logged inUsing CSRF tokens (e.g., with csurf middleware)
11How do you prevent CSRF?Using CSRF tokens and validating them on the serverapp.use(csurf({ cookie: true })); (requires middleware)
12How do you prevent brute-force attacks?Limiting the number of login attempts per IP addressRate limiting, CAPTCHAs, account lockout after multiple failed attempts.
13What is the difference between password hashing and salting?Hashing is a one-way process; salting adds a unique random string before hashingSalting prevents rainbow table attacks and ensures identical passwords have different hashes.
14How do you store sensitive configuration (e.g., secret keys)?Using environment variables or secret management systems (e.g., HashiCorp Vault)Never hardcode secrets in your code.
15What is the concept of stateless authentication?Authentication where session state is not stored on a specific server instanceUsing JWTs, where the token contains all necessary user info.

Advanced Node.js Authentication & Authorization Answers

#QuestionAnswerExamples
1What is argon2?A modern, secure password hashing algorithm, often recommended for new projectsFaster than bcrypt, considered safer against modern cracking techniques.
2Explain the importance of secure API design.Using HTTPS, proper input validation, rate limiting, authentication/authorization for API endpointsProtecting sensitive data, preventing abuse, ensuring data integrity.
3What is multi-factor authentication (MFA)?Requiring users to provide two or more forms of verification (e.g., password + code from app)Using libraries like speakeasy or integrating with Google Authenticator/Authy.
4Explain user permissions.Specific actions that a user can perform (e.g., 'read_post', 'write_comment', 'delete_user')Checking permissions: if (req.user.can('delete_post')) { ... }
5What is a custom authentication strategy in Passport.js?Implementing your own authentication flow (e.g., local username/password, custom OAuth provider)passport.use(new LocalStrategy({ usernameField: 'email' }, function(email, password, done) { ... }));
6Explain the concept of "Authorization Code Grant" (OAuth 2.0).A standard flow for web applications to obtain access tokens securelyUser redirects to authorization server, grants permission, receives authorization code, app exchanges code for token.
7What is the purpose of httpOnly cookies?Cookies that can only be accessed by the server, not JavaScript (e.g., preventing client-side theft)httpOnly: true in cookie options, preventing XSS attacks from cookie access.
8How do you handle user roles/permissions with JWT?Include roles or permissions within the JWT payload (e.g., a roles claim)jwt.sign({ userId: 1, roles: ['read_post', 'write_comment'] }, 'secretKey');
9What is Content Security Policy (CSP)?A security header that specifies which resources the browser is allowed to load for a pageHelps prevent Cross-Site Scripting (XSS) attacks.
10How do you prevent Cross-Site Scripting (XSS) attacks?Sanitizing user input before rendering it, using CSP, escaping HTMLLibraries like DOMPurify or using template engines that auto-escape HTML.
11Explain the concept of authentication services.Separating authentication logic from the main application (e.g., using a dedicated service)Creating a separate module for user registration, login, token management.
12What is the purpose of express-session with trust-proxy?Allows session cookies to be marked as secure (only sent over HTTPS)app.use(session());
13How do you implement rate limiting in Express?Custom middleware or libraries to prevent excessive requests from a single IP/userUsing libraries like express-rate-limit or custom middleware to track request counts.
14What is the importance of logging security events?Recording security events (e.g., login attempts, permission changes) for monitoring and auditingLogging failed logins, password changes, unauthorized access attempts.
15How do you manage user sessions in a distributed environment?Using a dedicated session store (e.g., Redis, MongoDB) instead of in-memory storageexpress-session with connect-redis or connect-mongo.

Last updated on July 29, 2025

🔍 Explore More Topics

Discover related content that might interest you

TwoAnswers Logo

Providing innovative solutions and exceptional experiences. Building the future.

© 2025 TwoAnswers.com. All rights reserved.

Made with by the TwoAnswers.com team