M A N N I N G Laurentiu Spilca Foreword by Joe Grandja ˘` SECOND EDITION
Praise for the first edition “One of the best resources you will come across for Spring Security 6—pragmatic and easy to follow, covering all aspects you are likely to use in production.” —Amarjit Bhandal, Senior Java Developer “One of the best technical books I read in the last year. It surprises me how well it teaches the Spring Security Framework!” —Simone Sguazza, Assistant Researcher, University of Applied Sciences and Arts of Southern Switzerland “Provides an excellent panoramic view of the Spring Security Framework!” —Sachin Handiekar, Lead Software Engineer at JPMC “Unrivaled in its depth and clarity, it stands as the ultimate authority—an indispensable guide for mastering the intricacies of Spring Security.” —Najeeb Arif, Senior Consultant at Thoughtworks “A must-have if you need to configure Spring Security. And almost every Spring application needs Spring Security.” —Luigi Rubino, Software Architect at Unimatica S.p.A.
MANN I NG Shelter ISland Spring Security in Action, Second Edition LAURENȚIU SPILCĂ
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 © 2024 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. ∞ Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 ISBN 9781633437975 Printed in the United States of America 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. Development editor: Marina Michaels Technical editor: Jean-Francois Morin Review editor: Dunja NikitoviÊ Production editor: Andy Marinkovich Copy editor: Lana Todorovic-Arndt Proofreader: Melody Dolab Technical proofreader: Jean-Francois Morin Typesetter: Tamara ŠveliÊ SabljiÊ Cover designer: Marija Tudor
v Development editor: Marina Michaels Technical editor: Jean-Francois Morin Review editor: Dunja NikitoviÊ Production editor: Andy Marinkovich Copy editor: Lana Todorovic-Arndt Proofreader: Melody Dolab Technical proofreader: Jean-Francois Morin Typesetter: Tamara ŠveliÊ SabljiÊ Cover designer: Marija Tudor brief contents Part 1 Say hello to Spring Security ....................1 1 ■ Security today 3 2 ■ Hello, Spring Security 15 Part 2 Configuring authentication ....................41 3 ■ Managing users 43 4 ■ Managing passwords 68 5 ■ A web app’s security begins with filters 83 6 ■ Implementing authentications 101 Part 3 Configuring authorization .................... 135 7 ■ Configuring endpoint-level authorization: Restricting access 137 8 ■ Configuring endpoint-level authorization: Applying restrictions 156 9 ■ Configuring CSRF protection 175 10 ■ Configuring CORS 199 11 ■ Implementing authorization at the method level 209 12 ■ Implementing filtering at the method level 235
vi brief contents Part 4 Implementing OAuth 2 and OpenID Connect ..................................................... 255 13 ■ What are OAuth 2 and OpenID Connect? 257 14 ■ Implementing an OAuth 2 authorization server 275 15 ■ Implementing an OAuth 2 resource server 297 16 ■ Implementing an OAuth 2 client 324 Part 5 Going reactive .......................................... 345 17 ■ Implementing security in reactive applications 347 Part 6 Testing security configurations ........... 371 18 ■ Testing security configurations 373
vii contents foreword xiii preface xv acknowledgments xvii about this book xviii about the author xxi about the cover illustration xxiii Part 1 Say hello to Spring Security ....................1 1 Security today 3 1.1 Discovering Spring Security 5 1.2 What is software security? 7 1.3 Why is security important? 12 1.4 What will you learn in this book? 13 2 Hello, Spring Security 15 2.1 Starting your first project 16 2.2 The big picture of Spring Security class design 20 2.3 Overriding default configurations 25 Customizing user details management 25 ■ Applying authorization at the endpoint level 29 ■ Configuring in different ways 32 ■ Defining custom authentication logic 34 Using multiple configuration classes 38
viii contents Part 2 Configuring authentication ....................41 3 Managing users 43 3.1 Implementing authentication in Spring Security 44 3.2 Describing the user 47 Describing users with the UserDetails contract 47 ■ Detailing on the GrantedAuthority contract 48 ■ Writing a minimal implementation of UserDetails 49 ■ Using a builder to create instances of the UserDetails type 51 ■ Combining multiple responsibilities related to the user 53 3.3 Instructing Spring Security on how to manage users 56 Understanding the UserDetailsService contract 56 Implementing the UserDetailsService contract 57 Implementing the UserDetailsManager contract 60 4 Managing passwords 68 4.1 Using password encoders 68 The PasswordEncoder contract 69 ■ Implementing your PasswordEncoder 70 ■ Choosing from the provided PasswordEncoder implementations 72 ■ Multiple encoding strategies with DelegatingPasswordEncoder 74 4.2 Taking advantage of the Spring Security Crypto module 78 Using key generators 79 ■ Encrypting and decrypting secrets using encryptors 80 5 A web app’s security begins with filters 83 5.1 Implementing filters in the Spring Security architecture 85 5.2 Adding a filter before an existing one in the chain 88 5.3 Adding a filter after an existing one in the chain 91 5.4 Adding a filter at the location of another in the chain 93 5.5 Filter implementations provided by Spring Security 98 6 Implementing authentications 101 6.1 Understanding the AuthenticationProvider 103 Representing the request during authentication 104 Implementing custom authentication logic 105 ■ Applying custom authentication logic 108
ixcontents 6.2 Using the SecurityContext 112 Using a holding strategy for the security context 114 Using a holding strategy for asynchronous calls 116 Using a holding strategy for standalone applications 118 Forwarding the security context with DelegatingSecurityContextRunnable 119 Forwarding the security context with DelegatingSecurityContextExecutorService 121 6.3 Understanding HTTP Basic and form-based login authentications 123 Using and configuring HTTP Basic 124 ■ Implementing authentication with form-based login 127 Part 3 Configuring authorization .................... 135 7 Configuring endpoint-level authorization: Restricting access 137 7.1 Restricting access based on authorities and roles 139 Restricting access for all endpoints based on user authorities 140 Restricting access for all endpoints based on user roles 148 Restricting access to all endpoints 153 8 Configuring endpoint-level authorization: Applying restrictions 156 8.1 Using the requestMatchers() method to select endpoints 157 8.2 Selecting requests to apply authorization restrictions 162 8.3 Using regular expressions with request matchers 169 9 Configuring CSRF protection 175 9.1 How CSRF protection works in Spring Security 176 9.2 Using CSRF protection in practical scenarios 182 9.3 Customizing CSRF protection 188 10 Configuring CORS 199 10.1 How does CORS work? 200
x contents 10.2 Applying CORS policies with the @CrossOrigin annotation 206 10.3 Applying CORS using a CorsConfigurer 207 11 Implementing authorization at the method level 209 11.1 Enabling method security 210 Understanding call authorization 211 ■ Enabling method security in your project 213 11.2 Applying preauthorization rules 214 11.3 Applying postauthorization rules 219 11.4 Implementing permissions for methods 223 12 Implementing filtering at the method level 235 12.1 Applying prefiltering for method authorization 236 12.2 Applying postfiltering for method authorization 242 12.3 Using filtering in Spring Data repositories 247 Part 4 Implementing OAuth 2 and OpenID Connect ..................................................... 255 13 What are OAuth 2 and OpenID Connect? 257 13.1 The big picture of OAuth 2 and OpenID Connect 259 13.2 Using various token implementations 262 Using opaque tokens 263 ■ Using non-opaque tokens 264 13.3 Obtaining tokens through various grant types 266 Getting a token using the authorization code grant type 266 Applying PKCE protection to the authorization code grant type 269 ■ Getting a token with the client credentials grant type 270 ■ Using refresh tokens to get new access tokens 271 13.4 What OpenID Connect brings to OAuth 2 272 13.5 The sins of OAuth 2 273 14 Implementing an OAuth 2 authorization server 275 14.1 Implementing basic authentication using JSON web tokens 276 14.2 Running the authorization code grant type 284
xicontents 14.3 Running the client credentials grant type 290 14.4 Using opaque tokens and introspection 292 14.5 Revoking tokens 295 15 Implementing an OAuth 2 resource server 297 15.1 Configuring JWT validation 298 15.2 Using customized JWTs 306 15.3 Configuring token validation through introspection 311 15.4 Implementing multitenant systems 317 16 Implementing an OAuth 2 client 324 16.1 Implementing OAuth 2 login 326 Implementing authentication with a common provider 326 Giving the user more possibilities 329 ■ Using a custom authorization server 330 ■ Adding flexibility to your configurations 333 ■ Managing authorization for an OAuth 2 login 335 16.2 Implementing an OAuth 2 client 336 Part 5 Going reactive .......................................... 345 17 Implementing security in reactive applications 347 17.1 What are reactive apps? 348 17.2 User management in reactive apps 353 17.3 Configuring authorization rules in reactive apps 358 Applying authorization at the endpoint layer in reactive apps 358 Using method security in reactive apps 364 17.4 Creating a reactive OAuth 2 resource server 367 Part 6 Testing security configurations ........... 371 18 Testing security configurations 373 18.1 Using mock users for tests 376 18.2 Testing with users from a UserDetailsService 383 18.3 Using custom Authentication objects for testing 384 18.4 Testing method security 388
xii contents 18.5 Testing authentication 390 18.6 Testing CSRF configurations 394 18.7 Testing CORS configurations 395 18.8 Testing reactive Spring Security implementations 396 appendix A Links to official documentation 399 appendix B Further reading 400 index 403
xiii foreword I first got to know Laurențiu Spilcă in 2022, when we virtually collaborated on a Spring- One presentation, and I was happy to finally meet him in person at Devoxx 2023 in Bel- gium. I was excited when he asked me to write this foreword. I’ll start with an excerpt from the book: “Applying a framework incorrectly leads to a less maintainable application. What is worse, sometimes those who fail in using the framework believe that it’s the framework’s fault.” This is such an important message! Over the years, I’ve gotten feedback from the community on several occasions that Spring Security is difficult to understand and has a steep learning curve. Whether or not that is the case, if you dive deep into the framework internals and really gain a profound understanding of the authentication architecture, you will learn how to take advantage of the framework’s capabilities, and ultimately, it will become easier to use. This is where the book truly hammers it home and dives deep into Spring Security’s authentication architecture, providing clear dia- grams accompanied by detailed explanations of each of the main components that collaborate in the authentication-processing flow. Throughout the book, Laurențiu makes clever use of analogies to help simplify the topic at hand. I really like the analogy used in the authentication architecture section, as he sums it up nicely: “If you know this architecture, you’re like a chef who knows their ingredients and can put together any recipe.” The collaboration diagram used to demonstrate how authentication processing works is excellent. It provides a high-level depiction of the flow and details the primary responsibility of each of the core components as it progresses throughout the book.
xiv foreword The content has a natural flow, starting off with very simple examples and progressing to more advanced examples without overwhelming the reader. After the book finishes examining the authentication architecture in detail, the next (logical) topic is authorization. This reminds me of a specific question that I repeatedly see in the community: “What is the difference between authority, role, and permission?” The book answers this question nicely as it provides very simple real-world examples of an authority, role, and permission, and how these can be associated with a user. It then progresses through general guidelines on how to model authorities in your application based on the functions available and the types of users of the system. Next, it uses these general principles and demonstrates how to define authorization rules in your Spring Security configuration to restrict access control. Part 4 covers the topics of OAuth 2 and OpenID Connect 1.0. I think it’s safe to state that the OAuth 2 and OpenID Connect 1.0 set of specifications is quite overwhelming, making it very difficult for anyone new to grasp their purpose and capabilities. How- ever, this book provides an excellent high-level overview of the core concepts (roles, authorization grant types, access token formats, etc.) defined in the specifications and correlates how these are implemented in Spring Security and Spring Authorization Server. I love the analogy in the book on how the OAuth 2 specification is very similar to accessing an office building, where you need an access card (with limited access) to enter the meeting room in the building. It goes through this real-world use case and refers to the different parts of the OAuth 2 system and the roles that each of them plays. It then builds a simple example using Spring Authorization Server along with Spring Security’s Client and Resource Server support. The examples start off minimally and then demonstrate how to configure clients to perform various grant type flows, for example, authorization code (with PKCE), client credentials, and refresh token. Then it demonstrates common configuration scenarios, for example, configuring opaque tokens and using token introspection and token revocation. Next, it takes it a step fur- ther and shows more advanced scenarios with regard to configuring multi-tenancy for resource servers. To sum it up, this book is a must-read for anyone looking to dive deep into Spring Security’s authentication architecture and framework internals, as it will ultimately empower you to take full advantage of the framework’s capabilities. —Joe Grandja, Spring Security Engineer, VMware by Broadcom
xv preface The journey through software development is an enthralling dance of building, learn- ing, teaching, and often, unlearning. Ever since I began my journey in 2007, I’ve found myself gracefully expanding my role from being solely a developer to being a devel- oper and trainer. While both roles have their unique charm, it’s the art of imparting knowledge, nurturing curiosity, and witnessing the aha moments of fellow learners that truly lights a fire in me. But let’s face it, the realms of development and training are deeply intertwined. To be a torchbearer, illuminating the way for others, one must first have their feet firmly rooted in the constantly evolving terrains of software application. Over the years, one realization stands out distinctly: while functional aspects of soft- ware might be its beating heart, nonfunctional attributes such as security, performance, and maintainability serve as its lifeline. It’s simpler to pinpoint a glitch in a function than to navigate the murky waters of security vulnerabilities or performance lags. No wonder many developers, seasoned or not, often hesitate when faced with these non- functional intricacies. Among these, security is not just paramount, but it’s imperative. And in the vast realm of security frameworks, Spring Security emerges as a frontrunner, given the wide- spread adoption and trustworthiness of the Spring ecosystem in the enterprise appli- cation domain. Yet, a glaring challenge remains—the steep learning curve associated with Spring Security. The plethora of scattered resources online often feels like puzzle pieces that refuse to fit cohesively, leading even the most tenacious of learners astray. It was these challenges, coupled with countless consultations witnessing improper or, even worse, vulnerable implementations of Spring Security, that sowed the seeds for the first edition of this book. My vision was clear: provide a guiding star to anyone, be it a Spring novice or aficionado, to master Spring Security.
xvi preface With the second edition, we delve deep into Spring Security, reflecting on the inno- vations, changes, and experiences since the first edition. We enhance what was, learn from what wasn’t, and introduce what’s now essential. It remains my earnest hope that this second edition of Spring Security in Action will serve not just as a book, but also as a trusted companion in your journey toward creating secure, robust applications. I envi- sioned this book as a beacon that ensures that you not only save time but also build with confidence, knowing your applications stand resilient against the ever-evolving threats of the digital realm.
xvii acknowledgments Creating this book has been a journey I couldn’t have embarked upon without the col- lective wisdom, support, and expertise of numerous exceptional individuals. First and foremost, a heartfelt thank you to Daniela, my wife and guiding light. Her insights, constant encouragement, and unwavering faith have been instrumental throughout this project. The entire team at Manning deserves a special mention. Their unwavering commit- ment and dedication have transformed this manuscript into the invaluable resource it is today. Among them, I’d like to particularly express my appreciation to Marina Micheals and Jean-François Morin. Their professionalism, support, and invaluable advice have significantly enriched this book. A hearty shoutout to my friend, Ioana Göz, the creative genius behind the illustra- tions. Her knack for translating my abstract thoughts into delightful visuals has added a unique charm to the pages, providing readers with occasional smiles amid the technical content. This book has greatly benefited from the meticulous eyes and feedback of numer- ous reviewers. Their keen observations and constructive feedback have been instru- mental in refining its content. A special thanks goes to the dedicated reviewers from Manning, Amarjit Bhandal, Asif Iqbal, Cosimo Damiano Prete, Geoff Williams, Javid Asgarov, Justin Reiser, Luigi Rubino, Manoj Kumar, Marcus Geselle, Michele Adduci, Mikael Byström, Mikhail Malev, Najeeb Arif, Patrick Wanjau, Richard Meinsen, Sachin Handiekar, Simeon Leyzerzon, and Simone Sguazza, and to my trusted circle of friends who lent their expertise. Lastly, to my colleagues and friends at Endava: your constant encouragement, thoughtful insights, and unwavering belief in my endeavors have been the silent forces driving me forward. I cherish and deeply value your support. To everyone who has touched this project, in ways big and small, please know that your contributions have been the threads weaving the tapestry of this book. Thank you!
xviii about this book Security is paramount in software development, and integrating it from the onset is essential. Spring Security in Action, Second Edition dives deeply into using Spring Security to infuse application-level security into your projects. Mastery of Spring Security and its correct application is indispensable for every developer. Delving into an application’s construction without this knowledge is a risk too great to take. Who should read this book? This book targets developers using the Spring Framework for enterprise applications. While I’ve tailored this book for those new to Spring Security, a foundational under- standing of the Spring Framework is necessary, including ¡ Using the Spring context ¡ Crafting REST endpoints ¡ Working with data sources Chapter 15 delves into security configurations for reactive applications. Hence, a prior understanding of reactive applications and their development using Spring is essen- tial. As we navigate the book, I’ll point you to supplementary resources to solidify or introduce necessary topics. All examples in this book use Java. Given the widespread adoption of Java in the Spring ecosystem, it’s assumed readers have a working knowledge of it. However, while some professionals might use languages like Kotlin, the foundation remains similar. The examples can be conveniently adapted to Kotlin if desired. If you feel you need a refresher on the prerequisites before starting with this book, I warmly recommend Spring Start Here (Manning, 2021), another book I wrote.
xixabout this book How this book is organized: A roadmap I crafted this book to guide you through the vast landscape of Spring Security, from fundamental concepts to more advanced areas. Each part of the book flows naturally into the next, making your journey of learning sequential and immersive. Here’s a brief breakdown: ¡ Part 1: Say hello to spring security In this part, I introduce you to the modern landscape of security and Spring Security. We’ll set the foundation by discussing the pivotal role of security in today’s digital age and how Spring Security addresses these challenges. ¡ Part 2: Configuring authentication Dive deeply into the core of authentication. I cover essential topics such as user management, password protocols, the crucial role of filters in web application security, and the implementation of authentication. ¡ Part 3: Configuring authorization We move from authentication to authorization. Together, we’ll explore endpoint-level authorizations, protective measures against threats such as CSRF, and managing CORS, and we’ll delve into intricate method-level authorizations and filtering. ¡ Part 4: Implementing OAuth 2 and OpenID Connect In this part, I guide you through the world of OAuth 2 and OpenID Connect. You’ll learn their significance and set up OAuth 2 servers, resource servers, and clients, thereby fortifying your application security. ¡ Part 5: Going reactive Here, I introduce you to the reactive programming paradigm, detailing how to secure reactive applications, so you can ensure your asynchronous operations remain tamper-proof. ¡ Part 6: Testing security configurations I emphasize the necessity of pre-deployment testing. We delve into the tech- niques to ensure your security configurations function precisely as intended. ¡ Appendixes Appendixes include resources for official documentation and further reading to supplement your learning and exploration. While I envisioned this book as a step-by-step journey, those with some prior experi- ence in Spring Security can navigate directly to their areas of interest. However, keep in mind that later chapters may reference concepts from earlier sections. If you’re already familiar with Spring Security basics, consider starting with part 3 or part 4 for OAuth 2 and OpenID insights. Those keen on reactive programming can jump to part 5.
xx about this book No matter where you start, make sure to grasp each concept thoroughly to benefit from the subsequent chapters. About the code This book provides over 70 projects, which we’ll work on starting with chapter 2 and up to chapter 18. When working on a specific example, I mention the name of the project that implements the example. My recommendation is that you try to write your own example from scratch together with the explanations in the book, and then only use the provided project to compare your solution with my solution. This approach will help you better understand the security configurations you’re learning. Each of the projects is built with Maven, making them easy to import to any IDE. I have used IntelliJ IDEA to write the projects, but you can choose to run them in Eclipse, STS, NetBeans, or any other tool of your choice. The appendix also serves as a refresher on how to create a Spring Boot project. This book contains many examples of source code, both in numbered listings and in line with normal text. In both cases, source code is formatted in a fixed-width font like this to separate it from ordinary text. In many cases, the original source code has been reformatted; we’ve added line breaks and reworked indentation to accommo- date the available page space in the book. In rare cases, even this was not enough, and listings include line-continuation markers (➥). Additionally, comments in the source code have often been removed from the listings when the code is described in the text. Code annotations accompany many of the listings, highlighting important concepts. You can get executable snippets of code from the liveBook (online) version of this book at https://livebook.manning.com/book/spring-security-in-action-second - edition. The complete code for the examples in the book is available for download from the Manning website at www.manning.com. liveBook discussion forum Purchase of Spring Security in Action, Second Edition includes free access to liveBook, Manning’s online reading platform. Using liveBook’s exclusive discussion features, you can attach comments to the book globally or to specific sections or paragraphs. It’s a snap to make notes for yourself, ask and answer technical questions, and receive help from the author and other users. To access the forum, go to https://livebook.manning .com/book/spring-security-in-action-second-edition/discussion. You can also learn more about Manning’s forums and the rules of conduct at https://livebook.manning .com/discussion. Manning’s commitment to our readers is to provide a venue where a meaningful dia- logue between individual readers and between readers and the author can take place. It is not a commitment to any specific amount of participation on the part of the author, whose contribution to the forum remains voluntary (and unpaid). We suggest you try asking the author some challenging questions lest their interest stray! The forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print.
Comments 0
Loading comments...
Reply to Comment
Edit Comment