Unit 4: Authentication and Database Integration - Subjective Questions
INT257 — Modern Web Application Development • Practice Questions with Detailed Answers
20 questions
Define authentication and explain its importance in modern web applications.
Authentication is the process of verifying the identity of a user, device, or service before granting access to an application. It answers the question: "Who are you?"
Authentication is important because it:
- Prevents unauthorized users from accessing private accounts and resources.
- Supports secure features such as user profiles, payments, and personal dashboards.
- Establishes a trusted identity for subsequent authorization decisions.
- Helps applications maintain accountability by associating actions with users.
- Protects sensitive data from unauthorized disclosure or modification.
Common authentication methods include passwords, one-time passwords, tokens, social login, and biometric verification. Passwords should be stored as secure hashes rather than plain text.
Explain the typical authentication workflow using username and password credentials.
A typical username-and-password authentication workflow consists of the following steps:
- The user submits a username and password through a secure form.
- The server validates the input format and searches for the corresponding user record.
- The stored password hash is retrieved from the database.
- The submitted password is compared with the stored hash using a password-hashing algorithm.
- If the comparison succeeds, the server creates an authenticated session or issues an access token.
- The client receives a session cookie or token for future requests.
- For each protected request, the server verifies the session or token before allowing access.
Passwords should be transmitted over HTTPS and processed with algorithms such as bcrypt, scrypt, or Argon2. Failed attempts should produce a generic error message so that attackers cannot determine whether a username exists.
Describe session management in a web application and explain how sessions are created, maintained, and destroyed.
Session management maintains a user's authenticated state across multiple HTTP requests. Since HTTP is stateless, a session identifier is used to associate requests with server-side session data.
- Session creation: After successful login, the server generates a random, unpredictable session identifier and stores user-related information on the server.
- Session maintenance: The identifier is sent to the browser in a cookie. The browser automatically includes the cookie in later requests.
- Session verification: The server uses the identifier to retrieve the session and determine whether the user is authenticated.
- Session expiration: Sessions should expire after a fixed period or after a period of inactivity.
- Session destruction: During logout, the server invalidates the session and removes or expires the browser cookie.
Secure cookies should use HttpOnly, Secure, and appropriate SameSite attributes. Session identifiers should be regenerated after login to reduce session fixation risks.
Compare cookie-based sessions and token-based authentication.
Cookie-based sessions and token-based authentication both maintain authentication state, but they differ in storage and verification.
| Aspect | Cookie-based sessions | Token-based authentication |
|---|---|---|
| State | Usually server-side | Often self-contained in the token |
| Client storage | Cookie | Cookie, memory, or application storage |
| Server lookup | Requires session-store lookup | May be verified using a signature |
| Revocation | Usually simple by deleting the session | More difficult until token expiry or blacklist handling |
| Scalability | Requires shared session storage in distributed systems | Can reduce session lookups, but requires careful token management |
| Common risks | Session theft and fixation | Token theft, leakage, and long-lived credentials |
Cookie-based sessions work well for traditional server-rendered applications. Token-based approaches are common in APIs and distributed systems. Neither approach is automatically secure; HTTPS, short lifetimes, secure storage, and proper validation are required.
What are protected routes? Explain how a web application protects a route from unauthenticated access.
A protected route is an application route that can be accessed only after the server confirms that the requester is authenticated.
A common protection process is:
- The client sends a request to the route.
- Authentication middleware checks for a valid session cookie or access token.
- The middleware verifies the credential's signature, expiration, and associated user.
- If authentication succeeds, the request continues to the route handler.
- If authentication fails, the server returns an unauthorized response, commonly HTTP
401, or redirects the user to a login page. - The route handler performs the requested operation only after the middleware has completed successfully.
Protection must be implemented on the server, even if the frontend hides links or redirects users. Client-side checks improve user experience but cannot enforce security because they can be bypassed.
Distinguish between authentication and authorization with suitable web application examples.
Authentication verifies a user's identity, whereas authorization determines what an authenticated user is allowed to do.
- Authentication answers: "Who is the user?"
- Authorization answers: "What may this user access or perform?"
For example, when a user logs in with valid credentials, the application authenticates the user. If that user attempts to delete a product, the application then checks whether the user's permissions include product deletion. A regular customer may be authenticated but unauthorized to perform that operation.
The usual order is:
- Authenticate the request.
- Identify the user and their permissions.
- Authorize the requested action.
- Execute the action only if permission is granted.
Authentication failures generally result in HTTP 401, while authorization failures generally result in HTTP 403.
Explain role-based access control and describe how it can be implemented in a web application.
Role-Based Access Control (RBAC) assigns permissions to roles, and roles to users. This avoids assigning every permission separately to every user.
For example:
customer: view personal orders and update a profile.editor: create and update articles.administrator: manage users, roles, and application settings.
An implementation can use a user record containing a role field or separate user, role, and permission tables. Authorization middleware can then check the required role before a route executes:
- Authenticate the request.
- Load the user's role from a trusted server-side source.
- Compare the role with the route's required role.
- Continue for an allowed role.
- Return HTTP
403for an authenticated user without sufficient permission.
RBAC should follow the principle of least privilege, meaning users receive only the permissions necessary for their responsibilities.
Design an authorization strategy for an application containing administrator, instructor, and student users.
An appropriate strategy can define roles and permissions as follows:
| Role | Example permissions |
|---|---|
| Administrator | Manage users, courses, roles, and system settings |
| Instructor | Create courses, publish lessons, and grade assigned students |
| Student | View enrolled courses, submit assignments, and view personal grades |
The request-processing design should be:
- Authenticate every protected request.
- Retrieve the user's role and relevant ownership information from the database.
- Apply role-based checks for general permissions.
- Apply resource-level checks for ownership, such as verifying that an instructor owns a course.
- Deny access by default when no explicit permission exists.
- Return
401when the user is unauthenticated and403when the user is authenticated but lacks permission. - Record sensitive authorization failures for auditing.
Role names should not be trusted from client-submitted form fields. Authorization decisions must be made using server-side data.
Define ORM and explain the main advantages and limitations of using an ORM in web application development.
An Object-Relational Mapper (ORM) is a software layer that maps programming-language objects and classes to relational database tables and rows.
Advantages:
- Reduces repetitive SQL and database boilerplate.
- Allows developers to work with familiar objects and methods.
- Provides model relationships such as one-to-many and many-to-many mappings.
- Often includes migrations, validation hooks, and transaction support.
- Helps reduce some SQL injection risks through parameterized queries.
- Improves portability between supported database systems.
Limitations:
- Automatically generated queries may be inefficient.
- Complex reports may be easier to express using direct SQL.
- Incorrect relationship loading can cause the N+1 query problem.
- Developers still need to understand tables, indexes, joins, and transactions.
- ORM abstractions can make database behavior less visible.
An ORM is useful for common application operations, but query performance should still be monitored.
Explain how database connectivity is established between a web application and a relational database.
Database connectivity allows the application server to communicate with a database management system.
The general process is:
- Select a database driver or ORM compatible with the database system.
- Provide a connection string containing the host, port, database name, username, and password.
- Create a connection or connection pool when the application starts.
- Acquire a connection when a request requires database access.
- Execute parameterized queries or ORM operations.
- Release the connection back to the pool after the operation completes.
- Handle connection errors, timeouts, and shutdown cleanup.
A connection pool improves performance by reusing established connections and limiting concurrent database usage. The application should use asynchronous operations where supported and should never expose database credentials to frontend code.
Describe the CRUD operations and explain how they map to common HTTP methods.
CRUD represents the four basic operations performed on persistent data:
- Create: Adds a new record. It commonly maps to HTTP
POST. - Read: Retrieves one or more records. It commonly maps to HTTP
GET. - Update: Changes an existing record. It commonly maps to HTTP
PUTorPATCH. - Delete: Removes a record. It commonly maps to HTTP
DELETE.
For example, an API for articles may use:
POST /articlesto create an article.GET /articlesto list articles.GET /articles/:idto retrieve one article.PATCH /articles/:idto update selected fields.DELETE /articles/:idto remove an article.
Each operation should validate input, authenticate the requester where necessary, authorize the action, handle missing records, and return suitable HTTP status codes.
Explain the complete lifecycle of a CRUD request from the client to the database and back to the client.
A CRUD request generally passes through several application layers:
- The client sends an HTTP request containing a method, URL, headers, and possibly a request body.
- Middleware parses the request and performs logging, authentication, and authorization checks.
- The route handler identifies the requested operation and extracts route parameters.
- The controller or service validates the input and applies business rules.
- The data-access layer uses an ORM or parameterized SQL query to communicate with the database.
- The database executes the operation and returns records, an affected-row count, or an error.
- The application transforms the result into a safe response format, removing confidential fields.
- The server returns an appropriate status code and JSON response to the client.
Error handling should distinguish validation errors, authentication failures, authorization failures, missing records, conflicts, and unexpected server errors.
What is data validation? Explain the difference between client-side and server-side validation.
Data validation checks whether submitted data is complete, correctly formatted, and acceptable according to application rules.
Client-side validation occurs in the browser. It provides immediate feedback, reduces unnecessary requests, and improves usability. However, it can be bypassed by sending requests directly to the server.
Server-side validation occurs on the application server. It is the authoritative security boundary and must validate every request before data is processed or stored.
Validation may check:
- Required fields and allowed data types.
- String length and numeric ranges.
- Email or URL format.
- Allowed enumeration values.
- Uniqueness constraints.
- Relationships between fields, such as matching passwords.
Both forms of validation are useful, but server-side validation is mandatory. Validation errors should return clear, structured messages without exposing internal implementation details.
Explain how input validation and parameterized queries help prevent common database security vulnerabilities.
Input validation and parameterized queries address different parts of database security.
- Input validation restricts data to expected types, lengths, formats, and values. It prevents malformed or abusive input from reaching business logic and reduces risks such as excessive payloads.
- Parameterized queries keep SQL commands separate from user-provided values. The database treats the supplied values as data rather than executable SQL syntax.
- Allowlisting is preferred for fields such as sort direction or column names, where values cannot always be passed as ordinary parameters.
- Output filtering prevents sensitive database fields, such as password hashes or internal tokens, from being returned to clients.
- Least-privilege database accounts limit the damage caused by a compromised application.
Escaping strings alone is not a reliable substitute for parameterized queries. Validation should be applied on the server for every relevant endpoint.
Describe environment variables and explain why they are used in web applications.
Environment variables are configuration values supplied to an application by its execution environment rather than hard-coded into source files.
They are commonly used for:
- Database connection strings.
- Session secrets and token-signing keys.
- API keys and third-party service credentials.
- Port numbers and runtime modes.
- Feature flags and deployment-specific settings.
They are useful because the same code can run in development, testing, staging, and production with different configuration values. Sensitive values are kept out of the source repository and can be managed by deployment platforms or secret-management systems.
Applications should validate required environment variables during startup, avoid logging secrets, provide safe defaults only for non-sensitive settings, and ensure that server-only variables are never bundled into frontend code.
Explain how an application should securely manage database credentials and other secrets using environment variables.
A secure secret-management process should follow these practices:
- Store credentials in environment variables or a dedicated secret manager rather than source code.
- Keep local development values in an ignored configuration file, such as
.env, and provide a documented example file containing placeholder names only. - Configure production secrets through the hosting platform or an encrypted secret store.
- Validate required values at startup and fail safely when they are missing.
- Use separate credentials for development, testing, and production.
- Grant the database account only the permissions required by the application.
- Rotate secrets periodically and immediately after suspected exposure.
- Prevent secrets from appearing in logs, error responses, client bundles, or version control history.
Environment variables reduce accidental exposure, but they are not a complete security system. Access controls, encryption, auditing, and rotation are also required.
Describe the security risks associated with improper session management and explain suitable countermeasures.
Improper session management can lead to account takeover and unauthorized access. Common risks include:
- Session fixation: An attacker causes a victim to use a known session identifier.
- Session theft: A session cookie is captured through malware, insecure transport, or cross-site scripting.
- Long-lived sessions: Stolen identifiers remain useful for an extended period.
- Predictable identifiers: Attackers can guess valid sessions.
- Logout failure: A session remains valid after the user logs out.
Countermeasures include:
- Regenerate the session identifier after login and privilege changes.
- Use HTTPS for all authenticated traffic.
- Set cookies with
HttpOnly,Secure, and suitableSameSiteattributes. - Use random, high-entropy session identifiers.
- Apply idle and absolute session timeouts.
- Invalidate sessions on logout and password changes.
- Protect state-changing requests against CSRF.
- Monitor unusual session activity where appropriate.
Explain the principle of least privilege in authentication, authorization, and database integration.
The principle of least privilege states that every user, process, service, and database account should receive only the permissions required to perform its intended task.
Applications apply this principle by:
- Giving ordinary users access only to their own resources.
- Assigning administrative permissions only to trusted roles.
- Using separate service accounts for different application components.
- Restricting database accounts from performing unnecessary schema or administrative operations.
- Limiting access tokens and sessions to appropriate scopes and lifetimes.
- Checking object ownership in addition to broad role membership.
Least privilege reduces the impact of stolen credentials, programming errors, and compromised components. It should be combined with default-deny authorization, regular permission reviews, auditing, and careful separation of development and production environments.
Compare one-to-one, one-to-many, and many-to-many relationships in ORM-based database design.
ORM relationships describe how records in one model correspond to records in another model.
- One-to-one: One record in model A corresponds to one record in model B. For example, a user may have one profile. A foreign key is commonly placed in one of the related tables with a uniqueness constraint.
- One-to-many: One record in model A corresponds to many records in model B. For example, one instructor may create many courses. The many-side table usually stores the foreign key.
- Many-to-many: Many records in model A correspond to many records in model B. For example, students can enroll in many courses and courses can contain many students. This requires a junction table containing foreign keys for both models.
An ORM can expose these relationships through methods or properties, but developers must still understand foreign keys, constraints, cascading behavior, and query performance.
Explain database transactions and describe why they are important when performing related CRUD operations.
A database transaction groups multiple operations into one logical unit. The operations either all succeed or are rolled back so that partial changes are not retained.
Transactions are commonly described using ACID properties:
- Atomicity: All operations succeed or none are applied.
- Consistency: Database constraints remain valid before and after the transaction.
- Isolation: Concurrent transactions do not produce invalid intermediate results.
- Durability: Committed changes persist after completion.
For example, transferring funds may require subtracting money from one account and adding it to another. If the second update fails, the first update must be rolled back. Similarly, creating an order and its order items should usually occur in one transaction.
An ORM may provide transaction APIs, but developers must choose transaction boundaries carefully and handle rollback and retry behavior where required.
Define authentication and explain its importance in modern web applications.
Authentication is the process of verifying the identity of a user, device, or service before granting access to an application. It answers the question: "Who are you?"
Authentication is important because it:
- Prevents unauthorized users from accessing private accounts and resources.
- Supports secure features such as user profiles, payments, and personal dashboards.
- Establishes a trusted identity for subsequent authorization decisions.
- Helps applications maintain accountability by associating actions with users.
- Protects sensitive data from unauthorized disclosure or modification.
Common authentication methods include passwords, one-time passwords, tokens, social login, and biometric verification. Passwords should be stored as secure hashes rather than plain text.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →