Spring Security in Action, Second Edition
()
About this ebook
Spring Security in Action, Second Edition is a revised version of the bestselling original, fully updated for Spring Boot 3 and Oauth2/OpenID Connect.
In Spring Security in Action, Second Edition you will learn essential security skills including how to:
- Implement and customize authentication and authorization
- Set up all components of an OAuth2/OpenID Connect system
- Utilize CRSF and CORS configurations
- Secure Spring reactive applications
- Write tests for security configurations
Whether you’re a beginner or a pro, Spring Security in Action, Second Edition teaches you how to secure your Java applications from the ground up. Author Laurentiu Spilca distills his years of experience as a skilled Java and Spring developer into an indispensable guide to everything security—from authentication and authorization, to testing security configurations. This new edition covers the latest patterns for application-level security in Spring apps, demonstrating how Spring Security simplifies every step of the security process.
Foreword by Joe Grandja.
About the technology
Spring Security makes it much, much easier to secure enterprise-scale Java applications. This powerful framework integrates with Spring apps end to end, with “secure by design” principles and ready-to-use features that help you implement robust authorization and authentication and protect against data theft and intrusions. And like everything else in the Spring ecosystem, it’s free, open source, and backed by the awesome team at VMWare.
About the book
Spring Security in Action, Second Edition updates this bestselling guide to Spring Security to include deep coverage of OAuth2/OpenID Connect and security configuration using the new SecurityFilterChain. The crystal clear explanations and relevant examples, teach you how to build your own authorization server, configure secure endpoints, and prevent cross-site scripting and request forgery attacks.
What's inside
- Custom authentication and authorization
- CRSF and CORS configurations
- Secure Spring reactive applications
- Write tests for security configurations
About the reader
For experienced Java and Spring developers.
About the author
Laurentiu Spilca is a skilled Java and Spring developer and an experienced technology instructor. He is also the author of Manning’s Spring Start Here and Troubleshooting Java.
Table of Contents
PART 1
1 Security today
2 Hello, Spring Security
PART 2
3 Managing users
4 Managing passwords
5 A web app’s security begins with filters
6 Implementing authentications
PART 3
7 Configuring endpoint-level authorization: Restricting access
8 Configuring endpoint-level authorization: Applying restrictions
9 Configuring CSRF protection
10 Configuring CORS
11 Implementing authorization at the method level
12 Implementing filtering at the method level
PART 4
13 What are OAuth 2 and OpenID Connect?
14 Implementing an OAuth 2 authorization server
15 Implementing an OAuth 2 resource server
16 Implementing an OAuth 2 client
PART 5
17 Implementing security in reactive applications
PART 6
18 Testing security configurations
Laurentiu Spilca
Laurentiu Spilca is a skilled Java and Spring developer and an experienced technology instructor. He is the author of Manning’s Spring Start Here and Spring Security in Action.
Read more from Laurentiu Spilca
Spring Start Here: Learn what you need and learn it well Rating: 0 out of 5 stars0 ratingsTroubleshooting Java: Read, debug, and optimize JVM applications Rating: 0 out of 5 stars0 ratingsSpring Security in Action Rating: 0 out of 5 stars0 ratings
Related to Spring Security in Action, Second Edition
Related ebooks
ASP.NET Core in Action, Third Edition Rating: 0 out of 5 stars0 ratingsMeteor in Action Rating: 0 out of 5 stars0 ratingsDesigning Deep Learning Systems: A software engineer's guide Rating: 0 out of 5 stars0 ratingsPlay for Java Rating: 0 out of 5 stars0 ratingsDependency Injection: Design patterns using Spring and Guice Rating: 0 out of 5 stars0 ratingsKafka Streams in Action, Second Edition Rating: 0 out of 5 stars0 ratingsBuild an Orchestrator in Go (From Scratch) Rating: 0 out of 5 stars0 ratingsGo Programming - From Beginner to Professional: Learn everything you need to build modern software using Go Rating: 0 out of 5 stars0 ratingsGenerative AI in Action Rating: 0 out of 5 stars0 ratingsAdvanced React Patterns Rating: 0 out of 5 stars0 ratingsAkka in Action, Second Edition Rating: 0 out of 5 stars0 ratingsLinux Kernel Programming: A comprehensive and practical guide to kernel internals, writing modules, and kernel synchronization Rating: 0 out of 5 stars0 ratingsC++ Cookbook: How to write great code with the latest C++ releases (English Edition) Rating: 0 out of 5 stars0 ratingsUltimate Certified Kubernetes Administrator (CKA) Certification Guide Rating: 0 out of 5 stars0 ratings.NET in Action, Second Edition Rating: 0 out of 5 stars0 ratingsKotlin Quick Start Guide: Core features to get you ready for developing applications Rating: 0 out of 5 stars0 ratingsMastering Secure Java Applications: Navigating security in cloud and microservices for Java (English Edition) Rating: 0 out of 5 stars0 ratingsRestlet in Action: Developing RESTful web APIs in Java Rating: 0 out of 5 stars0 ratingsUltimate Typescript Handbook: Build, scale and maintain Modern Web Applications with Typescript Rating: 0 out of 5 stars0 ratingsA Developer's Essential Guide to Docker Compose: Simplify the development and orchestration of multi-container applications Rating: 0 out of 5 stars0 ratingsUltimate Git and GitHub for Modern Software Development Rating: 0 out of 5 stars0 ratingsModern Multithreading: Implementing, Testing, and Debugging Multithreaded Java and C++/Pthreads/Win32 Programs Rating: 0 out of 5 stars0 ratingsAspectJ in Action: Enterprise AOP with Spring Applications Rating: 0 out of 5 stars0 ratingsLearn SQL Database Programming: Query and manipulate databases from popular relational database servers using SQL Rating: 0 out of 5 stars0 ratingsEnterprise OSGi In Action Rating: 0 out of 5 stars0 ratingsASP.NET jQuery Cookbook - Second Edition Rating: 0 out of 5 stars0 ratings
Internet & Web For You
Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Everybody Lies: Big Data, New Data, and What the Internet Can Tell Us About Who We Really Are Rating: 4 out of 5 stars4/5Notion for Beginners: Notion for Work, Play, and Productivity Rating: 4 out of 5 stars4/5The $1,000,000 Web Designer Guide: A Practical Guide for Wealth and Freedom as an Online Freelancer Rating: 4 out of 5 stars4/5Stop Asking Questions: How to Lead High-Impact Interviews and Learn Anything from Anyone Rating: 5 out of 5 stars5/5Get Into UX: A foolproof guide to getting your first user experience job Rating: 4 out of 5 stars4/5Social Engineering: The Science of Human Hacking Rating: 3 out of 5 stars3/5LinkedIn Profile Optimization For Dummies Rating: 4 out of 5 stars4/5The Digital Marketing Handbook: A Step-By-Step Guide to Creating Websites That Sell Rating: 5 out of 5 stars5/5Coding For Dummies Rating: 5 out of 5 stars5/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5UX/UI Design Playbook Rating: 4 out of 5 stars4/5The Designer’s Guide to Figma: Master Prototyping, Collaboration, Handoff, and Workflow Rating: 0 out of 5 stars0 ratingsThe Basics of User Experience Design by Interaction Design Foundation Rating: 4 out of 5 stars4/5Learn JavaScript in 24 Hours Rating: 3 out of 5 stars3/5Principles of Web Design Rating: 0 out of 5 stars0 ratings2022 Adobe® Premiere Pro Guide For Filmmakers and YouTubers Rating: 5 out of 5 stars5/5Coding with AI For Dummies Rating: 0 out of 5 stars0 ratingsGet Started in UX: The Complete Guide to Launching a Career in User Experience Design Rating: 4 out of 5 stars4/5The Logo Brainstorm Book: A Comprehensive Guide for Exploring Design Directions Rating: 4 out of 5 stars4/5Web Design For Dummies Rating: 4 out of 5 stars4/5HTML, CSS, & JavaScript All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsUltimate Tailwind CSS Handbook: Build sleek and modern websites with immersive UIs using Tailwind CSS Rating: 0 out of 5 stars0 ratingsJavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5RESTful API Design - Best Practices in API Design with REST: API-University Series, #3 Rating: 5 out of 5 stars5/5Learn NodeJS in 1 Day: Complete Node JS Guide with Examples Rating: 3 out of 5 stars3/5
Reviews for Spring Security in Action, Second Edition
0 ratings0 reviews
Book preview
Spring Security in Action, Second Edition - Laurentiu Spilca
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.
Spring Security in Action
Second Edition
Laurențiu Spilcă
Foreword by Joe Grandja
To comment go to liveBook
Manning
Shelter Island
For more information on this and other Manning titles go to
www.manning.com
Copyright
For online information and ordering of these and other Manning books, please visit www.manning.com. The publisher offers discounts on these books 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: [email protected]
©2024 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.
ISBN: 9781633437975
contents
Front matter
foreword
preface
acknowledgments
about this book
about the author
about the cover illustration
Part 1. Say hello to Spring Security
1 Security today
1.1 Discovering Spring Security
1.2 What is software security?
1.3 Why is security important?
1.4 What will you learn in this book?
2 Hello, Spring Security
2.1 Starting your first project
2.2 The big picture of Spring Security class design
2.3 Overriding default configurations
Customizing user details management
Applying authorization at the endpoint level
Configuring in different ways
Defining custom authentication logic
Using multiple configuration classes
Part 2. Configuring authentication
3 Managing users
3.1 Implementing authentication in Spring Security
3.2 Describing the user
Describing users with the UserDetails contract
Detailing on the GrantedAuthority contract
Writing a minimal implementation of UserDetails
Using a builder to create instances of the UserDetails type
Combining multiple responsibilities related to the user
3.3 Instructing Spring Security on how to manage users
Understanding the UserDetailsService contract
Implementing the UserDetailsService contract
Implementing the UserDetailsManager contract
4 Managing passwords
4.1 Using password encoders
The PasswordEncoder contract
Implementing your PasswordEncoder
Choosing from the provided PasswordEncoder implementations
Multiple encoding strategies with DelegatingPasswordEncoder
4.2 Taking advantage of the Spring Security Crypto module
Using key generators
Encrypting and decrypting secrets using encryptors
5 A web app’s security begins with filters
5.1 Implementing filters in the Spring Security architecture
5.2 Adding a filter before an existing one in the chain
5.3 Adding a filter after an existing one in the chain
5.4 Adding a filter at the location of another in the chain
5.5 Filter implementations provided by Spring Security
6 Implementing authentications
6.1 Understanding the AuthenticationProvider
Representing the request during authentication
Implementing custom authentication logic
Applying custom authentication logic
6.2 Using the SecurityContext
Using a holding strategy for the security context
Using a holding strategy for asynchronous calls
Using a holding strategy for standalone applications
Forwarding the security context with DelegatingSecurityContextRunnable
Forwarding the security context with DelegatingSecurityContextExecutorService
6.3 Understanding HTTP Basic and form-based login authentications
Using and configuring HTTP Basic
Implementing authentication with form-based login
Part 3. Configuring authorization
7 Configuring endpoint-level authorization: Restricting access
7.1 Restricting access based on authorities and roles
Restricting access for all endpoints based on user authorities
Restricting access for all endpoints based on user roles
Restricting access to all endpoints
8 Configuring endpoint-level authorization: Applying restrictions
8.1 Using the requestMatchers() method to select endpoints
8.2 Selecting requests to apply authorization restrictions
8.3 Using regular expressions with request matchers
9 Configuring CSRF protection
9.1 How CSRF protection works in Spring Security
9.2 Using CSRF protection in practical scenarios
9.3 Customizing CSRF protection
10 Configuring CORS
10.1 How does CORS work?
10.2 Applying CORS policies with the @CrossOrigin annotation
10.3 Applying CORS using a CorsConfigurer
11 Implementing authorization at the method level
11.1 Enabling method security
Understanding call authorization
Enabling method security in your project
11.2 Applying preauthorization rules
11.3 Applying postauthorization rules
11.4 Implementing permissions for methods
12 Implementing filtering at the method level
12.1 Applying prefiltering for method authorization
12.2 Applying postfiltering for method authorization
12.3 Using filtering in Spring Data repositories
Part 4. Implementing OAuth 2 and OpenID Connect
13 What are OAuth 2 and OpenID Connect?
13.1 The big picture of OAuth 2 and OpenID Connect
13.2 Using various token implementations
Using opaque tokens
Using non-opaque tokens
13.3 Obtaining tokens through various grant types
Getting a token using the authorization code grant type
Applying PKCE protection to the authorization code grant type
Getting a token with the client credentials grant type
Using refresh tokens to get new access tokens
13.4 What OpenID Connect brings to OAuth 2
13.5 The sins of OAuth 2
14 Implementing an OAuth 2 authorization server
14.1 Implementing basic authentication using JSON web tokens
14.2 Running the authorization code grant type
14.3 Running the client credentials grant type
14.4 Using opaque tokens and introspection
14.5 Revoking tokens
15 Implementing an OAuth 2 resource server
15.1 Configuring JWT validation
15.2 Using customized JWTs
15.3 Configuring token validation through introspection
15.4 Implementing multitenant systems
16 Implementing an OAuth 2 client
16.1 Implementing OAuth 2 login
Implementing authentication with a common provider
Giving the user more possibilities
Using a custom authorization server
Adding flexibility to your configurations
Managing authorization for an OAuth 2 login
16.2 Implementing an OAuth 2 client
Part 5. Going reactive
17 Implementing security in reactive applications
17.1 What are reactive apps?
17.2 User management in reactive apps
17.3 Configuring authorization rules in reactive apps
Applying authorization at the endpoint layer in reactive apps
Using method security in reactive apps
17.4 Creating a reactive OAuth 2 resource server
Part 6. Testing security configurations
18 Testing security configurations
18.1 Using mock users for tests
18.2 Testing with users from a UserDetailsService
18.3 Using custom Authentication objects for testing
18.4 Testing method security
18.5 Testing authentication
18.6 Testing CSRF configurations
18.7 Testing CORS configurations
18.8 Testing reactive Spring Security implementations
Appendix A. Links to official documentation
Appendix B. Further reading
index
front matter
foreword
I first got to know Laurențiu Spilcă in 2022, when we virtually collaborated on a SpringOne presentation, and I was happy to finally meet him in person at Devoxx 2023 in Belgium. 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 diagrams 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. 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. However, 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 further 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
preface
The journey through software development is an enthralling dance of building, learning, 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 developer 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 software 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 nonfunctional 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 widespread adoption and trustworthiness of the Spring ecosystem in the enterprise application 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.
With the second edition, we delve deep into Spring Security, reflecting on the innovations, 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 envisioned 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.
acknowledgments
Creating this book has been a journey I couldn’t have embarked upon without the collective 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 commitment 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 illustrations. 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 numerous reviewers. Their keen observations and constructive feedback have been instrumental 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!
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 understanding 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 essential. 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.
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 techniques 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 experience 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. 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 accommodate 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 https://www.manning.com/books/spring-security-in-action-second-edition.
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 dialogue 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.
about the author
Laurențiu Spilcă
has been a seasoned software developer and trainer since 2007, currently serving as a principal development consultant at Endava. In this role, he spearheads globally recognized projects with installations across the world. Laurențiu’s twin passions have consistently been clear: delivering top-tier software and imparting knowledge to fellow developers.
Throughout his career, Laurențiu has ardently believed that it’s not just about crafting high-quality software, but also about fostering a culture of shared knowledge and continuous learning. This conviction has led him to design and facilitate courses centered around Java technologies. Over the past decade, he has imparted knowledge to over 3,000 students and has been actively involved in courses at the Mathematics and Informatics Faculty of Bucharest University.
Beyond his contributions in the classroom, Laurențiu is also a recognized author. He has penned three pivotal books in the Java domain: Spring Security in Action, Spring Start Here, and Troubleshooting Java. These publications underscore his commitment to spreading knowledge and facilitating a deeper understanding of Java and its associated technologies.
His commitment to sharing insights extends to global platforms. From the streets of New York and San Francisco to the historic venues of Warsaw, Belgrade, and Berlin, Laurențiu has delivered presentations, tutorials, and workshops that resonate with international audiences.
In his quest to make knowledge widely accessible, Laurențiu also created a YouTube channel (youtube.com/@laurspilca), dedicated to Java and its adjacent technologies. On this platform, beginners and seasoned developers can examine a wide range of topics, all curated and presented with Laurenţiu’s trademark clarity.
Outside of his professional endeavors, Laurenţiu’s passions diversify into the realms of travel, music, and the mesmerizing world of scuba diving. Whether navigating the depths of the ocean or the intricacies of code, Laurenţiu’s journey is a testament to his spirit of exploration and discovery.
Twitter/X handle: @laurspilca
About the technical editor
Jean-François Morin
is a senior Java developer and architect at Laval University in Quebec City, Canada. He holds a B.Sc. in mathematics, a M.Sc. in computer science, and six Sun/Oracle Java certifications, including Java SE 17 Developer and JAVA EE 6 Enterprise Architect. He is also an experienced Java teacher and a regular Manning collaborator.
about the cover illustration
The figure on the cover of Spring Security in Action, Second Edition is captioned Homme de Murcie,
or Murcie Man,
taken from a collection by Jacques Grasset de Saint-Sauveur, published in 1797. Each illustration is finely drawn and colored by hand.
In those days, it was easy to identify where people lived and what their trade or station in life was just by their dress. Manning celebrates the inventiveness and initiative of the computer business with book covers based on the rich diversity of regional culture centuries ago, brought back to life by pictures from collections such as this one.
Part 1. Say hello to Spring Security
Diving into the realm of Spring Security? Let’s embark on this journey together! In this initial part of the book, we will set the stage by laying a solid foundation.
Chapter 1 begins by introducing you to the world of Spring Security. As we progress, we’ll delve deeper into the essence of software security, attempting to answer pertinent questions such as What is software security?
and Why is it of paramount importance?
Moreover, we’ll outline the learning trajectory of this book, ensuring you know what to anticipate as you proceed.
Chapter 2 promises to be a hands-on endeavor. We’ll kick things off by initiating your very first Spring project. If you’ve ever wondered about the architecture and class design that drives Spring Security, this chapter will provide a bird’s-eye view. But it’s not just about understanding the default mechanisms. The book will take things a step further by guiding you through the process of overriding default configurations. This will include deep dives into customizing user details, enhancing authorization at various endpoints, exploring diverse configuration methods, defining your own authentication logic, and efficiently utilizing multiple configuration classes.
By the time you conclude this part, not only will you have a solid grasp of the theoretical underpinnings of Spring Security, but you’ll also have a functional app secured with it. It’s a combination of understanding the why
and mastering the how
—all in a short span of time.
1 Security today
This chapter covers
What Spring Security is and what you can solve by using it
What security is for a software application
Why software security is essential and why you should care
Developers have become increasingly aware of the need for secure software, and they have been taking responsibility for security from the beginning of software development. Generally, as developers, we begin by learning that the purpose of an application is to solve business problems. This purpose refers to something where data could be processed somehow, persisted, and eventually displayed to the user as specified by requirements. This overview of software development, which is somehow imposed from the early stages of learning these techniques, has the unfortunate disadvantage of hiding practices that are also part of the process. While the application works correctly from the user’s perspective, and it eventually does what the user expects in terms of functionality, there are many aspects hidden in the final result.
Nonfunctional software qualities such as performance, scalability, availability, and security, as well as others, can have an effect over time, from the short to the long term. If not taken into consideration early on, these qualities can dramatically affect the profitability of the application owners (figure 1.1). Moreover, the neglect of these considerations can also trigger failures in other systems (for example, by the unwilling participation in a distributed denial of service [DDoS] attack). The hidden aspects of nonfunctional requirements (the fact that it’s much more challenging to see if something’s missing or incomplete) make these even more dangerous.
Figure 1.1 Users typically focus on what a system should do—its functional aspects. Occasionally, they may consider system performance, a nonfunctional attribute, but it’s rare for them to pay attention to security measures. Requirements that don’t pertain directly to functionality often go unnoticed compared to those that do.
There are multiple nonfunctional aspects to consider when working on a software system. In practice, all of these are important and need to be treated responsibly in the process of software development. This book focuses on one of these: security. You’ll learn how to protect your application, step by step, using Spring Security.
This chapter will show you the big picture of security-related concepts. Throughout the book, we will work on practical examples, and where appropriate, I’ll refer back to the description I give in this chapter. Where applicable, I’ll also provide you with more details. Here and there, you’ll find references to other materials (books, articles, and documentation) on specific subjects useful for further reading.
1.1 Discovering Spring Security
This section discusses the relationship between Spring Security and Spring. First, it is important to understand the link between the two before starting to use them. If we check the official website (https://spring.io/projects/spring-security), we can see that Spring Security is described as a powerful and highly customizable framework for authentication and access control. I would simply say it is a framework that greatly simplifies applying (or baking in) security for Spring applications.
Spring Security is the primary choice for implementing application-level security in Spring applications. Generally, its purpose is to offer you a highly customizable way of implementing authentication, authorization, and protection against common attacks. Spring Security is open source software released under the Apache 2.0 license. You can access its source code on GitHub at http://mng.bz/vPmJ. I highly recommend that you contribute to the project as well.
Note You can use Spring Security for both standard web servlets and reactive applications, as well as non-web apps. In this book, we’ll use Spring Security with the latest Java long-term supported, Spring, and Spring Boot versions (Java 21, Spring 6, and Spring Boot 3). However, all the book’s examples also work with Java 17, the previous long-term supported version.
I can guess that if you opened this book, then you work on Spring applications, and you are interested in securing those. Spring Security is most likely the best choice for you. It’s the de facto solution for implementing application-level security for Spring applications. Spring Security, however, doesn’t automatically secure your application. It’s not some kind of magic panacea that guarantees a vulnerability-free app. Developers need to understand how to configure and customize Spring Security around the needs of their applications. How to do this depends on many factors, from the functional requirements to the architecture.
Technically, applying security with Spring Security in Spring applications is simple. You’ve already implemented Spring applications, so you know that the framework’s philosophy starts with the management of the Spring context. You define beans in the Spring context to allow the framework to manage these based on the configurations you specify.
You use annotations to tell Spring what to do: expose endpoints, wrap methods in transactions, intercept methods in aspects, and so on. The same is true with Spring Security configurations, which is where Spring Security comes into play. You want to use annotations, beans, and in general, a Spring-fashioned configuration style comfortably when defining your application-level security. In a Spring application, the behavior that you need to protect is defined by methods.
To think about application-level security, you can consider your home and the way you allow access to it. Do you place the key under the entrance rug? Do you even have a key for your front door? The same concept applies to applications, and Spring Security helps you develop this functionality. It’s a puzzle that offers plenty of choices for building the exact image that describes your system. You can choose to leave your house completely unsecured, or you can decide not to allow everyone to enter your home.
The way you configure security can be straightforward like hiding your key under the rug, or it can be more complicated like choosing a variety of alarm systems, video cameras, and locks. In your applications, you have the same options, but as in real life, the more complexity you add, the more expensive it gets. In an application, this cost refers to the way security affects maintainability and performance.
But how do you use Spring Security with Spring applications? Generally, at the application level, one of the most frequently encountered use cases is when you’re deciding whether someone is allowed to perform an action or use some piece of data. Based on configurations, you write Spring Security components that intercept the requests and that ensure whoever makes the requests has permission to access protected resources. The developer configures components to do precisely what’s desired. If you mount an alarm system, it’s you who should make sure it’s set up for the windows as well as for the doors. If you forget to set it up for the windows, it’s not the fault of the alarm system that it doesn’t trigger when someone forces a window.
Other responsibilities of Spring Security components relate to data storage as well as data transit between different parts of the systems. By intercepting calls to these different parts, the components can act on the data. For example, when data is stored, these components can apply encryption or hashing algorithms. The data encodings keep the data accessible only to privileged entities. In a Spring application, the developer has to add and configure a component to do this part of the job wherever it’s needed. Spring Security provides us with a contract through which we know what the framework requires to be implemented, and we write the implementation according to the application design. We can say the same thing about transiting data.
In real-world implementations, you’ll find cases in which two communicating components don’t trust each other. How can the first know that the second one sent a specific message, and it wasn’t sent by someone else? Imagine you have a phone call with somebody to whom you must give private information. How do you make sure that a valid individual with the right to get that data is indeed on the other end, and not somebody else? The same situation is relevant to your application. Spring Security provides components that allow you to solve these problems in several ways, but you must know which part to configure and then set it up in your system. In this way, Spring Security intercepts messages and makes sure to validate communication before the application uses any kind of data sent or received.
Like any framework, one of the primary purposes of Spring is to allow you to write less code to implement the desired functionality. This is also what Spring Security does. It completes Spring as a framework by helping you write less code to perform one of the most critical aspects of an application—security. Spring Security provides predefined functionality to help you avoid writing boilerplate code or repeatedly writing the same logic from app to app. However, it also allows you to configure any of its components, thus providing great flexibility. To briefly recap this discussion:
You use Spring Security to bake application-level security into your applications in the Spring way. By this, I mean you use annotations, beans, the Spring Expression Language (SpEL), and so on.
Spring Security is a framework that lets you build application-level security. However, it is up to you, the developer, to understand and use Spring Security properly. Spring Security by itself does not secure an application or sensitive data at rest or in flight.
This book provides you with the information you need to effectively use Spring Security.
Alternatives to Spring Security
This book is about Spring Security, but as with any solution, I always prefer to have a broad overview. Never forget to learn the alternatives that you have for any option. One of the things I’ve learned over time is that there’s no general right or wrong. The saying Everything is relative
also applies here!
You won’t find a lot of alternatives to Spring Security when it comes to securing a Spring application. One alternative you could consider is Apache Shiro (https://shiro.apache.org). It offers flexibility in configuration and is easy to integrate with Spring and Spring Boot applications. Apache Shiro sometimes makes a good alternative to the Spring Security approach.
If you’ve already worked with Spring Security, you’ll find using Apache Shiro easy and comfortable to learn. It offers its own annotations and design for web applications based on HTTP filters, which greatly simplifies working with web applications. Also, you can secure more than just web applications with Shiro, from smaller command-line and mobile applications to large-scale enterprise applications. And although simple, it’s powerful enough to be used for a wide range