Securing APIs
by Tomas Trescak· APIs

0 / 1590 XP

Presentation Transcript
If you prefer text to video, check out the transcript of the presentation above

Slide 1 ----------- Slide 2 ----------- Part 1: Hey everyone! In our blogging app, users read posts and admins add new ones. APIs are like the messengers that carry data between the app and the server. Without them, nothing works! But they are open to abuse. Part 2: APIs are doors to your app. If they’re not locked properly, anyone can sneak in—stealing data or crashing your site. Scary, right? Part 3: Think about a hacker accessing unpublished blog posts or flooding your site with fake requests. Today, we’ll learn how to stop that! Part 4: Some think APIs are secure by default. Nope! Security isn’t automatic—you have to build it in. Part 5: Imagine an admin’s secret draft post leaking because we didn’t check who’s asking for it. That’s a data leak—sensitive info slipping out. Part 6: What if someone pretends to be the admin and deletes posts? That’s unauthorized access—huge trouble! Part 7: Ever heard of SQL injection? It’s like sneaking a command into a search bar to trick the server into spilling all posts. Part 8: A flood of fake requests could crash our blog, leaving readers frustrated. That’s a DDoS attack. Slide 3 ----------- Part 1: The mainstream approach is to authenticate users using your API. Authentication is like checking ID at the door. Only valid users—like our admin—get in. Part 2: We’ll use JSON Web Tokens (JWT). It’s a secure pass that proves you’re legit without sharing passwords. In our app, the admin logs in, gets a JWT, and uses it to manage posts. No token? No access! Part 3: We've covered this in the authentication lecture, but let's recap. The login route issues a new JWT token, which we can store in a cookie or in a local storage. Part 4: Then, each subsequent request reads the token. If the token is absent, the request is unauthenticated and fails. Part 5: We can also easily check the integrity of the token in case someone has tampered with its content. This could lead to unauthorised requests. Otherwise, we know who's knocking! Slide 4 ----------- Part 1: The other issue when dealing with APIs is the possibility of someone listening to the communication and stealing or manipulating sensitive data. This is also known as a man-in-the-middle attack. Using HTTPs severly limits this type of attack. Part 2: HTTPS is like sending your blog posts in a locked box. Without it, hackers can peek at everything! Part 3: You can use TLS certificates encrypt data between the client and server. It’s a must for our blogging app. The certificates are configured on the app level. Slide 5 ----------- Part 1: The other issues you may run into is someone either accidentally or malevolently flooding your API with millions of requests crashing your application. If so, you might have been targetted by DDoS attack. Part 2: Rate limiting caps how many requests someone can send. No more DDoS crashing our blog! Part 3: Throttling is a method used to control the number of requests that clients can make to our server, helping to ensure optimal performance. By implementing throttling, we establish a specific time interval during which a client can send a new request. For instance, we can set a rule that allows a client to create a new request only every five seconds. Any requests that arrive before this time period expires will be disregarded. This approach helps manage client activity and keeps our server running smoothly. Part 4: Let’s limit users to 100 requests every 15 minutes. Fair for readers, tough on attackers. Part 5: Using the express rate limit package, we can easily set the allowed number of requests per IP given the time frame. NextJS allows similar solutions. Slide 6 ----------- Part 1: Yet another problem that you can encounter is users sending malevolent or incorrect data to your API endpoint. Part 2: Validation ensures data—like a new blog post—fits what we expect. No funny business! You should validate data on client for better user experience, and then again on server for security reasons. Part 3: On top of validation, sanitisation strips out nasty stuff, like code meant to hack our database or start a cross-site scripting attack. Part 4: There are many libraries out there that will help you develop validation and sanitisation approaches. Part 5: Zod allows you to define the shape of your data, providing requirements on each property. Part 6: Then, we can use this schema to parse the incoming request assuring that data matches our expectations. Slide 7 ----------- Part 1: APIs need layers: authentication, encryption, limits, and validation. Our blog thrives with them! Part 2: Start secure—don’t bolt it on later. Test every endpoint like an admin or reader would. Part 3: Skipping HTTPS or weak tokens is like leaving your blog’s door unlocked. Don’t do it!

Description
All the extra information about this section

APIs (Application Programming Interfaces) are the backbone of modern applications, enabling systems to communicate and exchange data. However, this connectivity also opens up APIs to potential security threats, making it crucial to implement measures to protect both your data and services. This chapter explores common security challenges and practical strategies for securing your APIs. 1. UNDERSTANDING API SECURITY RISKS APIs are exposed to various risks that can compromise sensitive data or disrupt services: * Data Leakage: Sensitive data may be exposed due to improper validation or insufficient access controls. * Unauthorised Access: Attackers can gain access to API endpoints that lack proper authentication and authorisation. * Injection Attacks: Malicious data input, such as SQL injection, can manipulate backend systems. * DDoS (Distributed Denial of Service): High volumes of traffic can overwhelm your API, rendering it unresponsive. 2. IMPLEMENTING AUTHENTICATION AND AUTHORISATION Authentication ensures that only valid users can access the API, while authorisation determines which resources each user can access. * OAuth 2.0: An industry-standard protocol used for authorisation, allowing applications to access user data without exposing passwords. * JWT (JSON Web Token): A compact, self-contained token that verifies user identity and access rights. * API Keys: Simple tokens assigned to clients for identifying valid applications. Should be used with other security measures. Example: In an Express.js API, you might issue check for a JWT token like this: const jwt = require('jsonwebtoken'); const SECRET_KEY = 'YOUR_SECRET_KEY'; function issueToken() { // call this during login to issuse the secure token as a cookie const token = jwt.sign({ username: 'admin' }, SECRET_KEY, { expiresIn: '1h' }); // Set token as HTTP-only cookie res.cookie('authToken', token, { httpOnly: true, secure: true }); } function verifyToken(req, res, next) { const token = req.cookies.authToken; if (!token) return res.status(401).json({ message: 'Access denied' }); try { const verified = jwt.verify(token, SECRET_KEY); req.user = verified; next(); } catch (err) { res.status(400).json({ message: 'Invalid token' }); } } 3. USING HTTPS HTTPS (Hypertext Transfer Protocol Secure) encrypts data transmitted over the network, protecting against eavesdropping or man-in-the-middle attacks. * TLS (Transport Layer Security): Ensure that your API endpoints are configured with TLS certificates for encrypted connections. 4. RATE LIMITING AND THROTTLING Prevent abuse by limiting the number of requests clients can make in a given period. * Rate Limiting: Enforces a maximum number of requests per client within a timeframe, preventing DDoS attacks. * Throttling: Reduces the rate at which a client can make requests, ensuring fair resource allocation. Example: Using the express-rate-limit package for rate limiting in an Express.js API: const rateLimit = require('express-rate-limit'); const limiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100 // Limit each IP to 100 requests per windowMs }); app.use('/api', limiter); 5. INPUT VALIDATION AND SANITIZATION Avoid injection attacks by validating and sanitizing incoming data. * Validation: Check that incoming data conforms to the expected structure, type, and format. * Sanitization: Strip out dangerous characters or patterns to prevent SQL injection, XSS (Cross-Site Scripting), and other attacks. Example: In Node.js, you can use the express-validator package: const { body, validationResult } = require('express-validator'); app.post('/register', [ body('email').isEmail(), body('password').isLength({ min: 6 }) ], (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } // Register the user... }); 6. LOGGING AND MONITORING Monitor API usage to detect anomalies and identify potential threats. * Logging: Record all access attempts, including IP addresses and request paths. * Monitoring: Use analytics tools to monitor traffic and identify unusual patterns. 7. CONCLUSION Securing your API requires a layered approach that encompasses various strategies, including authentication, encryption, rate limiting, and validation. By understanding the risks and implementing appropriate safeguards, you can ensure that your API remains a robust and reliable channel for data exchange. Incorporating security from the start will also protect your application’s reputation and help build trust with your users.
Maggie

Discuss with Maggie
Use the power of generative AI to interact with course content

Maggie is a generative AI that can help you understand the course content better. You can ask her questions about the lecture, and she will try to answer them. You can also see the questions asked by other students and her responses.

Discuss with Others
Ask questions, share your thoughts, and discuss with other learners

Join the discussion to ask questions, share your thoughts, and discuss with other learners
Setup
React Fundamentals
10 points
Next.js
10 points
Advanced React
Databases
10 points
React Hooks
Authentication and Authorisation
10 points
APIs
CI/CD and DevOps
Testing React
Advanced Topics