Statistics
10
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-05-13

AuthorJosé Haro Peralta

Practical, battle-tested techniques to recognize and prevent attacks on your APIs. Hackers know how important your APIs are, and they also know how to find the weak spots in your API security. As a result, APIs have become principal vectors of attack against apps and sites. Secure APIs: Design, build, and implement shows you reliable methods you can use to counter cracks, hacks, and attacks on your internal and external APIs. In this innovative new book, you’ll learn: Addressing the OWASP Top 10 API security vulnerabilities API security by design Zero-trust security Automated API testing strategies Observability and monitoring for threat detection Written for developers and architects, Secure APIs: Design, build, and implement shows you how to create and deploy APIs that are resistant to the most common security threats. Author José Peralta illustrates each vulnerability with extended code samples and shows you exactly how to mitigate them in your own APIs. You’ll find insights into emerging AI-powered security threats, along with tips and patterns for using LLMs in your own security testing. about the technology APIs are the primary way to share data and services privately inside applications and publicly with customers and partners. Unfortunately, they’re also a prime target for cyberattacks. Here’s the good news! There are proven strategies for finding vulnerabilities, locking out intruders, and building APIs that are secure by design. what's inside API security by design Zero-trust security Automated API testing strategies Observability and monitoring for threat detection about the reader For software developers and architects, cybersecurity professionals, and QA engineers. Examples are in Python.

Tags
No tags
ISBN: 1633436632
Publish Year: 2025
Language: 英文
Pages: 376
File Format: PDF
File Size: 36.4 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

M A N N I N G José Haro Peralta Foreword by Dan Barahona Design, build, and implement
Secure APIs
ii
Secure APIs DESIGN, BUILD, AND IMPLEMENT JOSÉ HARO PERALTA FOREWORD BY DAN BARAHONA M A N N I N G SHELTER ISLAND
For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2026 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. The author and publisher have made every effort to ensure that the information in this book was correct at press time. The author and publisher do not assume and hereby disclaim any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from negligence, accident, or any other cause, or from any usage of the information herein. Manning Publications Co. Development editor: Marina Michaels 20 Baldwin Road Technical editor: Corey Ball PO Box 761 Review editor: Radmila Ercegovac Shelter Island, NY 11964 Production editor: Keri Hales Copy editor: Keir Simpson Proofreader: Katie Tennant Typesetter and cover designer: Marija Tudor ISBN 9781633436633 Printed in the United States of America
To my wife, Jiwon, whose constant support and encouragement gave me the strength I needed to write this book, and to our daughter, Ivy, whose magical laughter and curiosity brightened every step of the process
brief contents 1 ■ What is API security? 1 2 ■ Aligning API security with your organization 21 3 ■ API security principles 45 4 ■ Top API authentication and authorization vulnerabilities 74 5 ■ Top API configuration and management vulnerabilities 108 6 ■ API security by design 129 7 ■ API authorization and authentication 159 8 ■ Implementing API authentication and authorization 193 9 ■ Secure API infrastructure 224 10 ■ Financial-grade APIs 246 11 ■ Observability for API security 266 12 ■ Testing API security 289 appendix A API security checklist 311 appendix B Setting up Auth0 for authentication and authorization 314 appendix C API security RFCs and learning resources 325vi
contents foreword xii preface xiv acknowledgments xvi about this book xviii about the author xxiii about the cover illustration xxiv 1 What is API security? 1 1.1 What is API security? 2 1.2 What is API security by design? 7 Design 8 ■ Implementation 10 ■ Infrastructure 10 1.3 Why is API security important? 11 1.4 Unexpected vectors of attack 12 1.5 How API security fits into the API development cycle 14 1.6 The rapidly changing landscape of API security 17 1.7 Who this book is for and what you will learn 18 2 Aligning API security with your organization 21 2.1 Evaluating your API security posture 22 2.2 Threat modeling is a team sport 26 Application decomposition 28 ■ Threat identification and ranking 29 ■ Response and mitigations 32 ■ Review and validation 33vii
CONTENTSviii2.3 Act now! 33 Document your APIs 34 ■ Strengthen authentication and authorization 34 ■ Use proper API libraries 36 ■ Use cloud protection tools 37 2.4 Creating an API security program 38 2.5 Aligning API security with your organization 39 2.6 Navigating API security audits 42 3 API security principles 45 3.1 Shift-left API security 46 3.2 Zero-trust APIs 51 3.3 Validate everything 55 3.4 No such thing as an internal API 62 3.5 You can’t protect what you don’t know 64 3.6 DevSecOps for APIs 68 4 Top API authentication and authorization vulnerabilities 74 4.1 Running the code examples 75 4.2 Broken object-level authorization 77 4.3 A practical example of BOLA 79 4.4 Broken authentication 82 4.5 A practical example of broken authentication 86 4.6 Broken object property level authorization 87 Mass assignment 88 ■ Excessive data exposure 92 Practical example of excessive data exposure 95 4.7 Broken function-level authorization 97 4.8 A practical example of preventing BFLA 100 4.9 Unrestricted access to sensitive business flows 101 4.10 A practical example of mitigating abuse of vulnerable business flows 104 5 Top API configuration and management vulnerabilities 108 5.1 Unrestricted resource consumption 109 Fending off a DoS attack 109 ■ Addressing unrestricted resource consumption with code 112 5.2 Server-side request forgery 114
CONTENTS ix5.3 A practical example of mitigating SSRF 117 5.4 Security misconfiguration 118 5.5 A practical example of mitigating security misconfiguration 120 5.6 Improper inventory management 121 5.7 Unsafe consumption of APIs 123 5.8 Addressing unsafe consumption of APIs in practice 125 6 API security by design 129 6.1 What is vulnerable API design? 130 6.2 Predictable identifiers 134 6.3 Unconstrained user input 135 6.4 Flexible schemas 142 Optional properties 142 ■ Additional properties 145 6.5 Exposing server-side properties in user input 148 6.6 Designing safe user flows 151 7 API authorization and authentication 159 7.1 Authentication vs. authorization 160 7.2 Understanding JSON Web Tokens 162 JWTs defined 163 ■ Structure and representation of JWTs 163 7.3 Understanding Open Authorization 169 7.4 Understanding OAuth flows 171 Authorization code flow 172 ■ Protecting authorization requests with proof of key exchange 174 ■ Client credentials flow 176 Device authorization flow 177 ■ Refresh token flow 178 7.5 Sender-constrained tokens 179 Using mTLS for certificate-bound tokens 179 ■ Demonstrating proof of possession 181 7.6 Understanding OpenID Connect 184 7.7 Understanding role-based access controls 187 8 Implementing API authentication and authorization 193 8.1 Documenting authenticated endpoints with OpenAPI 194 8.2 Issuing JWTs 197
CONTENTSx8.3 Validating JWTs 203 8.4 Integrating with an OpenID Connect provider 206 Logging in users and issuing access tokens with an OIDC provider 207 ■ Validating access tokens issued by an OIDC provider 213 8.5 Adding authorization middleware 215 8.6 Implementing role-based access controls 219 9 Secure API infrastructure 224 9.1 API gateways 225 9.2 Secure network topologies 233 9.3 Protecting against layers 3–6 attacks 236 9.4 Fending off malicious traffic with WAFs 242 10 Financial-grade APIs 246 10.1 What is open banking? 247 10.2 What is FAPI? 249 10.3 Understanding FAPI’s attacker model 249 10.4 Securing APIs with FAPI 2.0’s security profile 251 10.5 Securing authorization requests 256 10.6 Message signing 262 11 Observability for API security 266 11.1 What is API observability? 267 11.2 Logs, traces, and metrics 268 11.3 Instrumenting APIs 274 11.4 Logging custom events 277 11.5 Detecting input-based attacks 280 11.6 Detecting endpoint abuse attacks 283 11.7 Summary 287 12 Testing API security 289 12.1 Designing an API security testing strategy 290 12.2 Discovering design security flaws in our APIs 293 12.3 Using fuzzing and contract testing 296 12.4 Automating access control tests 302
xi12.5 Testing business flow vulnerabilities 306 appendix A API security checklist 311 appendix B Setting up Auth0 for authentication and authorization 314 appendix C API security RFCs and learning resources 325 references 329 index 341
foreword A few years ago, a cyber researcher decided to examine the Coinbase app. They watched all the traffic between their browser and the server, mapping out the API calls behind everyday functions such as checking prices and executing trades. Like a good hacker, they ditched the web interface and started communicating directly with the API, where they could be a lot more creative with requests. (The UI is far too con- trolled and restrictive.) This particular researcher had already purchased some Ethereum, so they crafted a request to sell their Ethereum via the API but told the server to sell it as Bitcoin instead. They pressed Enter and waited for the error message to return—but it never came. What they received instead was a trade confirmation. Their $1,060 in Ethereum successfully sold as more than $43,000 in Bitcoin. To Coinbase’s credit, the issue was fixed within hours, and the researcher was rewarded with the company’s largest-ever bug bounty: $250,000. José has written the book we need for a world in which these kinds of API flaws are discovered daily. The Coinbase story is only one vivid example of what attackers love about APIs: over-permissioned functions, exposed data, and logic flaws invisible in the UI. José doesn’t waste time with platitudes or silver bullets. He goes straight at these hard problems, showing how to build APIs with security woven into their DNA. He explains why authentication and authorization are so critical; what the most common mistakes are; and how to design, test, and operate APIs that can withstand the kind of abuse attackers attempt every day. APIs, after all, make the internet work. Every time you log in to your bank account, check the weather, or turn on your car’s air conditioning from your phone, you’re using an API. APIs have made it vastly easier to build, integrate, and operatexii
FOREWORD xiiiapplications. Today, it’s estimated that more than 90% of all internet traffic flows through APIs. Attackers have caught on. The age of simple SQL injections and cross-site scripting attacks is fading—or at least those attackers are a lot less effective. The new battle- ground is the API layer, where attackers exploit flaws that legacy security tools can’t defend. This unrelenting tide of incidents inspired me to create APIsec University, helping educate developers and security engineers to build and defend APIs securely. More than 100,000 students have enrolled, which is proof of both the urgency of the problem and the hunger for solutions. But the breaches keep coming, not in thousands of records but hundreds of millions—37 million at T-Mobile, 200 million at Venmo, and 700 million at LinkedIn. The conclusion is inescapable: traditional defenses such as firewalls, detection sys- tems, code scanners, and app testing are failing at the API layer. There are good reasons why. API attacks aren’t obvious. SQL injection is easy to detect and block; logic flaws are not. Attackers take advantage of subtle gaps in busi- ness logic that are almost impossible to detect in real time. They unfold slowly and deliberately, over weeks or months, whereas defenses have milliseconds to decide whether a request is legitimate. Too often, APIs live in a blind spot between develop- ment and security. That is exactly why this book matters. José doesn’t just explain the problem but also shows you how to fix it. If your team builds, uses, or integrates APIs, his book is mandatory reading. You won’t find a more complete, digestible, and practical guide. APIs are the engines of modern innovation. Let’s make sure that they aren’t an open invitation to attackers as well. —DAN BARAHONA COFOUNDER, APISEC UNIVERSITY
preface APIs are now the main attack vector on the internet and the principal source of breaches. Technical and business leaders rightly consider API security to be a top con- cern. The sheer number of standards and protocols we need to know to implement API security is daunting, but that doesn’t mean we should shy away from APIs. In today’s ecosystem, that’s probably impossible. Our mission as developers, architects, and cybersecurity professionals is to learn the right standards and protocols to protect our APIs, and this book will help you in that journey. APIs have become the industry standard for exposing data and functionality over the internet. We use APIs to power web and mobile applications; connect Internet of Things (IoT) devices; drive integrations between microservices; deliver products and services; and, more recently, expose the capabilities of generative AI models. APIs account for 83% of all internet traffic; unfortunately, they are often improperly secured, making them ideal targets for hackers and cybercriminals. In 2024, Akamai registered 311 billion attacks against web applications and APIs, with 230 billion attacks against e-commerce applications alone. What do attacks against APIs look like? Many of them are traditional types of attacks, such as SQL and command injection, server-side request forgery (SSRF), and denial-of-service attacks (DoS). But we are also seeing a growing trend toward more sophisticated attacks, such as fuzzing and abuse of vulnerable business logic and flows. According to research by Imperva, business logic exploits now account for the larg- est percentage of API attacks (27%). Examples include business logic–based DoS attacks (exploiting anti-patterns such as improper pagination), data scraping, and scalping. Threat actors exploit business flow vulnerabilities by taking advantage of design flaws in our APIs. In the real world, these types of attacks cause most breaches.xiv
PREFACE xvIn January 2024, a threat actor scraped and leaked the personal details of more than 15 million users of Trello, the popular project management platform, without break- ing a single security protocol or gaining unauthorized access. Also, for many years, the United Kingdom’s Driver and Vehicle Standards Agency (DVSA) has been fighting scalpers who buy all available driving-test slots and resell them at much higher prices. These are but some examples of a growing trend in the current cybersecurity landscape. Why are API attacks such a big problem? They are difficult to detect and mitigate. Research by Salt Security shows that 95% of API attacks come from authenticated users. For all intents and purposes, modern threat actors look and feel like legitimate users when they launch an attack against your API. If you have a rate-limiting policy, they’ll comply with it; if you use CAPTCHA challenges, they’ll solve them; if you require the use of a standard user agent, they’ll mock it. Modern threat actors’ modus operandi means they often go undetected by tradi- tional threat detection and protection tools such as web application firewalls (WAFs). The critical question for us is, can we do anything to protect our APIs against such threats? Yes we can! The solution to modern sophisticated threats is to shift left on security and embrace security by design with a robust zero-trust model, all of which this book teaches you.
acknowledgments Writing this book was an incredibly satisfying and fulfilling effort but also full of chal- lenges and unexpected difficulties. I’m thrilled to be writing these pages, and I’m not overstating the facts when I say that this wouldn’t be the case if not for the invaluable support I’ve received from family members, colleagues, my publisher, and the community. I benefited enormously from people who contributed ideas for the book and pro- vided feedback on various chapters and drafts. Special thanks go to Corey J. Ball, Dana Epp, Katie Paxton Fear, Teresa Pereira, Frank Kilcommins, Erik Wilde, David Roldán, Alberto Cabrero, Bandana Kaur, Al-Amir Badmus, Mayur Pandya, Tushal Padsala, Colin Domoney, Radu Popa, Alex Martelli, Jason McDonald, Naomi Ceder, Alex Aki- mov, Emmanuel Paraskakis, Mark de Rijk, Carlos Villanúa Fernández, Jason Harmon, Jacob Ideskog, Travis Spencer, Michał Trojanowski, Karo Moilanen, Ikenna Nwaiwu, Jędrzej Kardach, Tristan Kalos, Dmitry Dygalo, Mehdi Medjaoui, and Kelvin Meeks. I’m also indebted to my colleagues at APIsec, especially Raj Ramanatham, Mohsin Niyazi, Feroz Iqbal, Dan Barahona, Dave Piskai, Jesse Freeman, Alex Rifman, Faizel Lakhani, and the whole community at APIsec University. Since 2023, I’ve presented drafts and ideas from the book at various conferences, including PyCon US, EuroPython, OWASP Global AppSec, apidays, API Conference, the Platform Summit, and various podcasts and meetups. I want to thank everyone who attended my presentations and gave me valuable feedback. I also want to thank the attendees of my workshops at microapis.io for their thoughtful comments on the book. I want to express my gratitude to my acquisitions editor, Andy Waldron. He did a brilliant job of helping me get my book proposal in good shape and keeping the book focused on relevant topics. He also supported me tirelessly to promote the book and helped me reach a wider audience.xvi
ACKNOWLEDGMENTS xvii The book you now have in your hands is readable and understandable thanks to the invaluable work of my development editor, Marina Michaels, who went far beyond and then some more to help me write a better book. She did an outstanding job of helping me improve my writing style and keeping me on track and motivated. I also want to thank the rest of the Manning team who were involved in the pro- duction of this book, including Melissa Ice, Radmila Ercegovac, Robin Campbell, Aira Dučić, Ian Hough, Ana Romac, Sam Wood, Rebecca Rinehart, Keri Hales, Aleksandar Dragosavljević, Mihaela Batinic, Azra Dedić, Stjepan Jureković, and Matko Hrvatin, as well as the production team who helped shape this book into its final format. I also thank Marjan Bace for betting on this book and giving it a chance. While working on this book, I had the opportunity to receive detailed, outstanding feedback from the most amazing group of reviewers, including Aamiruddin Syed, Adalbert Jurkiewicz, Advait Patel, Akhilesh Keshap, Aleksei Sharypov, Amitabh Chee- koth, Anil Kumar Moka, Anirudhan Sudarsan, Anthony Staunton, Anupam Mehta, Anurag Malik, Anusha Nerella, Aparna Achanta, Arun Kumar R, Asaad Saad, Astha Puri, Bhanu Sekhar Guttikonda, Colin Domoney, Datta Snehith Dupakuntla Naga, David Roldán Martínez, Denis Saripov, Divya Parashar, Durga Krishnamoorthy, Evgeny Borovikov, Ganesh Swaminathan, Gilberto Taccari, Harsh Gupta, Hilde Van Gysel, Jereme Allen, Karan Kumar Ratra, Karol Skorek, Karthikeyan Magarajan, Krutik Poo- jara, Kushal Thakkar, Manas Kulkarni, Manjunath Ravi, Manuel Vidaurre, Maria Teresa Pereira, Mehmet Yilmaz, Mozhar Alhosni, Naman Jain, Narayanan Jayaratcha- gan, Payam Pourashraf, Prachit Kurani, Pradyumna Kodgi, Pragya Keshap, Prasanna Jatla, Praveen Chinnusamy, Radu Popa, Raja Chattopadhyay, Raj, Rajiv Moghe, Rakesh Kumar Pal, Ravi Teja, Sai Chiligireddy, Saketh Patibandla, Samarth Shah, Samer H, Sankalp Kumar, Satish Prahalad Gururujan, Senthil Bala, Shivaprasad Sankesha Narayana, Shyam Balagurumurthy Viswanathan, Sibasis Padhi, Simone Sguazza, Siri Varma Vegiraju, Sriram Macharla, Sudhanva Hebbale, Surya Prakash, Tannu Jiwnani, Udy Dhansingh, Ujjwal Verma, and Venkata Thummala. Their feedback was thorough and of exceptional quality, and without a glimmer of doubt, it allowed me to write the best possible version of this book. Since the book went into MEAP, I’ve been blessed by the words of encouragement and feedback that many of my readers sent me through LinkedIn and by email. I also want to thank the brilliant community of readers who actively participated in Man- ning’s liveBook platform and left invaluable feedback for improving the content. Finally, thank you, dear reader, for acquiring a copy of my book. I hope that you find this book useful and informative and that you enjoy reading it as much as I enjoyed writing it. I love to hear from my readers, and I’d be delighted if you shared your thoughts about the book with me.
about this book The goal of this book is to teach you how to secure your APIs. You’ll learn about the most common exploits hackers use to breach APIs and how to prevent them through secure API design, implementation, and operations. You’ll learn to threat-model risks for your APIs; create a zero-trust security strategy; automate your security-testing pro- cess; keep your attack surface under control; use observability for threat detection; and apply the highest, most advanced industry standards for authentication, authori- zation, and data validation. Who should read this book This book is helpful for software developers, architects, technical leaders, QA engi- neers, and product owners who work with APIs. The book covers advanced topics at the intersection between APIs and cybersecurity, but all concepts are explained in detail and in accessible language, with plenty of examples and illustrations and emphasis on the business impact of every API vulnerability. Therefore, the book should be accessible to both technical and nontechnical readers. As I emphasize throughout the book, API security is everybody’s job, and tackling it properly requires a strong alignment among business, product, and technical teams. I hope that this book helps create such alignment by being accessible to all stakeholders. The coding examples in the book are in Python, but you don’t need to know the language to follow along with them because every listing is explained thoroughly. The GitHub repository for this book contains detailed instructions on setting up the envi- ronment for every example and running the code.xviii
ABOUT THIS BOOK xixHow this book is organized: A road map The book is divided into 12 chapters. Chapters 1–3 introduce the main concepts in API security and lay out the principles for building and delivering secure APIs. The following chapters analyze the main types of security vulnerabilities (chapters 4–5), how to prevent them (chapters 6–10), how to detect threats (chapter 11), and how to automate API security testing (chapter 12). Here’s a detailed breakdown:  Chapter 1 explains what API security is, why APIs are the main attack vector and most common source of breaches on the internet, and how the principles of API security by design help you mitigate those risks.  Chapter 2 explains how you lay out an API security strategy that aligns with your organization’s business goals. It also illustrates step by step how to threat-model your APIs and what best practices to follow when designing an API security program.  Chapter 3 takes a deep dive into the foundational principles of API security. It explains what it truly means to shift left your security strategy and how to imple- ment a zero-trust model for APIs, as well as the importance of documenting your APIs before building them.  Chapter 4 explains the most common authentication and authorization vulner- abilities from the Open Worldwide Application Security Project (OWASP) top 10 API Security Risks, including broken object-level authorization (BOLA), bro- ken authentication, broken object property-level authorization (BOPLA), bro- ken function-level authorization (BFLA), and unrestricted access to sensitive business flows. Every vulnerability is explained in simple language, exemplified with real-world cases, and illustrated with code listings.  Chapter 5 explains the most common API configuration and management vul- nerabilities from the OWASP top 10 API security risks, including unrestricted resource consumption, SSRF, security misconfiguration, improper inventory management, and unsafe consumption of APIs. As in chapter 4, every vulnera- bility is explained in accessible language, including real-world examples and detailed code listings.  Chapter 6 explains how to tackle API security by design. It illustrates common design flaws (such as the use of predictable identifiers, unconstrained user input, optional properties, and unsafe user flows) that threat actors can exploit to abuse and breach our APIs, and it provides patterns that prevent such exploits.  Chapter 7 is a deep dive into the foundations of API authentication and autho- rization protocols and standards, including Open Authorization (OAuth), OpenID Connect (OIDC), JSON Web Tokens (JWTs), and sender-constrained