Authentication and Authorization in JS Answers
0:000:00
Node.js Authentication & Authorization Answers
Basic Node.js Authentication & Authorization Answers
# | Question | Answer | Examples |
---|---|---|---|
1 | What is Authentication? | Verifying the identity of a user (Who are you?) | Logging in with username/password, social login (Google, Facebook) |
2 | What 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 |
3 | How do you securely store passwords? | Hashing the password using a one-way cryptographic function (with salt) | Using libraries like bcrypt or argon2 |
4 | What is a Salt? | A unique random string added to a password before hashing | Prevents rainbow table attacks |
5 | What is a Session? | A server-side object used to store information about a user's state | Storing user ID and login status on the server, often using session cookies |
6 | What is a JWT (JSON Web Token)? | A secure method for transmitting information between parties as a JSON object | Contains claims (information) about the user, signed by the server |
7 | How do you generate a JWT? | Using a library like jsonwebtoken | jwt.sign({ userId: 1, username: 'alice' }, 'secretKey'); |
8 | How do you verify a JWT? | Using a library like jsonwebtoken with the same secret key | jwt.verify(token, 'secretKey', (err, decoded) => { ... }); |
9 | Where do you store a JWT on the client-side? | Typically in localStorage, sessionStorage, or HTTP-only cookies | localStorage.setItem('token', token); |
10 | What 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 |
11 | How do you implement authentication middleware? | A function that checks for a valid token or session before allowing a request | app.use('/protected', authenticateMiddleware, routeHandler); |
12 | What is Passport.js? | A popular authentication middleware for Node.js | Supports various strategies (local, JWT, OAuth, etc.) |
13 | What is bcrypt? | A library for hashing passwords (using salting and iteration) | bcrypt.hash('password', 10, (err, hash) => { ... }); |
14 | Should you ever store plain-text passwords in a database? | NO! Always hash them. | Store the hashed value, not the original password. |
15 | What is the importance of HTTPS for authentication? | Encrypts communication between the client and server | Protects credentials (passwords, tokens) from eavesdropping |
Intermediate Node.js Authentication & Authorization Answers
# | Question | Answer | Examples |
---|---|---|---|
1 | What is Role-Based Access Control (RBAC)? | Assigning permissions to roles (e.g., 'admin', 'editor', 'viewer') and assigning users to roles | An 'admin' role can delete users; an 'editor' role can edit posts. |
2 | How do you implement RBAC in Node.js? | Checking the user's role in middleware or route handlers | if (req.user.role === 'admin') { /_ allow / } else { / deny _/ } |
3 | What is Attribute-Based Access Control (ABAC)? | Granting permissions based on attributes of the user, resource, and environment | Only a user who owns a document can edit it. |
4 | What is OAuth 2.0? | An authorization framework that allows third-party applications to access user resources securely | "Login with Google", "Login with Facebook" flows |
5 | What is OpenID Connect (OIDC)? | An identity layer built on top of OAuth 2.0, providing identity verification | Allows users to prove their identity using a third-party provider (e.g., Google) |
6 | What is a Refresh Token? | A long-lived token used to obtain new access tokens without requiring the user to log in again | Stored securely and often sent in HTTP-only cookies |
7 | What is an Access Token? | A short-lived token used to access protected resources | Typically sent in the Authorization header (Authorization: Bearer <token> ) |
8 | How do you handle token expiration? | Setting an exp claim in the JWT and using refresh tokens to get new access tokens | jwt.sign({ ... }, 'secret', { expiresIn: '1h' }); Use refresh token when access token expires. |
9 | What is the purpose of express-session? | Middleware for managing HTTP sessions in Express applications | app.use(session({ secret: 'my-secret', resave: false, saveUninitialized: false })); |
10 | What is CSRF (Cross-Site Request Forgery)? | An attack that tricks a user into performing unwanted actions on a website where they are logged in | Using CSRF tokens (e.g., with csurf middleware) |
11 | How do you prevent CSRF? | Using CSRF tokens and validating them on the server | app.use(csurf({ cookie: true })); (requires middleware) |
12 | How do you prevent brute-force attacks? | Limiting the number of login attempts per IP address | Rate limiting, CAPTCHAs, account lockout after multiple failed attempts. |
13 | What is the difference between password hashing and salting? | Hashing is a one-way process; salting adds a unique random string before hashing | Salting prevents rainbow table attacks and ensures identical passwords have different hashes. |
14 | How 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. |
15 | What is the concept of stateless authentication? | Authentication where session state is not stored on a specific server instance | Using JWTs, where the token contains all necessary user info. |
Advanced Node.js Authentication & Authorization Answers
# | Question | Answer | Examples |
---|---|---|---|
1 | What is argon2? | A modern, secure password hashing algorithm, often recommended for new projects | Faster than bcrypt, considered safer against modern cracking techniques. |
2 | Explain the importance of secure API design. | Using HTTPS, proper input validation, rate limiting, authentication/authorization for API endpoints | Protecting sensitive data, preventing abuse, ensuring data integrity. |
3 | What 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. |
4 | Explain 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')) { ... } |
5 | What 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) { ... })); |
6 | Explain the concept of "Authorization Code Grant" (OAuth 2.0). | A standard flow for web applications to obtain access tokens securely | User redirects to authorization server, grants permission, receives authorization code, app exchanges code for token. |
7 | What 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. |
8 | How 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'); |
9 | What is Content Security Policy (CSP)? | A security header that specifies which resources the browser is allowed to load for a page | Helps prevent Cross-Site Scripting (XSS) attacks. |
10 | How do you prevent Cross-Site Scripting (XSS) attacks? | Sanitizing user input before rendering it, using CSP, escaping HTML | Libraries like DOMPurify or using template engines that auto-escape HTML. |
11 | Explain 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. |
12 | What is the purpose of express-session with trust-proxy? | Allows session cookies to be marked as secure (only sent over HTTPS) | app.use(session()); |
13 | How do you implement rate limiting in Express? | Custom middleware or libraries to prevent excessive requests from a single IP/user | Using libraries like express-rate-limit or custom middleware to track request counts. |
14 | What is the importance of logging security events? | Recording security events (e.g., login attempts, permission changes) for monitoring and auditing | Logging failed logins, password changes, unauthorized access attempts. |
15 | How do you manage user sessions in a distributed environment? | Using a dedicated session store (e.g., Redis, MongoDB) instead of in-memory storage | express-session with connect-redis or connect-mongo. |