SWD 414 Lecture Note
SWD 414 Lecture Note
Example:
When a user logs into an e-commerce site, their session stores login details and items
in their cart. The session persists until it times out or the user logs out.
2. Cookies
How They Work:
Cookies are small pieces of data stored on the client’s browser. They can persist across
sessions and store non-sensitive information, such as user preferences or session
identifiers.
Example: A "Remember Me" feature saves a persistent cookie with a token, allowing
the user to stay logged in between visits.
Summary
Cookies are ideal for lightweight, client-side storage of non-sensitive data or identifiers.
Sessions are better suited for storing sensitive information and managing complex data securely
on the server.
By leveraging both appropriately, developers can create secure, scalable, and user-friendly web
applications.
3.0 SECURITY PRACTICES
Security practices such as authentication, authorization, middleware, and web tokens are vital
for protecting web applications and user data. Authentication ensures users are who they claim
to be, while authorization determines what actions or resources authenticated users can access.
Middleware acts as an intermediary, handling tasks like request validation and enforcing
security policies before requests reach the application. Web tokens, such as JSON Web Tokens
(JWT), enable secure, stateless authentication by transmitting user identity and permissions
Impact: Attackers can gain unauthorized access to sensitive data, modify or delete
records, and compromise the database.
SELECT * FROM users WHERE username = 'user' OR '1'='1'; this always returns
true, allowing unauthorized access.
Prevention: Use anti-CSRF tokens, validate the origin of requests, and implement
SameSite cookies.
3.3 Authentication Tokens
Authentication tokens are secure digital representations used to verify a user's identity and grant
access to protected resources in web applications. They are commonly used in stateless
authentication, allowing servers to validate users without storing session data.
How Authentication Tokens Work:
1. User Login: The user provides credentials (e.g., username and password).
2. Token Generation: If valid, the server generates a token (e.g., a JSON Web Token
or JWT) containing user details and permissions.
3. Token Storage: The client stores the token (in local storage, cookies, or memory)
and includes it in subsequent requests (usually in an Authorization header).
4. Token Validation: The server validates the token before processing the request.
Features of Authentication Tokens:
Compact and Portable: Can be easily transmitted between client and server.
Secure: Often encrypted or signed to prevent tampering.
Stateless: Allows servers to avoid storing session data, improving scalability.
3.4 Various Authentication Token Types and Their Uses
Authentication tokens come in different forms, each designed for specific use cases in web and
API security. Below are the main types of authentication tokens and their applications:
1. JSON Web Token (JWT)
Structure: Consists of three parts: Header, Payload (user data), and Signature.
Use Cases:
Stateless authentication in APIs and SPAs.
User login and session management.
Secure data exchange between services.
Description: Used in the OAuth 2.0 framework for delegated access. Access tokens
grant temporary access to resources, while refresh tokens are used to obtain new
access tokens.
3. Bearer Tokens
Description: Simple tokens that indicate the bearer has access rights. Commonly
used as part of OAuth.
4. Session Tokens
Description: Tokens generated during user login that map to a session stored on the
server.
6. API Keys
Description: Tokens that include a cryptographic hash to verify the authenticity and
integrity of the request.
Use Cases:
Enterprise-level SSO and federated authentication.
Example: An "Editor" role may include permissions to "Create," "Read," and "Update"
content.
Example: A "Support Agent" role may have "Read" access to user tickets but not
"Delete" access.
Benefits of Using Roles and Permissions
Simplified Access Management: Assigning roles to users instead of individual
permissions reduces administrative overhead.
Scalability: Roles and permissions allow for flexible scaling in large systems with
multiple users and access levels.
Enhanced Security: Limits access to sensitive data and actions, ensuring users can only
perform tasks relevant to their role.
Compliance and Auditability: Clear definitions of roles and permissions make it easier
to enforce policies and maintain audit trails.
By leveraging roles and permissions effectively, authorization systems provide secure,
manageable, and scalable access control tailored to organizational needs.
3.7 Middleware and Its Uses in Request Handling
Middleware is software or code that sits between the client and the server's core application
logic, processing incoming requests and outgoing responses. It acts as a series of filters or steps
that each request passes through before reaching its destination. Middleware is widely used in
web application frameworks, such as Express.js in Node.js, Django, or Flask, to handle
repetitive tasks, enforce security policies, or modify request/response data.
3.7.1 Nature of Middleware: Onion-Like Layers of Protection
Middleware is often conceptualized as an onion-like layered structure, where:
Each layer (middleware function) handles a specific concern (e.g., authentication,
logging, or data parsing).
Requests must pass through multiple layers sequentially before reaching the application
logic.
Responses traverse back through the layers, allowing additional processing or
modification.
This structure ensures modularity and separation of concerns, making the application easier to
manage and secure.
Logging and Monitoring: Middleware logs request details (e.g., IP address, endpoint
accessed, and response time) for debugging and monitoring purposes.
Example: Middleware that tracks API usage patterns.
Data Parsing and Validation: Middleware parses incoming request bodies (e.g., JSON,
form data) and validates them to ensure they meet the expected format.
Example: A middleware that rejects requests with missing or invalid fields in the
payload.
Rate Limiting and Throttling: Middleware prevents abuse by limiting the number of
requests a user or client can make in a given time frame.
Example: Throttling requests to 100 per minute per user.
Error Handling: Middleware catches errors during request processing and provides
consistent error responses to clients.
Example: Returning a 500 Internal Server Error with a standardized error message.
3.7.3 Advantages of Middleware
1) Modularity: Each middleware function focuses on a specific task, making it easy to
modify or replace individual layers.
2) Reusability: Middleware can be reused across multiple routes or applications, reducing
redundancy.
3) Centralized Control: Common functionalities like logging and security checks are
handled in a single place, improving maintainability.
4) Scalability: Middleware layers can be added or adjusted as the application grows.
Middleware, with its layered nature, ensures that each request undergoes multiple stages of
processing and validation before reaching the application logic. This modular approach
enhances security, performance, and maintainability, making middleware a critical component
in modern web application development.
4.0 CONNECTION TO DATABASE AND HANDLE RESULT SETS IN PARAGRAPH.
Connecting to a database and handling result sets are essential steps in building dynamic web
applications that rely on data storage and retrieval. A database connection establishes
communication between an application and a database management system (DBMS), enabling
2. Port: The port number on which the database server is listening for connections.
Example: 5432 for PostgreSQL, 3306 for MySQL.
3. Database Name: The name of the database to which the application should connect.
Example: my_database.
5. Driver or Provider: Specifies the database driver or provider the application should use.
Example: Driver= {SQL Server} for ODBC, or Provider= SQLOLEDB for OLE DB.
b. MySQL: mysql://username:password@hostname:port/database_name
Example: mysql://root:[email protected]:3306/sample_db
d. MongoDB: mongodb://username:password@hostname:port/database_name
Example: mongodb://user1:[email protected]:27017/testdb
4.2.3 Use of Connection Strings in Applications
a) Configuration Files: To improve security and maintainability, connection strings are
often stored in configuration files or environment variables.
DATABASE_URL=postgresql://admin:securepass@localhost:5432/my_database
Usage in Code:
import os
db_url = os.getenv("DATABASE_URL")
Features of psycopg2:
Specific to PostgreSQL: Tailored for PostgreSQL databases.
Advanced Features: Supports transactions and server-side cursors.
Parameterization: Reduces SQL injection risks.
Example Code:
import psycopg2
try:
conn = psycopg2.connect(
dbname="test_db",
user="postgres",
password="password",
host="localhost",
port="5432"
)
print("Connected successfully!")
except Exception as e:
print("Connection failed:", e)
finally:
if conn:
conn.close()
4. Java with JDBC (Java Database Connectivity): JDBC is a Java-based API for
connecting to and interacting with databases.
Features of JDBC:
Database Independence: Supports various databases with specific drivers.
Extensive Functionality: Provides full access to database operations.
Error Handling: Robust mechanisms for handling exceptions.
Example Code (MySQL):
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
Each method has its strengths and is suited to specific programming languages, database types,
and application architectures. Selecting the right method ensures efficient, secure, and
maintainable database connectivity.
4.4 Execute Basic Queries on a Database and Retrieve Data into a Result Set
Executing basic queries on a database and retrieving data involves the following steps:
1. Establishing a connection to the database.
2. Executing SQL queries to interact with the database.
3. Storing and processing the results in a result set variable.
Below are examples in various programming languages to demonstrate this process.
PHP (Using PDO)
Example: Retrieve all rows from a table named users.
try {
// Connect to the database
$pdo = new PDO("mysql:host=localhost;dbname=test_db", "root", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try:
except Exception as e:
print(f"Error: {e}")
finally:
if conn:
cursor.close()
conn.close()
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
} catch (SQLException e) {
Explanation:
fetch(PDO::FETCH_ASSOC): Fetches one row at a time as an associative array.
while Loop: Iterates through each row until no more rows are left.
Output: Data from each row is displayed.
Traversal Using MySQLi
Example Code (Object-Oriented):
// Step 1: Connect to the database
$mysqli = new mysqli("localhost", "root", "password", "test_db");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
Explanation:
fetch_assoc(): Fetches one row as an associative array.
while Loop: Iterates through rows while data is available.
Condition num_rows > 0: Ensures the query returns records before looping.
Example Code (Procedural):
// Step 1: Connect to the database
$conn = mysqli_connect("localhost", "root", "password", "test_db");
// Handle errors
if (curl_errno($curl)) {
echo "Error: " . curl_error($curl);
} else {
// Decode and display the response
$data = json_decode($response, true);
foreach ($data as $user) {
echo "Name: " . $user['name'] . ", Email: " . $user['email'] . "<br>";
}
}
// Handle errors
if (curl_errno($curl)) {
echo "Error: " . curl_error($curl);
} else {
echo "Response: " . $response;
}
2. Symfony (PHP): Symfony is another robust PHP framework that provides a reusable
set of components for building scalable, high-performance web applications. It is often
used as a base for other frameworks, such as Laravel.
Key Features:
Modular and Reusable Components: Symfony is known for its reusable components
that can be integrated into any project, making it highly flexible.
Twig Templating Engine: A secure and flexible templating system.
Routing and Dependency Injection: Symfony’s powerful routing system and
dependency injection make application development highly maintainable and flexible.
Built-in Debugging and Profiler: Helps track errors and optimize performance during
development.
Use Cases: