📄 Page
1
Secure RESTful APIs Simple Solutions for Beginners — Massimo Nardone
📄 Page
2
Apress Pocket Guides
📄 Page
3
Apress Pocket Guides present concise summaries of cutting-edge developments and working practices throughout the tech industry. Shorter in length, books in this series aims to deliver quick-to-read guides that are easy to absorb, perfect for the time-poor professional. This series covers the full spectrum of topics relevant to the modern industry, from security, AI, machine learning, cloud computing, web development, product design, to programming techniques and business topics too. Typical topics might include: • A concise guide to a particular topic, method, function or framework • Professional best practices and industry trends • A snapshot of a hot or emerging topic • Industry case studies • Concise presentations of core concepts suited for students and those interested in entering the tech industry • Short reference guides outlining ‘need-to-know’ concepts and practices. More information about this series at https://link.springer.com/ bookseries/17385.
📄 Page
4
Secure RESTful APIs Simple Solutions for Beginners Massimo Nardone
📄 Page
5
Secure RESTful APIs: Simple Solutions for Beginners ISBN-13 (pbk): 979-8-8688-1284-2 ISBN-13 (electronic): 979-8-8688-1285-9 https://doi.org/10.1007/979-8-8688-1285-9 Copyright © 2025 by Massimo Nardone This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director, Apress Media LLC: Welmoed Spahr Acquisitions Editor: Melissa Duffy Development Editor: Laura Berendson Editorial Assistant: Gryffin Winkler Cover designed by eStudioCalamar Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 New York Plaza, Suite 4600, New York, NY 10004-1562, USA. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail booktranslations@springernature.com; for reprint, paperback, or audio rights, please e-mail bookpermissions@springernature.com. Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub. For more detailed information, please visit https://www.apress. com/gp/services/source-code. If disposing of this product, please recycle the paper Massimo Nardone Helsinki, Finland
📄 Page
6
This book is dedicated to the memory of my loving late father Giuseppe. Your support, your education, your values made me the man I am now. You will be loved and missed forever. I also would like to dedicate this book to my children Luna, Leo and Neve. Your love and support mean everything to me. —Massimo
📄 Page
7
vii Table of Contents About the Author ���������������������������������������������������������������������������������xi About the Technical Reviewer �����������������������������������������������������������xiii Acknowledgments ������������������������������������������������������������������������������xv Introduction ��������������������������������������������������������������������������������������xvii Chapter 1: Introduction to RESTful APIs �����������������������������������������������1 What Are the Major Differences Between REST and SOAP? ���������������������������������1 How to Combine REST and API to Create RESTful API? �����������������������������������������2 What Is JSON? ������������������������������������������������������������������������������������������������������3 What Are the RESTful API Key Concepts? �������������������������������������������������������������4 What Are the HTTP Methods or Verbs? �����������������������������������������������������������������5 What Are the HTTP Request Status Codes? ����������������������������������������������������������6 Problem �����������������������������������������������������������������������������������������������������������7 Solution �����������������������������������������������������������������������������������������������������������7 Problem �����������������������������������������������������������������������������������������������������������8 Solution �����������������������������������������������������������������������������������������������������������8 Problem �����������������������������������������������������������������������������������������������������������9 Solution �����������������������������������������������������������������������������������������������������������9 Summary�������������������������������������������������������������������������������������������������������������13
📄 Page
8
viii Chapter 2: Key Security Concerns and Risks for RESTful APIs �����������15 What Are the RESTful API Key Security Concerns? ���������������������������������������������15 What Are the Most Common Sources of Risk? ����������������������������������������������������17 What Are the Common Risks Associated with RESTful APIs? �����������������������������18 What Are the Most Common RESTful APIs Risk Mitigation Strategies? ��������������21 Summary�������������������������������������������������������������������������������������������������������������22 Chapter 3: Data Protection and Validation for RESTful APIs ���������������23 What Is Data Protection?�������������������������������������������������������������������������������������23 1� What Are the Main Key Objectives of Data Protection? �����������������������������23 2� Why Is Data Protection Important? ������������������������������������������������������������24 3� What Are the Most Common Data Protection Practices? ���������������������������24 4� What Are the Most Important Types of Data Protection? ���������������������������25 RESTful API Data Security �����������������������������������������������������������������������������������26 5� What Are the Key Principles for RESTful API Data Security? ���������������������26 6� What Does RESTful API Security Look Like? ����������������������������������������������33 Why Do Data Validation for RESTful APIs and How? �������������������������������������������39 Problem ���������������������������������������������������������������������������������������������������������40 Solution ���������������������������������������������������������������������������������������������������������40 7� How to Perform Data Validation in RESTful APIs? �������������������������������������41 Summary�������������������������������������������������������������������������������������������������������������43 Chapter 4: JSON Web Token (JWT) Authentication �����������������������������45 What Is JSON Web Token (JWT)? ������������������������������������������������������������������������45 1� How Do We Create a New DB and User in PostgreSQL? ���������������������������������49 2� How Do We Create a New Project with Spring Initializr? ��������������������������������50 3� How Do We Configure the application�properties File with Information About the DB Used, the JPA/JWT, and Server Configuration? �������������������������56 4� How Do We Generate a JWTsecret Value for Our Project? ������������������������������57 Table of ConTenTs
📄 Page
9
ix 5� How Do We Create New APIs for Our Project? ������������������������������������������������57 6� How Do We Create New User and Role Models for Our Project? ��������������������58 7� How Do We Create New Role Java Classes for Our Project? ��������������������������58 8� How Do We Create New Repository Java Classes for Our Project? ����������������62 9� How Do We Create a JWT Authentication Filter for Our Project? ��������������������68 JWT Authentication Filter ������������������������������������������������������������������������������70 10� How Do We Create the Spring REST APIs Controller? �����������������������������������77 11� How to Test Our Project? �������������������������������������������������������������������������������85 Summary�������������������������������������������������������������������������������������������������������������89 Chapter 5: Securing OAuth2 Authentication Flow ������������������������������91 RESTful APIs and OAuth 2�0 ��������������������������������������������������������������������������������91 OAuth2 Introduction ��������������������������������������������������������������������������������������������92 OAuth2 Security ��������������������������������������������������������������������������������������������������94 1� How to Integrate OAuth2 with Spring Security for RESTful APIs? �������������������96 2� What Is OAuth2 Login? ����������������������������������������������������������������������������������100 3� How to Develop an OAuth2 and Spring Security Project? �����������������������������101 4� What Are the Needed OAuth2 and Spring Security Dependencies? ��������������103 5� How to Create the Spring Security SpringSecurityConfiguration Java Class to Use OAuth2? ���������������������������������������������������������������������������108 6� How to Configure Google to Be Accessed via OAuth 2�0 Login? �������������������110 7� How to Generate OAuth2 IDs and Secret Keys for Google? ���������������������������110 Summary�����������������������������������������������������������������������������������������������������������117 Index �������������������������������������������������������������������������������������������������119 Table of ConTenTs
📄 Page
10
xi About the Author Massimo Nardone has more than 29 years of experience in information and cybersecurity for IT/OT/IoT/IIoT, web/mobile development, cloud, and IT architecture. His true IT passions are security and Android. He holds an MSc in computing science from the University of Salerno, Italy. Throughout his working career, he has held various positions, starting as a programming developer and then security teacher, PCI QSA, auditor, assessor, lead IT/ OT/SCADA/cloud architect, CISO, BISO, executive, program director, OT/IoT/IIoT security competence leader, VP of OT security, etc. In his last working engagement, he worked as a seasoned cyber and information security executive, CISO, and OT, IoT, and IIoT security competence leader, helping many clients to develop and implement cyber, information, OT, and IoT security activities. He is currently working as Vice President of OT security for SSH Communications Security. He is a author of numerous Apress books, including Secure RESTful APIs, Cybersecurity Threats & Attacks in Gaming Industry, Pro Spring Security 6, Pro JPA 2 in Java EE 8, and Pro Android Games, and has reviewed more than 75 titles.
📄 Page
11
xiii Naga Santhosh Reddy Vootukuri is a senior software engineering manager at Microsoft, working within the Cloud Computing + AI (C+AI) organization. With over 17 years of experience spanning across three countries (India, China, and the USA), Naga has developed a rich and varied technical background. His expertise lies in cloud computing, artificial intelligence, distributed systems, and microservices. At Microsoft, Naga leads the Azure SQL Database team, focusing on optimizing SQL deployment processes to enhance the efficiency and scalability of services for millions of databases globally. He is responsible for the entire infrastructure of the Azure SQL deployment space and has been instrumental in the development of Master Data Services, a master data management solution by Microsoft. This project earned him recognition for delivering impactful solutions to complex data challenges. Naga has authored and published numerous research articles in peer- reviewed and indexed journals. He is a senior member of IEEE and contributes technical articles as a Core MVB member at DZone, engaging with millions of active readers. He also serves as an editorial board member for a highly reputed science journal (SCI), where he reviews research articles on cloud computing and AI. In addition to his professional roles, Naga is deeply involved in the tech community as a speaker, book reviewer for Apress, and contributor to platforms like DZone and the Microsoft Tech Community. He recently About the Technical Reviewer
📄 Page
12
xiv served as an IEEE AI Summit committee chair and lightning talk chair and selected some of the best lightning talks. He also delivered AI-related workshops and received an AI innovator award from Washington Senator Lisa Wellman. He also served as a judge for the Globee Awards, Fabric and AI Learning Hackathon, and Cosmos DB and AI Hackathon on devpost, which further showcased his expertise and commitment to the advancement of technology. abouT The TeChniCal RevieweR
📄 Page
13
xv Many thanks go to my wonderful children Luna, Leo and Neve for your continuos support You are and will be always the most beautiful reason of my life. I want to thank my beloved late father Giuseppe and my mother Maria, who always supported me and loved me so much. I will love and miss both of you forever. My beloved brothers, Roberto and Mario, for your endless love and for being the best brothers in the world. Brunaldo and Kaisa for bringing joy and happiness to Luna and Leo. Thanks a lot to Melissa Duffy for giving me the opportunity to work as writer on this book, to Sowmya Thodur for doing such a great job during the editorial process and supporting me all the time, and of course Naga Santhosh Reddy Vookuri the technical reviewer of this book, for helping me to make a better book. —Massimo Acknowledgments
📄 Page
14
xvii Introduction RESTful APIs are a common method for enabling communication between different software systems. As these Application Programming Interfaces (APIs) often handle sensitive data and critical operations, securing them is paramount. This section covers key strategies and best practices for securing RESTful APIs. This book is for RESTful APIs beginner developers who want to learn about applying security when developing REST APIs applications. It will be a practical pocket guide and help developers understand how to develop and deploy security when dealing with RESTful APIs for authentication and authorization, data protection, threat detection and prevention, etc. This book is a tutorial and reference that guides you through the implementation of the security features for a Java web application by presenting consistent solutions to security issues with RESTful APIs. This book explores a comprehensive set of functionalities to implement industry-standard authentication and authorization mechanisms for Java applications, providing examples on how to develop customized RESTful APIs secure apps dealing with data validation, JSON Web Token (JWT), and Open Authorization 2.0 (OAuth 2.0). Prerequisites The examples in this book are all built with Java 17+ and Maven 3.9.9. Spring Security 6 was the version used throughout the book. Tomcat Web Server v11 was used for the different web applications in the book, mainly through its Maven plugin, and the laptop used was a ThinkPad Yoga 360 with 8GB of RAM. All the projects were developed using the IntelliJ IDEA Ultimate 2024.2.4.
📄 Page
15
xviii You are free to use your own tools and operating system. Because everything is Java based, you should be able to compile your programs on any platform without problems. Downloading the Code The code for the examples given in this book is available via the Download Source Code button located at https://github.com/Apress/Secure- RESTful-APIs. inTRoduCTion
📄 Page
16
1© Massimo Nardone 2025 M. Nardone, Secure RESTful APIs, Apress Pocket Guides, https://doi.org/10.1007/979-8-8688-1285-9_1 CHAPTER 1 Introduction to RESTful APIs This chapter will explain what RESTful APIs are. REST, which stands for Representational State Transfer, is an architectural style for designing networked applications. REST has become the predominant way of designing APIs (Application Programming Interfaces) for web-based applications. What Are the Major Differences Between REST and SOAP? SOAP (Simple Object Access Protocol) is a protocol for exchanging structured information in the implementation of web services. It uses XML as its message format and relies on application layer protocols like HTTP or SMTP for message negotiation and transmission. SOAP is designed to enable communication between applications running on different operating systems, with different technologies, and written in different programming languages. REST (Representational State Transfer) and SOAP (Simple Object Access Protocol) are two different architectural styles for designing APIs.
📄 Page
17
2 REST is more flexible and simpler, making it the preferred choice for most modern applications. SOAP, with its built-in security and transaction handling, remains valuable for enterprise-grade and mission-critical applications. Table 1-1 shows the major differences between REST and SOAP. Table 1-1. Major differences between REST and SOAP Feature REST SOAP Protocol HTTP HTTP, SMTP, TCP Data format JSON, XML XML Complexity Simple Complex Scalability Highly scalable Less scalable Performance Faster Slower Use case Web, mobile APIs Enterprise applications How to Combine REST and API to Create RESTful API? An API (Application Programming Interface) is a set of rules and protocols that enable different software applications to communicate and interact with each other. It serves as a bridge between systems, allowing them to exchange data or functionality without needing to understand the details of each other’s implementation. REST APIs provide a structured and standardized way for different software applications to communicate over the Internet. They’ve become the backbone of modern web and mobile applications, enabling seamless integration and interaction between various services and systems. REST APIs allow different software applications to communicate and interact with each other over the Internet using standard HTTP methods. CHAPTEr 1 INTrOduCTION TO rESTFuL APIS
📄 Page
18
3 A RESTful API, therefore, refers to an API that is designed and implemented in compliance with the principles of REST. Both REST and RESTful APIs are widely used for building modern web applications and services. While the terms are often used interchangeably, a RESTful API ensures full adherence to REST principles, making it a more precise implementation of the REST architecture. HATEOAS stands for Hypermedia As The Engine Of Application State. It is a constraint of the REST (Representational State Transfer) architectural style that enables dynamic and self-descriptive interactions in a RESTful API. With HATEOAS, clients interact with a RESTful API entirely through hyperlinks provided dynamically by the server in the responses, rather than hardcoding the API’s paths and operations. Table 1-2 describes the major differences between REST API and RESTful API. Table 1-2. Differences between REST API and RESTful API Aspect REST API RESTful API Definition Any API that uses rEST principles Strictly adheres to all rEST principles Flexibility More flexible in design approach Fully compliant with rEST constraints HATEOAS May not include HATEOAS Includes HATEOAS for navigation What Is JSON? JSON (JavaScript Object Notation) is a lightweight, text-based data format used for representing structured data. It is easy to read and write for humans and easy to parse and generate for machines, making it a popular choice for data exchange in web applications, APIs, and configuration files. CHAPTEr 1 INTrOduCTION TO rESTFuL APIS
📄 Page
19
4 Here are the key features of JSON: 1. Lightweight: Minimal syntax and simple structure. 2. Language Independent: While derived from JavaScript, JSON is supported by most programming languages. 3. Human-Readable: Designed to be easily read and understood by humans. 4. Versatile: Can represent complex nested data structures like objects and arrays. What Are the RESTful API Key Concepts? • Resource-Oriented: • In REST, every piece of data or functionality is treated as a resource, identified by a unique URI (Uniform Resource Identifier). • Examples are /users, /products, and /orders. • Client–Server Architecture: • REST separates the client (the application making the request) from the server (the application fulfilling the request), which allows them to evolve independently. • Stateless Communication: • Each API request contains all necessary information (authentication, state, etc.). • The server does not store session information about clients, ensuring scalability. CHAPTEr 1 INTrOduCTION TO rESTFuL APIS
📄 Page
20
5 • HTTP Methods/Verbs: RESTful APIs rely on standard HTTP methods to perform operations on resources: • GET • POST • PUT • DELETE • PATCH • Representation Formats: • RESTful APIs commonly use JSON (JavaScript Object Notation) and XML to represent data. • JSON is preferred due to its simplicity and compatibility with modern web technologies. • Uniform Interface: • REST enforces a standardized interface, ensuring consistent interaction between clients and servers. What Are the HTTP Methods or Verbs? In RESTful APIs, HTTP methods (also known as verbs) define the type of operation to perform on a given resource. HTTP methods or verbs are fundamental to the design and operation of RESTful APIs. They provide a standardized way to perform actions on resources, ensuring clear communication between clients (e.g., web apps, mobile apps) and servers. Each method plays a critical role in defining the behavior of a RESTful API and how it interacts with resources. CHAPTEr 1 INTrOduCTION TO rESTFuL APIS