0% found this document useful (0 votes)
3 views31 pages

API Security

The document provides an overview of APIs, including their definition, common use cases, and security practices. It emphasizes the importance of API security measures such as authentication, authorization, encryption, and regular risk assessments to protect against vulnerabilities. Additionally, it discusses the use of OAuth 2.0 and JWT for secure access and information exchange, along with best practices for API design and error handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views31 pages

API Security

The document provides an overview of APIs, including their definition, common use cases, and security practices. It emphasizes the importance of API security measures such as authentication, authorization, encryption, and regular risk assessments to protect against vulnerabilities. Additionally, it discusses the use of OAuth 2.0 and JWT for secure access and information exchange, along with best practices for API design and error handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

API: SECURITY, CREATION AND

DESIGNING

NISHANI S NITHIKA A RAM PRAJEETH

22011102064 22011102065 22011102082


WHAT
IS AN API
API stands for Application Programming Interface, and it's
a set of rules that allows different software applications to
communicate with each other. APIs act as a contract
between two applications, defining how they exchange
requests and responses.
COMMON USE CASES
0 DATA INTEGRATION
1 APIs facilitate the integration of disparate systems, allowing
organizations to consolidate data from various sources,
enhancing data accuracy and accessibility for informed
decision-making.
02ManyTHIRD PARTY SERVICES
applications leverage APIs to connect with third-party services,
such as payment gateways or social media platforms, enabling
enhanced functionality and user engagement without extensive in-
house development.
03 APIsMOBILE AND WEB APPLICATIONS
are crucial for mobile and web applications, providing a means
for these platforms to communicate with servers, retrieve data,
and perform operations efficiently, ensuring a smooth user
experience.
API SECURITY
API security refers to the practices and technologies used to protect APIs
from being exploited.
This involves several layers of security:
• Authentication – Verifying that the parties requesting access to the API
are who they claim to be.
• Authorization – Ensuring that the authenticated party has permission to
perform the requested actions.
• Encryption – Protecting data in transit and at rest from interception or
tampering.
• Rate Limiting – Preventing abuse and denial-of-service attacks by limiting
how often a user or service can make requests.
• Logging and Monitoring – Keeping records of API usage to detect and
respond to potential security threats or policy violations.
• Data Validation – Ensuring that the data received from an API is correct
and safe to process. This helps prevent common attacks such as SQL injection or
cross-site scripting (XSS).
API SECURITY PRINCIPLES
01 AUTHENTICATE AND AUTHORIZE
Implement strong authentication methods using OAuth 2.0, OpenID Connect, and JSON
Web Tokens (JWT) to secure API access. Enforce the Principle of Least Privilege (POLP) by
granting only necessary permissions based on roles, groups, or users.

02 IMPLEMENT ACCESS CONTROL


Use a zero-trust security model for managing access, ensuring APIs are protected behind
firewalls, API gateways, and web application firewalls (WAF). Apply controls such as rate
limiting, geo-velocity checks, geo-fencing, and content validation to protect from overuse or
attacks.

03 ENCRYPT API TRAFFIC


Ensure all API traffic, including requests and responses, is encrypted using HTTPS.
Implement HTTP Strict Transport Security (HSTS) to prevent API clients from falling back
to less secure protocols and to ensure encryption at all times.
API SECURITY PRINCIPLES
04 DATA VALIDATION
Always validate and sanitize API inputs server-side, even if the data is cleansed on the
client-side. This helps prevent attacks such as SQL injection, Cross-Site Scripting (XSS),
and Cross-Site Request Forgery (CSRF). Use debugging tools like Postman to monitor
data flows.

05 CONDUCT API RISK ASSESSMENTS


Regularly assess your APIs using OWASP’s API Security Top 10 to identify vulnerabilities.
Document the risk levels, affected systems, and create mitigation plans. Update the risk
assessment whenever API changes or new threats arise.

06 LIMIT DATA EXPOSURE


APIs should return only the necessary data fields for a given request to minimize
exposure. Avoid sending entire data records when only partial information is needed,
and reduce the risk of overexposure of sensitive data.
API SECURITY PRINCIPLES
07 SELECT APPROPRIATE API
Choose SOAP for more stringent security needs, as it supports message-level
encryption, digital signatures, and Web Services Security. REST is simpler but requires
careful implementation of access control and encryption, as it deals with data
transmission more flexibly, often using JSON.

08 ASSESS THIRD PARTY API


Before integrating third-party APIs, understand their security mechanisms and how they handle
data. Ensure third-party APIs meet your security standards to avoid introducing vulnerabilities
through external integrations.

09 SECURE API KEYS


Store API keys securely using environment variables or a secrets management service
to prevent accidental exposure. Never hard-code them in your source code. Regularly
rotate API keys and delete unused ones to reduce the attack surface.
API SECURITY PRINCIPLES
10 REGULAR SECURITY TESTING
Test API security during development and continue testing regularly to ensure security
controls work as intended. Simulate attacks to evaluate incident response preparedness
and address any gaps in threat detection and mitigation.

11 MAINTAIN AN API REGISTRY


Create and maintain a comprehensive API registry listing all active, retired, and deprecated
APIs. Document details such as payloads, usage, and access points, along with ownership. This
helps prevent shadow APIs and aids in compliance and audits.
AUTHENTICATION TYPES
•Basic Authentication: Using username and password in the
header (less secure).

•OAuth 2.0: OAuth 2.0 is an authorization framework that allows


third-party applications to access user data without exposing their
credentials. Instead of sharing passwords, users grant access
tokens to apps, which can then interact with the API on their behalf.

•JWT (JSON Web Tokens): JWT is a compact, URL-safe token


used for securely transmitting information between parties. It is
often used for authentication, containing a payload (such as user
data) that is cryptographically signed to ensure its integrity. JWTs
are commonly used in OAuth 2.0 to grant and verify user access.
FRAMEWORKS
What is OAuth 2.0?
1. OAuth 2.0 is an open authorization framework that allows third-party
services to access user resources without sharing credentials.
2. It provides a secure and scalable method for authorizing client applications.

Key Components:
3. OAuth Client: Application requesting access to a resource.
4. Authorization Server: Verifies the user’s identity and issues tokens.
5. Resource Owner: The user who owns the resource/data.
6. Resource Server: Holds the protected resources (data) which the client wants
to access.
WORKFLOW:
Step 1: Authorization Request
The OAuth Client requests authorization from the Authorization Server to
access resources on behalf of the Resource Owner.
Step 2: Token Issuance
Upon authorization, the Authorization Server provides a token to the OAuth
Client.
Step 3: Access Resource
The OAuth Client uses the token to access the OAuth Resource Server, which
holds the desired resources.
Step 4: Resource Access
The Resource Server verifies the token and grants the client access to the
resources.
• PROPERTIES:
• Authentication: When a user successfully logs in using their credentials, an
ID token is returned. According to the OpenID Connect (OIDC) specs, an ID
token is always a JWT.
• Authorization: Once a user is successfully logged in, an application may
request to access routes, services, or resources (e.g., APIs) on behalf of that
user. To do so, in every request, it must pass an Access Token, which may be
in the form of a JWT. Single Sign-on (SSO) widely uses JWT because of the
small overhead of the format, and its ability to easily be used across
different domains.
• Information exchange: JWTs are a good way of securely transmitting
information between parties because they can be signed, which means you
can be certain that the senders are who they say they are. Additionally, the
structure of a JWT allows you to verify that the content hasn't been
tampered with.
1. JWT authentication is a token-based stateless authentication
mechanism. It is popularly used as a client-side-based
stateless session, this means the server doesn’t have to
completely rely on a data store (or) database to save session
information.
2. JWTs can be encrypted, but they are typically encoded &
signed. We will be focusing on Signed JWTs. The purpose of
Signed JWT is not to hide the data but to ensure the
authenticity of the data. And that is why it’s highly
recommended to use HTTPS with Signed JWTs.
Feature OAuth 2.0 Java Web Tokens (JWT)
Purpose Authorization protocol for third- Token format used for secure
party access. information exchange.
Function Delegates access to resources Self-contained tokens with
via tokens. claims, typically used in OAuth.
State Can be stateful (session-based Stateless—JWT is self-
tokens) or stateless. contained and doesn't require
server-side storage.
Use Case Used to control access to Used to transmit data between
resources and grant parties securely.
permissions.
Token Type Can use different types of JWT is one specific type of
tokens (e.g., Bearer tokens, token, often used in OAuth.
JWT).
Signature Doesn't require a signature Always includes a signature to
itself (though OAuth tokens can ensure data integrity.
be signed).
Storage OAuth tokens may be stored JWTs are typically stored in
server-side. local storage or cookies.
Sample JWT implementation
const express = require('express’);
const jwt = require('jsonwebtoken’);
const bcrypt = require('bcryptjs'); // For password hashing (optional but common)
const app = express();
app.use(express.json()); // Middleware to parse JSON

// Secret key to sign the JWT (in a real app, store this securely)
const JWT_SECRET = 'your_secret_key’;

// Dummy database (just an example)


const users = [ { id: 1, username: 'john', password: bcrypt.hashSync('password123', 8) } ];

// Route to login a user and return a JWT


app.post('/login', (req, res) => {
const { username, password } = req.body;

// Find user by username


const user = users.find(u => u.username === username);

if (!user) { return res.status(400).json({ message: 'Invalid username or password' }); }

// Check if the password matches the hashed password


const passwordIsValid = bcrypt.compareSync(password, user.password);
if (!passwordIsValid) {
return res.status(400).json({ message: 'Invalid username or password' }); }
// Generate JWT (expires in 1 hour)
const token = jwt.sign({ id: user.id, username: user.username }, JWT_SECRET,
{ expiresIn: '1h' // Token expires in 1 hour
});

// Send the token to the client


res.json({ token }); });

// Protected route (requires valid JWT)


app.get('/protected', (req, res) => { // Get token from the Authorization header
const token = req.headers['authorization’];
if (!token) {
return res.status(403).json({ message: 'Token is required' }); }

// Verify the token


jwt.verify(token, JWT_SECRET, (err, decoded) => {
if (err) {
return res.status(401).json({ message: 'Invalid token' }); }

// Access protected data


res.json({ message: 'Welcome to the protected route!', user: decoded }); }); });

// Start the server


app.listen(3000, () => { console.log('Server running on port 3000'); });
API DESIGN FOR SECURITY
1. Input validation
Input validation ensures that the data coming into the API is in the correct format and safe to
use. This is crucial because attackers often try to manipulate inputs (like form fields) to inject
malicious code, such as SQL injection attacks.
If your API expects a number, make sure the input is actually a number and not a script or a
harmful string.

•Whitelisting: Only allow known, safe characters or inputs. For example, for a name field,
allow letters and spaces only.
•Escaping Special Characters: Convert special characters into harmless representations to
prevent them from being interpreted as code. (e.g. <, >, ‘, “).
•Avoid Direct User Input in SQL Queries: This is essential to prevent SQL injection. Always
use prepared statements or parameterized queries that separate user inputs from the query
itself.
2. Rate limiting and throttling

Prevent brute force and denial-of-service attacks by limiting API usage per user or IP.
Rate limiting ensures that users can only make a certain number of requests in a given
period, protecting your API from being overwhelmed by excessive requests (brute force or
denial-of-service attacks).
How It Works: You can define a rule that allows each user (or IP address) to make, for
example, only 100 requests per minute. If they exceed that limit, their requests will be
blocked temporarily.
3. Error handling
Design APIs to return generic error messages to avoid leaking sensitive information.
Explanation: When an API encounters an error, it’s important to be careful about what
information is shared. If an API gives too much detail in its error messages, it can
unintentionally reveal sensitive information about the system to potential attackers.
Best Practices:
• Return generic error messages such as “An error occurred” or “Invalid input,”
without revealing technical details (e.g., "SQL syntax error").
• Log detailed errors internally: For debugging purposes, keep detailed logs in the
server, but only expose minimal information to the user.
• Avoid exposing stack traces: These contain critical information about your code
structure, which could help attackers find vulnerabilities.
THANK YOU

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy