The purpose of website security is to prevent attacks like denial of service attacks, or displaying
modified (and often damaging) information on their homepages, leaking of email id and
passwords, credit card credentials of users in public domain. The more formal definition of
website security is the act/practice of protecting websites from unauthorized access, use,
modification, destruction, or disruption.
Website Security Threats
1. Cross Site Scripting(XSS)
2. SQL Injection
3. Cross Site Request Forgery (CSRF)
1. Cross Site Scripting
XSS is a term used to describe a class of attacks that allow an attacker to inject client-side
scripts through the website into the browsers of other users. Because the injected code comes
to the browser from the site, the code is trusted and can do things like send the user's site
authorization cookie to the attacker. When the attacker has the cookie, they can log into a site
as though they were the user and do anything the user can, such as access their credit card
details, see contact details, or change passwords.
The XSS vulnerabilities are divided into reflected and persistent, based on how the site returns
the injected scripts to a browser.
• A reflected XSS vulnerability occurs when user content that is passed to the server is
returned immediately and unmodified for display in the browser.
o Any scripts in the original user content will be run when the new page is loaded.
For example, consider a site search function where the search terms are encoded
as URL parameters, and these terms are displayed along with the results.
o An attacker can construct a search link that contains a malicious script as a
parameter
(e.g., [Link]
/[Link]"></script>) and email it to another user.
o If the target user clicks this "interesting link", the script will be executed when
the search results are displayed.
o This gives the attacker all the information they need to enter the site as the target
user, potentially making purchases as the user or sharing their contact
information.
• A persistent XSS vulnerability occurs when the malicious script is stored on the
website and then later redisplayed unmodified for other users to execute unwittingly.
o For example, a discussion board that accepts comments that contain
unmodified HTML could store a malicious script from an attacker. When the
comments are displayed, the script is executed and can send to the attacker the
information required to access the user's account.
o This sort of attack is extremely popular and powerful, because the attacker
might not even have any direct engagement with the victims.
While the data from POST or GET requests is the most common source of XSS vulnerabilities,
any data from the browser is potentially vulnerable, such as cookie data rendered by the
browser, or user files that are uploaded and displayed.
The best defense against XSS vulnerabilities is to remove or disable any markup that can
potentially contain instructions to run the code. For HTML this includes elements, such
as <script>, <object>, <embed>, and <link>.
The process of modifying user data so that it can't be used to run scripts or otherwise affect the
execution of server code is known as input sanitization. Many web frameworks automatically
sanitize user input from HTML forms by default.
2. SQL Injection
SQL injection vulnerabilities enable malicious users to execute arbitrary SQL code on
a database, allowing data to be accessed, modified, or deleted irrespective of the user's
permissions. A successful injection attack might spoof identities, create new identities
with administration rights, access all data on the server, or destroy/modify the data to
make it unusable.
SQL injection types include Error-based SQL injection, SQL injection based on boolean
errors, and Time-based SQL injection.
This vulnerability is present if user input that is passed to an underlying SQL statement
can change the meaning of the statement. For example, the following code is intended
to list all users with a particular name (userName) that has been supplied from an HTML
form:
statement = "SELECT * FROM users WHERE name = '" + userName + "';"
If the user specifies a real name, the statement will work as intended. However, a
malicious user could completely change the behavior of this SQL statement to the new
statement in the following example, by specifying a';DROP TABLE users; SELECT *
FROM userinfo WHERE 't' = 't for the userName.
SELECT * FROM users WHERE name = 'a';DROP TABLE users; SELECT * FROM
userinfo WHERE 't' = 't';
The modified statement creates a valid SQL statement that deletes the users table and
selects all data from the userinfo table (which reveals the information of every user).
This works because the first part of the injected text (a';) completes the original
statement.
To avoid such attacks, the best practice is to use parameterized queries (prepared
statements). This approach ensures that the user input is treated as a string of data rather
than executable SQL, so that the user cannot abuse special SQL syntax characters to
generate unintended SQL statements. The following is an example:
SELECT * FROM users WHERE name = ? AND password = ?;
When executing the above query, for example, in Python, we pass
the name and password as parameters, as shown below.
[Link]("SELECT * FROM users WHERE name = ? AND password = ?",
(name, password))
Libraries often provide well-abstracted APIs that handle SQL injection protection for the
developer, such as Django's models. You can avoid SQL injection by using encapsulated
APIs rather than directly writing raw SQL.
Causes of Injection Vulnerabilities
• When the data input by users is not verified, sanitized or filtered.
• It directly adds user input into SQL or command strings, which mixes trusted code with
untrusted data.
• It uses user input in ORM queries, letting attackers fetch data they shouldn't access.
• It builds database queries using user input without using parameters or escaping, which
can lead to injections.
Injection attacks can be prevented by
• Use parameterized queries or prepared statements.
• Validate and sanitize all user inputs.
• Avoid building SQL queries using string concatenation.
• Apply the principle of least privilege to database users.
• Keep your database and libraries up to date.
• Deploy a Web Application Firewall (WAF) as an extra layer.
3. Cross Site Request Forgery (CSRF)
• CSRF attacks allow a malicious user to execute actions using the credentials of another
user without that user's knowledge or consent.
• This type of attack is best explained by example. Josh is a malicious user who knows
that a particular site allows logged-in users to send money to a specified account using
an HTTP POST request that includes the account name and an amount of money. Josh
constructs a form that includes his bank details and an amount of money as hidden
fields, and emails it to other site users (with the Submit button disguised as a link to a
"get rich quick" site).
• If a user clicks the submit button, an HTTP POST request will be sent to the server
containing the transaction details and any client-side cookies that the browser
associated with the site (adding associated site cookies to requests is normal browser
behavior). The server will check the cookies, and use them to determine whether or
not the user is logged in and has permission to make the transaction.
• The result is that any user who clicks the Submit button while they are logged in to the
trading site will make the transaction. Josh gets rich.
• NOTE: The trick here is that Josh doesn't need to have access to the user's cookies (or
access credentials). The browser of the user stores this information and automatically
includes it in all requests to the associated server.
• One way to prevent this type of attack is for the server to require that POST requests
include a user-specific site-generated secret. The secret would be supplied by the server
when sending the web form used to make transfers. This approach prevents Josh from
creating his own form, because he would have to know the secret that the server is
providing for the user. Even if he found out the secret and created a form for a particular
user, he would no longer be able to use that same form to attack every user.
Common Web vulnerabilities
1. Broken Access control
2. Cryptographic Failures
3. Injection
4. Insecure Design
5. Security Misconfiguration
6. Vulnerable and Outdated Content
7. Identification and Authentication Failures
8. Software and Data Integrity Failures
9. Security Logging and Monitoring Failures
10. Server-Side Request Forgery
1. Broken Access control
• This vulnerability occurs when there is broken access to resources, it means there are
some improperly configured missing restrictions on authenticated users which allows
them to access unauthorized functionality or data like access to others accounts,
confidential documents, etc.
• For this attack, attackers take the help of session management and try to access data
from the unexpired session tokens, which gives them access to many valid IDs and
passwords.
Vulnerabilities under Broken Access Control
• A system where access is not granted as per user roles, i.e. anyone in the system can
access any resource, no principle of least privilege is being followed.
• Use of insecure direct object references to access someone else's account without their
knowledge
• Lack of access controls in PUT, POST, DELETE in APIs
• Any kind of tampering with JSON web tokens to elevate privileges like changing roles
from to 'user' to that of an 'admin'.
Broken access control attacks can be prevented by
• Use role-based or attribute-based access control.
• Always enforce authorization on the server side.
• Centralize access control logic.
• Verify resource ownership before access.
• Avoid exposing internal IDs directly (prevent IDOR).
• Log and monitor access control failures.
• Apply the principle of least privilege.
2. Cryptographic Failures
Any organisations data whether in transit or rest when insecure is a cryptographic
failure. Sensitive information like credentials, health records, classified data, business
secrets etc. are included. If the data falls under the privacy laws, it's subjected to a
cryptographic failure.
Vulnerabilities under Cryptographic Failures
• Old or weak cryptographic measures being used by default in a system.
• Data transmission without being encrypted, use of protocols such as HTTP, SMTP, FTP.
• Use of unapproved hash functions such as MD5 or SHA1
• Server certificate and trust chain is not verified properly
• Use of default crypto keys, weak crypto keys, keys being re-used, improper key
management in a system
Ways to Prevent Cryptographic Failures
• Use strong, modern encryption algorithms like AES-256 to protect sensitive data.
• Rotate cryptographic keys regularly to reduce the risk of exposure.
• Generate keys using secure, random processes to avoid predictability.
• Implement multi-factor authentication (MFA) for accessing encryption systems.
• Ensure encryption of both data at rest and in transit to safeguard information throughout
its lifecycle.
• Audit cryptographic systems regularly to detect weaknesses and vulnerabilities.
• Avoid hard-coding keys in code, store them in secure, external locations.
3. Injection
Injection vulnerabilities occur when untrusted data is sent to an interpreter, such as SQL,
NoSQL, or LDAP.
Examples:
● SQL Injection: SELECT * FROM users WHERE id = ‘1’ OR ‘1’=’1';
● Command Injection: rm -rf /
Mitigation Strategies:
● Use parameterized queries.
● Employ input validation and sanitization.
● Utilize ORM frameworks.
4. Insecure Design
Insecure Design vulnerabilities refers to weaknesses that lie in the designing process of
a product. These weaknesses cannot be overcome by secure implementation. They
include flaws like lack of assessment of the security measures required in a design while
being developed.
Principles like Secure design, SDLC, Resource management are overlooked or not
properly configured during development phase.
How to Prevent Insecure Design Vulnerability
• Use Secure development lifecycle during the designing phase of a product
• A pre-configured library of secure design patterns to use as a roadmap
• Threat modelling for designing authentication, access controls, business logics and key
flows
• Conduct unit and integration tests to check if all critical flows of the design are safe as
per the threat model
• A comprehensive document containing use-cases and misuse-cases for each level of the
application
• Segregate the tier layers and network layers on the system according to the level of
protection needed for each of them
5. Security Misconfiguration
It is estimated that up to 95% of cloud breaches are the result of human errors and this
fact leads us to the next vulnerability called security misconfiguration. This
vulnerability refers to the improper implementation of security intended to keep
application data safe. As we know that developer's work is to work on the functionality
of websites and not on security and this flaw allows hackers to keep track of the
configuration of the security and find new possible ways to enter websites. The most
common reason for this vulnerability is not patching or upgrading systems,
frameworks, and components.
Vulnerabilities covered under Security Misconfiguration
• Use of default credentials by an account
• Latest security features on disable mode in the updated systems
• Outdated software
• Insecure security settings like libraries, databses, application frameworks
• Lack of appropriate security measures in the cloud services
• Security headers not set to secure values
How to Prevent Security Misconfiguration Vulnerabilities
• Using Dynamic application security testing (DAST)
• Disabling the use of default passwords
• Keeping an eye on cloud resources, applications, and servers
• Automated process to verify the effectiveness of security configurations time to time
6. Vulnerable and Outdated Components
• Nowadays there are many open-source and freely available software
components (libraries, frameworks) that are available to developers and if there
occurs any component which has got a known vulnerability in it then it becomes
a weak link that can impact the security of the entire application.
• It also occurs because developers frequently don’t know which open source and
third-party components are present in their applications and this makes it
difficult for developers to update components when new vulnerabilities are
discovered in their current versions.
• Attackers can take advantage of these weaknesses to gain unauthorized access,
execute code, or disrupt application functionality.
Vulnerabilities due to Vulnerable and Outdated Components
• Lack of information about all the components including client and server side, including
direct and nested dependencies
• Vulnerable or outdated software, including databases, OS, servers, DBMS, APIs,
runtime environments, libraries and all other components of an application.
• Irregular scan of vulnerabilities in a system
• Untested compatibility of updated, upgraded and patched libraries by software
developers
Vulnerable and Outdated Components attacks can be prevented by
• Remove unnecessary dependencies, features, components and files
• Install components of a system only from official sources through secure channels only.
• Properly maintain the libraries and components and regularly check for updates and
upgrades for each.
7. Identification and Authentication Failures
This vulnerability was previously in the list with the name of broken authentication, It
is a vulnerability that allows an attacker to use manual or automatic methods to try
to gain control over any account they want in a system. In worse conditions, they could
also gain complete control over the system. Identification and Authentication Failures
normally occurs when applications incorrectly execute functions related to session
management allowing intruders to compromise passwords, security keys, or session
tokens.
Causes of Identification and Authentication Failures
• Automated attacks like credential stuffing, brute-force attacks to gain unauthorized
access to a system
• Default and weak credentials are allowed by any system
• Lack of Multi-factor authentication
• Insecure password recovery mechanisms
• Unencrypted storage of usernames and passwords
• Improper validation of Session IDs
Identification and Authentication Failures can be prevented by
• Implementing multi-factor authentication
• Protecting user credentials
• Sending passwords over encrypted connections
• Weak passwords should not be allowed for any user
• Credential Recovery process must be secured
8. Software and Data Integrity Failures
When the integrity of a software or data could be compromised by an attacker leads to
software and data integrity failures. If an application relies on dependencies like
libraries, modules or plugins from a untrusted source or repository it could lead to
Software and Data Integrity Failures. Auto-update functionality where systems are
updated automatically without a proper integrity verification are vulnerable to attacks.
Vulnerabilities under Software and Data Integrity Failures
• Untrusted sources of dependencies for plugins, libraries, modules
• Insecure CI/CD pipeline leading to unauthorized access, malware upload or system
compromise
• Auto-update without proper integrity verification
Software and Data Integrity Failures can be prevented by
• Ensuring libraries and dependencies are installed from trusted repositories
• Unencrypted serialized data should not be sent to untrusted clients without an integrity
check
• use of digital signature to verify the integrity of any software or data
• Efficient code review process for code and configuration changes to reduce the chance
of injected malicious code into the software pipeline.
9. Security Logging and Monitoring Failures
Security Logging and Monitoring Failures occur when applications do not properly log
critical events or fail to monitor and alert on suspicious activities. This can delay
detection of breaches, hinder incident response, and allow attackers to operate
undetected within systems.
Security Logging and Monitoring Failure can be prevented by
• Login controls, access controls and server-side input validation must be ensured
• Logs generated by the system should follow a particular format that can be easily stored
and processed by log management solutions
• Effective monitoring and flagging of suspicious activities that are responded quickly to
• A proper implementation of an incident response plan in case of security incident
10. Server-Side Request Forgery
SSRF(Server-Side Request Forgery) is a newly added vulnerability to the list of
OWASP-10, it refers to when a web application do not validate the user-supplied
URLs before fetching them, which lets the attacker to force the legit website to send a
forged request to an unexpected destination, despite being protected by firewalls, access
controls etc.
Server-Side Request Forgery can be prevented by
• Sanitization and validation of all client-side input data
• HTTP redirections should be disabled
• Avoid using server-side functionality to fetch remote URLs unless absolutely necessary.
• If URL fetching is required, limit it to internal logic with strict controls.
• Use firewalls and network policies to prevent outbound requests to internal or sensitive
systems.
Authentication and Authorization
Two critical pillars of security are authentication—verifying user identity—
and authorization—granting access to resources based on identity.
Authentication is the process of verifying the identity of a user or system to ensure
they are who they claim to be.
• It typically involves credentials such as usernames, passwords, one-time passwords
(OTPs), or biometric methods like fingerprints and face recognition.
• By validating these credentials, authentication prevents unauthorized access and helps
protect sensitive systems and data from security breaches.
Authorization is the process of determining and granting access rights to an
authenticated user or system.
• It defines what resources a user can access and what actions they are allowed to
perform.
• Authorization always occurs after authentication and ensures that only permitted users
can perform specific tasks, thereby enforcing security policies and protecting sensitive
resources.
Authentication Authorization
During the authorization process, a
In the authentication process, the
person's or users's permissions are
identity of users is verified before
checked to determine their access to
granting access to the system.
resources.
In the authentication process, a In this process, a user’s identity is
user’s identity is verified to ensure verified to ensure they are who they
they are who they claim to be. claim to be.
Authentication is performed before Authorization is performed after the
the authorization process authentication process
It needs usually the user's login It requires the user’s privileges or
details. security levels.
Authentication determines whether It determines what permissions the
the person is user or not. user has.
Generally, transmit information Generally, transmit information
through an ID Token. through an Access Token.
The OpenID Connect (OIDC)
The OAuth 2.0 protocol governs the
protocol is an authentication
overall system of user authorization
protocol that is generally in charge
process.
of user authentication process.
The authorization permissions
The authentication credentials can cannot be changed by user as these
be changed in part as and when are granted by the owner of the
required by the user. system and only he/she has the
access to change it.
The user authentication is visible at The user authorization is not visible
user end. at the user end.
The user authentication is identified The user authorization is carried out
with username, password, face through the access rights to
recognition, retina scan, resources by using roles that have
fingerprints, etc. been pre-defined.
Authentication Authorization
Example: After an employee
Example: Employees in a company
successfully authenticates, the
are required to authenticate through
system determines what
the network before accessing their
information the employees are
company email.
allowed to access.
Overview of Authentication Techniques
Authentication is the first line of defense in any application, confirming a user's identity before
granting access.
• Password-Based Authentication: Traditionally, users enter a password to access an account. While
common, this method has vulnerabilities if passwords aren’t securely stored. Using hashing (like
bcrypt) and salting ensures passwords are unreadable even if exposed.
• Token-Based Authentication: In stateless applications, tokens like JSON Web Tokens
(JWTs) serve as authentication credentials. A token, often stored client-side, is sent with requests,
confirming the user’s identity without needing session data on the server.
• OAuth2 and OpenID Connect: OAuth2 is an authorization protocol that allows users to authorize
access to their data on third-party apps without sharing passwords. OpenID Connect extends
OAuth2 with an identity layer, providing user information through a single identity provider.
• Multi-Factor Authentication (MFA): MFA adds a layer of security by requiring additional
verification, such as SMS codes or Time-Based One-Time Passwords (TOTP) from apps like
Google Authenticator. This technique strengthens defenses against password-based attacks.
Popular Authentication Methods
Session-Based Authentication
Session-based authentication stores user sessions on the server, linking them with a session ID stored
in the user’s browser cookies. While effective for small applications, it requires robust session
management, especially in cases of high traffic.
JWT (JSON Web Token)
JWTs are widely used for stateless authentication. A JWT includes encoded information about the
user and is stored client-side, reducing server load. However, managing token expiry and storage
securely (e.g., in HTTP-only cookies) is critical.
OAuth2 and Social Logins
OAuth2 enables users to log in using third-party accounts (e.g., Google, Facebook). Social logins
are convenient for users and minimize password management risks, but require careful
implementation of scopes to limit data access.
Authorization Techniques and Strategies
Authorization ensures users access only permitted resources.
Role-Based Access Control (RBAC)
RBAC assigns permissions based on roles, simplifying access management for predefined user
types (e.g., Admin, Editor, Viewer). It is ideal for applications with clear user roles, making
permission allocation straightforward.
Attribute-Based Access Control (ABAC)
ABAC bases permissions on various user or environment attributes, such as location, time of access,
or device type. This dynamic control system is more flexible than RBAC and suits applications
needing context-based access control.
Access Control Lists (ACLs)
ACLs define permissions for individual resources, allowing for granular control. For instance, each
file or record might have unique access rules, providing fine-grained management at the resource
level.
Policy-Based Access Control (PBAC)
PBAC uses policies to define access based on multiple factors, making it ideal for complex
applications with detailed access requirements. It supports both ABAC and RBAC, offering layered
control, especially useful in microservices architectures.
Best Practices for Secure Authentication and Authorization
Implementing robust authentication and authorization systems requires following best practices to
mitigate potential vulnerabilities:
• Use Secure Protocols: Always use HTTPS to encrypt data between the client and server, avoiding
plaintext transmission. Secure cookies should be HTTP-only to prevent client-side access.
• Implement Password Best Practices: Enforce strong passwords and use modern hashing
algorithms (e.g., bcrypt, Argon2) with salting to secure stored passwords.
• Secure Token Storage: Store authentication tokens in HTTP-only cookies or use local storage with
caution to prevent unauthorized access. For sensitive applications, limit token lifespan and use
refresh tokens.
• Least Privilege Principle: Users should only have access to the resources necessary for their roles,
minimizing the risk of unauthorized access.
Common Challenges in Authentication and Authorization
Ensuring security requires addressing several challenges:
• Session Management: Handling session expiry and renewal is crucial, particularly in session-based
authentication. Techniques like session hijacking prevention—e.g., IP address or browser
fingerprint verification—help secure user sessions.
• Token Expiry and Refreshing: JWTs are stateless, so managing expiry is important. Implement
refresh tokens to extend session duration securely without compromising statelessness.
• Cross-Site Request Forgery (CSRF) Prevention: CSRF attacks exploit user identity on trusted
sites. Use CSRF tokens and avoid token storage in cookies where possible to protect against these
attacks.
Implementing Authentication in Distributed Systems
In microservices and distributed systems, centralizing user identity can simplify management.
• Identity Providers (IdP): Using an IdP allows centralized management of user authentication
across services, reducing redundancy. Common IdPs include Auth0, Firebase Authentication,
and Keycloak.
• Identity Federation and Single Sign-On (SSO): For distributed applications, SSO enables users
to authenticate once and access multiple systems seamlessly. Federated identity allows integration
of multiple identity sources (e.g., Google, LinkedIn) with a single app.
Secure Communication with HTTPS
HTTPS stands for HyperText Transfer Protocol Secure. It is the most common protocol for
sending data between a web browser and a website. HTTPS is the secure variant of HTTP and
is used to communicate between the user's browser and the website, ensuring that data transfer
is encrypted for added security.
Working of HTTPS
• HTTPS establishes the communication between the browser and the web server. It uses
the Secure Socket Layer (SSL) and Transport Layer Security (TLS) protocol for
establishing communication. The new version of SSL is TLS(Transport Layer
Security).
• HTTPS uses the conventional HTTP protocol and adds a layer of SSL/TLS over it.
• The workflow of HTTP and HTTPS remains the same, the browsers and servers still
communicate with each other using the HTTP protocol.
• However, this is done over a secure SSL connection. The SSL connection is responsible
for the encryption and decryption of the data that is being exchanged to ensure data
safety.
I. Security Goals
HTTP is an open protocol, inappropriate for secure communications.
• Goal: widespread public access to public information.
• Clear text. All HTTP messages are transmitted in clear text (a.k.a., plaintext). They
can be read by anyone and are vulnerable to packet sniffers.
• Mostly anonymous access. HTTP does not require identify confirmation. In essence,
anonymous access is allowed, although client domains/IP addresses may be recorded.
HTTPS is designed to support secure, private communications.
• Confidentiality through encryption of messages.
• Authentication to verify identities of communicating parties.
II. Encryption
Encryption is the process of translating a plaintext message into an encoded form, not
readable by others.
A ciphertext is the result of encryption. The ciphertext can be transmitted over the network.
Even if intercepted, the ciphertext is designed to be unreadable.
Decryption is the process of recovering the original plaintext message from the ciphertext.
HTTP transfers data in a hypertext format between the browser and the web server, whereas
HTTPS transfers data in an encrypted format. As a result, HTTPS protects websites from
having their information broadcast in a way that anyone eavesdropping on the network can
easily see.
• During the transit between the browser and the web server, HTTPS protects the data
from being accessed and altered by hackers.
• Even if the transmission is intercepted, hackers will be unable to use it because the
message is encrypted.
• It uses an asymmetric public key infrastructure for securing a communication link.
Public Algorithms, Private Keys
Encryption generally uses public algorithms and private keys. Public algorithms are assumed
to be known by everyone. Private keys are the secrets that allow senders and recipients to
keep others from decrypting messages.
Why public algorithms? Secrecy can be achieved using private algorithms known only to
sender and recipient. But what if the algorithm is discovered?
• It may be costly and time-consuming to replace the "broken" encryption technology
with a new private algorithm.
• How do you communicate the new private algorithm?
• With public algorithms, only the secrecy of the decryption key must be maintained.
• If the key is discovered, it can quickly be replaced without investing in new
encryption technology.
Symmetric vs. Public Key Algorithms
Symmetric algorithms use the same key for encryption and decryption.
• The key is a shared secret between sender and recipient.
• A separate key is required for every sender-recipient pair.
• How are keys communicated?
Public key algorithms use two keys: a public encryption key and a private decryption key.
• Anyone can encode a message to a particular recipient using that recipient's public
key.
• Only the recipient can recover the plaintext using the private key.
• The private key need never be communicated.
• Only one pair of keys is needed by each recipient.
• A discovered private key can very quickly be changed by simply publishing a new
public key.
Limits to Encryption
Encryption technology cannot provide a guarantee of confidentiality. The plaintext of a
message may be discovered in several ways.
• Host compromise of sender system.
• Recipient's private key becomes known.
• Ciphertext is cracked through a weak algorithm or short key.
Note: HTTPS uses the following algorithms for encryption and hashing purposes:
• RSA: Used during the TLS/SSL handshake to securely exchange keys between client
and server. It’s an asymmetric encryption algorithm.
• SHA-256: Used for data integrity in digital signatures and certificates. It’s a hashing
algorithm, not for encrypting the actual traffic.
III. Authentication
Digital Signatures
A digital signature is used to secure the authenticity of a document.
• A checksum or message digest is computed for the document.
• The checksum is encrypted with the author's private key.
• The document is signed by appending the encrypted checksum to document.
• The authenticity of a document can be computing the document checksum and
comparing this with the result of decrypting the signature with the author's public key.
But how do we know that we have the right public key for an author, i.e., it is not a fake?
Digital Certificates
A digital certificate is a record that establishes the identity of a party to a communication
(e.g., author of a document).
• Certificates identify the certificate owner (subject) and the owner's public key.
• Certificate authorities are trusted third parties that issue certificates.
• A digital signature for the certificate is computed using the certificate authority's
private key.
• Verifying the identity and public key of a large number of potential correspondents is
reduced to verifying the identity and public keys of a smaller number of certificate
authorities.
IV. SSL/TSL: Secure Sockets Layer/Transport Layer Security
SSL (Secure Sockets Layer) 3.0 is the current widely deployed protocol used for providing a
secure communications layer for HTTP, as developed by Netscape.
TLS (Transport Layer Security) is the standards-track IETF protocol based on SSL. TLS 1.0
is essentially the successor to SSL 3.0.
SSL/TLS is a layer on top of TCP/IP, below application level protocols.
HTTP over SSL/TLS is known as HTTPS.
Application Layer HTTP HTTPS
SSL/TLS
Network Layer TCP/IP
TCP/IP
Normally, HTTPS service listen on port 443, while HTTP defaults to port 80. Both types of
service may be running on a single server.
The main responsibility of SSL is to ensure that the data transfer between the communicating
systems is secure and reliable. It is the standard security technology that is used for
encryption and decryption of data during the transmission of requests.
• HTTPS is basically the same old HTTP but with SSL.
• For establishing a secure communication link between the communicating devices,
SSL uses a digital certificate called SSL certificate.
Roles of the SSL layer
• Ensuring that the browser communicates with the required server directly.
• Ensuring that only the communicating systems have access to the messages they
exchange.
The Handshake
The handshake is the key process for a client and server to exchange authentication and
encryption information under SSL or TLS.
1. Establish identity of server.
2. Develop a shared encryption key that can be used to exchange messages, called the
session key.
• Client: Hello, here is a list of encryption algorithms I know.
• Server:
o Hello, here is the algorithm I chose from your list.
o Also, here is my certificate and public key.
• Client examines certificate and makes sure that it is signed by a known certificate
authority.
• Client: OK, here is the premaster secret encrypted with your public key.
• Now both client and server can use the premaster secret to compute the session key:
the encryption key for subsequent messages.
• Client: [encrypted] I'm finished with the handshake.
• Server: Got it, an encrypted reply is next.
• Server: [encrypted] I'm finished with the handshake.
• All subsequent messages are encrypted.
Essentially, SSL consists of two phases corresponding to two subprotocols. The SSL
Handshake Protocol governs the first phase to establish secure communication. Subsequently,
all messages are encrypted and exchanged using the SSL Record Protocol.
Input Validation
Input validation is a fundamental aspect of web application security.
Input validation is the process of checking user-supplied data against predefined rules to ensure
it meets expected criteria.
It ensures that only properly formatted data is accepted by an application, which helps to protect
against a variety of attacks, such as SQL injection, cross-site scripting (XSS), and command
injection.
The Importance of Input Validation
Web applications often rely on user input to function correctly. This input can come from various sources,
such as form submissions, URL parameters, cookies, and APIs.
Without proper validation, malicious actors can manipulate input to exploit vulnerabilities in the application.
Input validation acts as a first line of defense by ensuring that only valid, expected data is processed by the
application.
Common Threats Mitigated by Input Validation
1. SQL Injection (SQLi)
• Description: An attacker injects malicious SQL code into a query, allowing them to
manipulate or access the database.
• Example: Entering ' OR '1'='1 in a login form to bypass authentication.
• Mitigation: Validate and sanitize input to ensure it does not contain harmful SQL code.
2. Cross-Site Scripting (XSS)
• Description: An attacker injects malicious scripts into web pages viewed by other users,
leading to data theft, session hijacking, and other malicious actions.
• Example: Embedding <script>alert('XSS');</script> in a comment field.
• Mitigation: Validate and sanitize input to prevent the inclusion of executable scripts.
3. Command Injection
• Description: An attacker executes arbitrary commands on the server by injecting malicious
input into a command executed by the application.
• Example: Entering ; rm -rf / in a search field that passes input to a shell command.
• Mitigation: Validate input to ensure it does not contain characters or patterns that could be
interpreted as commands.
4. Cross-Site Request Forgery (CSRF)
• Description: An attacker tricks an authenticated user into performing unwanted actions on
a web application.
• Example: Sending a user a malicious link that triggers a fund transfer when clicked.
• Mitigation: Validate and verify the source of requests to ensure they are legitimate.
Input Validation Techniques
Input validation is the process of checking user-supplied data against predefined rules to ensure it meets
expected criteria. Effective validation techniques include:
• Data type validation: Ensuring input matches the expected data type (e.g., integer, string, date).
• Length validation: Limiting input to a specific length to prevent buffer overflows.
• Range validation: Checking if input falls within a predefined range (e.g., age between 0 and 120).
• Pattern matching: Using regular expressions to validate input against specific patterns (e.g., email
format).
• Whitelisting and blacklisting: Creating lists of allowed or prohibited characters or words.
Sanitization
Input sanitization involves transforming or removing harmful characters from user input to
prevent malicious code execution. Key techniques include:
• Removing or modifying harmful characters: Eliminating characters that can be
exploited in attacks.
• Normalizing input data: Converting input to a standard format to prevent
inconsistencies.
• Escaping special characters: Properly escaping characters to prevent their interpretation
as code.
• Input filtering: Applying filters to remove or modify specific types of input.
Best Practices for Input Validation and Sanitization
To effectively protect your application, consider the following best practices:
• Validate input at multiple layers: Implement validation at both the client and server
sides.
• Use parameterized queries and prepared statements: Prevent SQL injection by using
parameterized queries and prepared statements in database interactions.
• Employ output encoding: Encode output to prevent XSS attacks by rendering special
characters as their literal equivalents.
• Consider input validation libraries: Leverage existing libraries to simplify validation
and sanitization processes.
• Regular security testing and code reviews: Conduct thorough security assessments and
code reviews to identify vulnerabilities.
• Stay updated on security vulnerabilities: Keep informed about the latest threats and
vulnerabilities to implement appropriate countermeasures.
Output Encoding
Output encoding, in the context of web security, is a crucial technique used to prevent injection
attacks, particularly Cross-Site Scripting (XSS).
Output encoding is the process by which characters in the input string that potentially make it
dangerous are escaped, so they are treated as text instead of being treated as part of a language
like HTML.
This is the appropriate choice when you want to treat input as text, for example, because your
website uses templates that interpolate input into content. Most modern templa2ng engines
automa2cally perform output encoding. For example, Django's templa2ng engine performs
the following conversions:
• < is converted to <
• > is converted to >
• ' is converted to '
• " is converted to "
• & is converted to &
This means that if you pass <img src=x onerror=alert('XSS!')> into the
Django template above, it will be converted to <img src=x
onerror=alert('XSS!')>, which is displayed as the following
text:
You searched for <img src=x onerror=alert('XSS!')>.
UNIT-4
The most common way to connect frontend to backend is by using RESTful API
communication. Other processes of connecting frontend to backend include using web socket
communication, server-side rendering (SSR), GraphQL integration or combining WebSockets
and GraphQL.
There are 5 known ways to connect frontend and backend applications, they include:
#Process 1: Connecting Frontend and Backend using RESTful API Communication
#Process 2: Connecting frontend and Backend using Web Socket Communication
#Process 3: connecting Frontend and Backend using Server Side Rendering (SSR)
#Process 4: Connecting Frontend and Backend using GraphQL Integration
#Process 5: Connecting Frontend and Backend by combining WebSockets and GraphQL
Connecting Frontend and Backend using RESTful API
Communication
RESTful API Communication: Representational State Transfer (REST) is a popular
architectural style for building web services.
It utilizes the HTTP protocol for communication between the frontend and backend.
Before we dive deep into “RESTful API Communications”, let’s first understand some key
connection terms.
API: This means Application Programming Interface, it defines a set of rules and protocols
that allow different software applications to communicate with each other.
HTTP (Hypertext Transfer Protocol): HTTP is the protocol used for transferring data over
the web. It enables communication between clients (such as browsers) and servers.
Endpoints: Endpoints are URLs that represent specific resources on the server.
In RESTful APIs, endpoints are used to perform different actions (e.g., retrieving data,
creating new records, updating existing records, deleting records).
HTTP Methods: RESTful APIs utilize different HTTP methods for different types of
operations:
• GET: Retrieve data from the server.
• POST: Send data to the server to create new records.
• PUT: Update existing records on the server.
• DELETE: Remove records from the server.
We now understand the meaning of API, HTTP, Endpoints, HTTP Methods and REST.
Let’s now talk about the steps required to connect frontend and backend using RESTful API
STEP 1: Setting Up the Backend API
• Choose a backend framework or technology such as [Link] with Express or
Django for Python.
• Define routes and endpoints for your API using the chosen framework.
• Implement business logic and database operations within the API endpoints.
STEP 2: Sending Requests from the Frontend
• Use JavaScript’s fetch API or libraries like Axios to send HTTP requests from the
frontend.
• Construct the appropriate request method (GET, POST, PUT, DELETE) and
headers.
• Include any necessary data in the request body or as query parameters.
STEP 3: Handling Responses in the Frontend
• Parse and process the response received from the backend.
• Update the frontend’s UI based on the response data.
• Handle error cases and display appropriate messages to the user.
BEST PRACTICES FOR SEAMLESSLY INGRATING FRONT END AND BACKEND
Best practices that can help fullstack developers integrate frontend and backend systems more
efficiently. From choosing the right technologies to optimizing performance and security, these
strategies will help you build more robust, scalable applications.
1. Crafting Efficient APIs to Connect Frontend and Backend
• At the heart of every fullstack application lies the API (Application Programming
Interface). The API acts as a bridge, enabling the frontend to communicate with the
backend and vice versa. Designing efficient and scalable APIs is crucial for ensuring
smooth communication between both layers.
• When designing APIs, it’s essential to choose the right approach based on the needs of
the application.
Versioning:
Over time, APIs evolve. Introducing breaking changes can disrupt frontend
functionality. To avoid this, make sure to version your APIs, so older versions remain
functional while the frontend is updated to accommodate newer ones.
2. Component-Based Frontend Architectures
Modern frontend development revolves around creating reusable, modular components. This
approach not only improves code maintainability but also ensures that the application can scale
more efficiently.
• React, [Link], and Angular:
Frameworks like React, [Link], and Angular are built around component-based
architecture. By breaking down the UI into smaller components, fullstack developers
can manage and reuse elements across the application, reducing redundancy.
• State Management:
As applications grow, managing state across components becomes increasingly
complex. Tools like Redux (for React) or Vuex (for [Link]) centralize state
management, making it easier to control data flow and debug the application.
3. Backend Best Practices: Designing Scalable and Efficient Systems
The backend of a fullstack application is responsible for handling business logic, database
operations, and processing API requests. To ensure scalability and performance, fullstack
developers must pay attention to the following:
• Choosing the Right Framework:
Frameworks like [Link], Django, and Ruby on Rails offer powerful tools for building
scalable backends. [Link] is particularly suited for high-performance applications
requiring non-blocking, asynchronous operations, making it ideal for real-time apps or
microservices architectures.
• Database Management:
Whether you choose an SQL (e.g., PostgreSQL, MySQL) or NoSQL (e.g., MongoDB)
database depends on the type of data you’re working with. SQL databases are perfect
for structured data and complex queries, while NoSQL offers flexibility for unstructured
or rapidly changing data.
• Handling Authentication and Authorization:
Implementing secure authentication mechanisms like JWT (JSON Web Tokens)
or OAuth2 ensures that only authorized users can access sensitive data or services.
Fullstack developers should also pay close attention to how user sessions are managed
and ensure security best practices are followed.
4. Synchronizing Frontend and Backend for Seamless Interaction
Fullstack developers must ensure that the frontend and backend are perfectly in sync.
Misaligned data structures or improper API handling can lead to bugs or poor user experience.
Here’s how to keep both sides in harmony:
• Data Consistency:
Use tools like TypeScript to enforce consistent data types across both frontend and
backend. For example, using shared types for API responses ensures that the frontend
and backend expect the same structure, minimizing runtime errors.
• Error Handling:
It’s important to implement consistent error-handling mechanisms across the stack.
Ensure that backend errors are properly logged and communicated to the frontend, where
they can be gracefully displayed to the user.
• Shared Business Logic:
Avoid duplicating business logic across frontend and backend. Instead, move shared
logic (e.g., validation or data formatting) to a common API or library, ensuring both
layers follow the same rules.
5. Optimizing Performance Across the Fullstack
Performance optimization is crucial to providing a smooth user experience. Fullstack developers
need to address both frontend and backend bottlenecks to ensure optimal performance.
Frontend Optimization Techniques:
• Use lazy loading to load components and images only when needed, reducing initial
load times.
• Implement code splitting to break the application into smaller chunks, so only the
necessary code is loaded at runtime.
• Compress images and minify CSS/JavaScript files to reduce file sizes and improve load
speeds.
Backend Optimization Techniques:
• Caching with tools like Redis or Memcached can drastically reduce database load and
improve API response times.
• Use pagination or limit queries to handle large datasets efficiently and prevent API
overloads.
6. Fullstack Security: Protecting Both Frontend and Backend
Security is a major concern in fullstack development, and both the frontend and backend must
be protected from potential threats.
Frontend Security:
• Always use HTTPS to secure communication between the frontend and backend.
• Implement proper input validation and sanitation to prevent common attacks like Cross-
Site Scripting (XSS).
Backend Security:
• Use robust authentication mechanisms (like OAuth2 or JWT) to secure your APIs.
• Employ rate limiting to protect your application from brute-force attacks or excessive
API calls.
RESTful API
REST (Representational State Transfer) is an architectural style for creating web services. This
is the most popular approach. It generally uses HTTP request and response methods in order to
exchange data in a normalize format. The backend exposes different endpoints for multiple
functionalities, and then frontend makes calls to these endpoints in order to retrieve or
manipulate data.
Procedure:
1. Client (Frontend):
• Makes an HTTP request to a specific API endpoint (URL) on the server.
• Specifies the request method (GET, POST, PUT, DELETE) and the desired
action.
• May include request body with data for specific actions like creation or update.
2. Server (Backend):
• Receives the request and identifies the targeted endpoint based on the URL and
method.
• Processes the request, accessing databases, performing calculations, or
interacting with other services.
• Prepares a response containing the requested data, status code (e.g., 200 for
success), and any additional information.
3. Client:
• Receives the response and interprets the status code and data content.
• Updates the user interface or performs further actions based on the returned
information.
AJAX
AJAX = Asynchronous JavaScript And XML.
AJAX is not a programming language.
AJAX just uses a combination of:
• A browser built-in XMLHttpRequest object (to request data from a web server)
• JavaScript and HTML DOM (to display or use the data)
• It is a web development technique in which a web app fetches content from the server
by making asynchronous HTTP requests, and uses the new content to update the
relevant parts of the page without requiring a full page load. This can make the page
more responsive, because only the parts that need to be updated are requested.
• Ajax can be used to create single-page apps, in which the entire web app consists of a
single document, which uses Ajax to update its content as needed.
• Initially Ajax was implemented using the XMLHttpRequest interface, but
the fetch() API is more suitable for modern web applications: it is more powerful, more
flexible, and integrates better with fundamental web app technologies such as service
workers. Modern web frameworks also provide abstractions for Ajax.
• AJAX allows web pages to be updated asynchronously by exchanging data with a web
server behind the scenes. This means that it is possible to update parts of a web page,
without reloading the whole page.
HOW AJAX WORKS?
How AJAX works to send & receive data asynchronously
AJAX uses JavaScript to:
1. Send a request to the server in the background.
2. Server processes the request.
3. Response is returned (JSON/XML/text).
4. JavaScript updates only the required part of the webpage.
This avoids a full page refresh.
AJAX Example (Using fetch())- Send Request
fetch("[Link]
.then(response => [Link]())
.then(data => {
[Link](data);
[Link]("result").innerHTML = [Link];
});
• JS sends an asynchronous request.
• Page does NOT reload.
• Response arrives from server.
• Only a small part of the page updates.
ASYNCHRONOUS PROGRAMMING
Synchronous vs Asynchronous
Feature Synchronous Asynchronous
Execution Tasks execute sequentially Tasks execute concurrently
Blocking Each task blocks the next until Non-blocking – tasks run in background
finished
Example Reading a file before sending a Reading a file asynchronously while
response handling other requests
Asynchronous programming is a technique that enables your program to start a potentially long-
running task and still be able to be responsive to other events while that task runs, rather than
having to wait until that task has finished. Once that task has finished, your program is presented
with the result.
Many functions provided by browsers, especially the most interesting ones, can potentially take
a long time, and therefore, are asynchronous. For example:
• Making HTTP requests using fetch()
• Accessing a user's camera or microphone using getUserMedia()
• Asking a user to select files using showOpenFilePicker()
So even though you may not have to implement your own asynchronous functions very often,
you are very likely to need to use them correctly.
The Problem with Synchronous Code
Imagine we’re building a web app that needs to fetch user data from an API. If JavaScript
worked only synchronously, our code might look like this:
The problem? The entire webpage would freeze for 3 seconds while waiting for the API
response. Users couldn’t click buttons, scroll, or do anything. This creates a terrible user
experience.
Mechanisms for Asynchronous Programming
1. Asynchronous Callbacks – The Solution
Asynchronous callbacks allow us to handle time-consuming tasks without freezing the browser.
Instead of waiting for an operation to complete, we tell JavaScript: “Start this task, and when
it’s done, call this function.”
Here’s how the same API call would work with async callbacks:
2. Promises
• Represents a value that may be available now, later, or never.
• Has three states: pending, fulfilled, rejected.
3. Async/Await
• Introduced in ES2017 for cleaner asynchronous code.
• Works on top of Promises.
• CORS (Cross-Origin Resource Sharing)