front matter

foreword

Security used to be one of those system features that most people felt they could safely ignore. Unless you were working for the CIA, the military, perhaps law enforcement, or of course Google, you needed it, but it wasn’t top of your list of concerns. After all, most of the people who used your system probably came from your organization. And in any case, why would someone want to attack your system rather than a more interesting one?

How times have changed! As the list of damaging, expensive, and simply embarrassing security failures grows; as more and more personal data gets released after data breaches; and as more and more companies suffer ransomware attacks, it has become obvious that security is now everyone’s problem.

I have spent a number of years trying to bridge the historical gap between the communities of software development and software security, so I was overjoyed to find that my colleague Laurenţiu Spilcă was planning to write a book on Spring Security. The reason I was so pleased is that, as my colleague at Endava, I know that Laurenţiu is a highly competent software engineer, a great engineering leader, and a Spring Security expert. But more than that, he can really communicate complex topics effectively, as his educational work in the Java community and beyond plainly illustrates.

In this book, Laurenţiu summarizes some of the key foundations of software security, particularly as it applies to Java web applications, and then shows you how to use Spring Security to meet many of the security threats that your application is likely to meet.

You are in good hands. Laurenţiu’s approach is practical, but he always ensures that you understand the concepts as well as the syntax, so once you’ve read this book, you’ll know how to confidently and correctly apply the information in it to your applications. Using Spring Security won’t address every security concern in your application, but following the advice in this book will improve the security of your application immensely.

In summary, this book is timely, practical, and well written. I certainly plan to have a copy on my bookshelf. I suggest that all Java developers who care about the security of their applications do the same.

Eoin Woods

Chief Technical Officer, Endava

preface

I’ve worked as a software developer and trainer for software development since 2008. I can say that even if I like both these roles, I’m partial towards being a trainer/teacher. For me, sharing knowledge and helping others to upskill has always been a priority. But I strongly believe, in this domain, you can’t be just one or the other. Any software developer to some degree has to take on the role of a trainer or mentor, and you can’t be a trainer in software development without first having a solid understanding of how to apply what you teach in real-world scenarios.

With experience, I came to understand the importance of non-functional software requirements like security, maintainability, performance, and so on. I could even say I’ve spent more time learning non-functional aspects than I have invested in learning new technologies and frameworks. In practice, it’s generally much easier to spot and solve functional problems than non-functional ones. That’s probably why I encounter many developers who fear to deal with messy code, memory-related issues, multi-threaded design problems, and, of course, security vulnerabilities.

Certainly, security is one of the most crucial non-functional software features. And Spring Security is one of the most widely used frameworks for baking security into applications today. That’s because the Springframework--the Spring ecosystem--is recognized as a leader in the technologies used to develop enterprise applications within the Java and JVM universes.

But what concerns me especially is the difficulty someone faces in learning to use Spring Security properly to protect applications against common vulnerabilities. Somehow, someone could find all the details about Spring Security on the web. But it takes a lot of time and experience to put them together in the right order so that you expend a minimum of effort using the framework. Moreover, incomplete knowledge could lead someone to implement solutions that are hard to maintain and develop, and that might even expose security vulnerabilities. Too many times, I’ve been consulted by teams working on applications in which I’ve discovered Spring Security being improperly used. And, in many cases, the main reason was the lack of understanding of how to use Spring Security.

Because of this, I decided to write a book that helps any developer with Spring understand how to use Spring Security correctly. This book should be a resource to help someone with no knowledge of Spring Security understand it gradually. And what I hope, in the end, is that this book brings significant value to the reader with the time they’ll save in learning Spring Security and all the possible security vulnerabilities they’ll avoid introducing into their apps.

acknowledgments

This book wouldn’t be possible without the many smart, professional, and friendly people who helped me throughout its development process. First, I want to say a big thanks to my fiancée, Daniela, who was always there for me and helped with valuable opinions, continuously supporting and encouraging me. I’d also like to express my gratitude and send special thanks to Adrian Buturugă and Eoin Woods for their valuable advice: they helped me from the very first table of contents and proposal. A special thanks goes to Eoin for taking the time to write the forward for the book.

I want to thank the entire Manning team for their huge help in making this a valuable resource. I especially want to call out Marina Michaels, Nick Watts, and Jean-François Morin for being incredibly supportive and professional. Their advice brought great value to this book. Thanks go also to Deirdre Hiam, the project editor; Frances Buran, the copyeditor; Katie Tennant, the proofreader, and Mihaela Batinić, the review editor. Thanks so much everyone. You’re awesome and real professionals!

I want to thank my friend Ioana Göz for the drawings she created for the book. She did a great job turning my thoughts into the cartoons you’ll discover here and there throughout the book. And I want to thank everyone who reviewed the manuscript and provided useful feedback that helped me improve the content of this book. I’d like to call out the reviewers from Manning, as well friends of mine who advised me: Diana Maftei, Adrian Buturugă, Raluca Diaconu, Paul Oros, Ovidiu Tudor, Roxana Stoica, Georgiana Dudanu, Marius Scarlat, Roxana Sandu, Laurenţiu Vasile, Costin Badea, Andreea Tudose, and Maria Chiţu.

Last, but not least, I want to thank all the colleagues and friends from Endava who encouraged me throughout this period. Your thoughts and care mean very much to me.

about this book

Who should read this book?

This book is for developers using the Spring framework to build enterprise applications. Every developer should take into consideration the security aspects of their applications from the earliest stages of the development process. This book teaches you how to use Spring Security to configure application-level security. In my opinion, knowing how to use Spring Security and apply the security configurations in applications properly is mandatory for any developer. It’s simply something so important that you shouldn’t take on the responsibility of implementing an app without knowing these aspects.

I have designed this book as a resource for a developer starting with no background in Spring Security. The reader should already know how to work with some of the Spring framework fundamental aspects such as these:

Using the Spring context

Implementing REST endpoints

Using data sources

In chapter 19, we discuss applying security configurations for reactive apps. For this chapter, I also consider that you understand reactive applications and how to develop them with Spring a prerequisite. Throughout the book, I recommend resources you can use as refreshers or to learn topics you need to know in order to gain a proper understanding of what we’re discussing.

The examples I wrote for this book are in Java. I expect that if you’re a developer using the Spring framework, you also understand Java. While it’s true that at work, you could use some other language, like Kotlin, it’s still likely that you also understand Java well. For this reason, I chose to use Java for writing the examples for the book. If you feel more comfortable, any of these examples could be easily rewritten in Kotlin as well.

How this book is organized: A roadmap

This book is divided into two parts that cover 20 chapters. Part 1 of this book contains the first two chapters, in which we discuss security in general, and I teach you how to create a simple project that uses Spring Security:

In chapter 1, we discuss the importance of security in software applications and how you should think about security and vulnerabilities, which you’ll learn to avoid introducing into your apps by using Spring Security. This chapter prepares you for the rest of the book, where we use Spring Security in applied examples.

In chapter 2, you learn to create a simple Spring Boot project using Spring Security. We also discuss the Spring Security authentication and authorization architecture and its components on a high level. We start with straightforward examples and then, steadily throughout this book, you learn to apply detailed customizations for these components.

Part 2 of this book consists of eighteen chapters that progressively drive you throughout all the implementation details you need to understand to use Spring Security in your applications:

In chapter 3, you learn to use the Spring Security components that are related to user management. You learn how to describe a user with the interfaces provided by Spring Security and how to implement the functionality that enables your application to load and manage user details.

In chapter 4, you learn how to manage user’s passwords with Spring Security. We discuss encryption, hashing, and the Spring Security components related to password validation. As you might expect, passwords are sensitive details and play an essential role in most security implementations. Knowing to manage passwords is a valuable skill that we dissect in detail in this chapter.

In chapter 5, you learn how to customize the authentication logic of your application using Spring Security components. After learning in chapter 2 that Spring Boot provides you with a default implementation for authentication logic, in this chapter, you discover further that for specific requirements in real-world scenarios, you need to define custom authentication logic.

In chapter 6, the first hands-on exercise, we create a small, secured web application. We put together everything you learned in chapters 2 through 5, and you find out how to assemble these pieces into a fully working app. This app is a more complex one, and it teaches you is how to assemble in a working app the customized components you learned to develop while reading the previous chapters.

In chapter 7, we start the discussion about authorization configuration, and you learn how to configure authorization constraints. As part of almost any application, we need to make sure that actions can be executed only by authorized calls. After learning in chapters 2 through 6 how to manage authentication, it’s time you configure whether the authenticated user has the privilege of executing certain actions. You learn in this chapter how to deny or permit access for requests.

In chapter 8, we continue our discussion on authorization, and you learn how to apply authorization constraints for specific HTTP requests. In the previous chapter, we only refer to how to permit or deny requests depending on the circumstances. In this chapter, you learn to apply different authorization configurations for specific requests depending on the path or the HTTP method.

In chapter 9, we discuss customizing the filter chain. You learn that the filter chain represents a chain of responsibility that intercepts the HTTP request to apply authentication and authorization configurations.

In chapter 10, we discuss how cross-site request forgery protection works, and you learn how to customize it with Spring Security. Then, we discuss cross-origin resource sharing, and you learn how to configure more relaxed CORS policies and when you should do this.

In chapter 11, our second hands-on exercise, we work on an application that implements customized authentication and authorization. You apply what you learned already in this book, but you also learn what tokens are and their purpose in authorization.

In chapter 12, we begin our journey into a more complex topic, OAuth 2. This topic is the subject of chapters 12 through 15. In this chapter, you learn what OAuth 2 is, and we discuss the flows in which a client can obtain an access token to call endpoints exposed by a backend application.

In chapter 13, you learn how to use Spring Security to build a custom OAuth 2 authorization server.

In chapter 14, you learn how to use Spring Security to build a resource server in your OAuth 2 system, as well as ways in which the resource server validates the tokens issued by the authorization server.

In chapter 15, we conclude the OAuth 2 topic with how systems use JSON Web Tokens for authorization.

In chapter 16, we discuss applying authorization configurations at the method level.

In chapter 17, we continue the discussion from chapter 16, and you learn how to apply authorization configurations to filter values that represent inputs and outputs of methods.

In chapter 18, our third hands-on exercise, we apply with an example what you learned in chapters 12 through 17. Moreover, you learn how to use the third-party tool Keycloak as an authorization server in your OAuth 2 system.

In chapter 19, you learn how to apply security configurations for reactive applications developed with the Spring framework.

In chapter 20, we wrap up our journey. You learn how to write integration tests for your security configurations.

I designed the book to be easy for you to read in order from the first to the last chapter. In most cases, to understand the discussion of a specific chapter, you need to understand the topic previously discussed. For example, it doesn’t make sense to read chapter 3, where we discuss customization of user management components, if you haven’t had an overview of the Spring Security main architecture, which we discuss in chapter 2. You’d find it more difficult reading about password management before understanding first how user details are retrieved. Reading chapters 1 through 10 in the given order brings you the best benefit, especially if you have no or minimal experience with Spring Security. The following figure presents the path to take when reading this book.


Figure FM.1 The complete path for this book, Spring Security in Action. If you are a beginner with Spring Security, the best thing to do is to read all the chapters in order.

If you already have some knowledge of how Spring Security components work but are only interested in implementing OAuth 2 systems with Spring Security, you could go directly to chapter 12 and start your OAuth 2 journey to chapter 15. But, remember that the fundamentals discussed in chapters 1 through 11 are really important. Often, I find people with a bare understanding of the basics who try to understand a more complex aspect. Don’t fall into this trap. For example, I recently interacted with people who wanted to use JWTs without knowing how the basic Spring Security architecture works. This approach generally doesn’t work and leads to frustration. If you aren’t familiar yet with the basics and want to learn about OAuth2 applications, start with the beginning of the book, and don’t go directly to chapter 15.


Figure FM.2 If you’re already comfortable with the basics and you’re interested only in a specific subject (for example, OAuth 2), you can skip to the first chapter that describes the topic of your interest.

You can also decide to read chapters 16 and 17 directly after chapter 11 if you’re not interested in OAuth 2. In that case, you can skip the OAuth 2 part completely. The OAuth 2 chapters are intended to be read in order, starting with chapter 12 and up through chapter 15. And it also makes sense to read the last hands-on chapter of the book, which is chapter 18, after you read both the OAuth 2 parts and chapters 16 and 17.

You may decide whether to read chapter 19 or not, which is related to securing reactive apps. This chapter is only relevant to reactive apps, so you can skip it if it’s not pertinent to your interests.

In the last chapter, chapter 20, you learn how to define your integration tests for security configurations. We use examples that were explained throughout the book, and you need to understand the concepts we discussed in all the previous chapters. However, I separated chapter 20 into multiple sections. Each section is directly related to the main concepts discussed in the book. So, if you need to learn how to write integration tests, but you don’t care about reactive apps, you can still easily read chapter 20 and skip over the section referring to reactive apps.

About the code

The book provides over 70 projects, which we work on starting with chapter 2 and up through chapter 19. 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 helps you better understand the security configurations you’re learning.

Each of the projects is built with Maven, which makes it easy to be imported into any IDE. I used IntelliJ IDEA to write the projects, but you can run them in Eclipse, STS, NetBeans, or any other tool of your choice. The appendix also helps you 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. At times, the original source code has been reformatted; I 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 ( ). Code annotations accompany many of the listings, highlighting important concepts.

The liveBook discussion forum

Purchasing Spring Security in Action includes free access to a private web forum run by Manning Publications where you can make comments about the book, ask technical questions, and receive help from the author and from other users. To access the forum, go to http://mng.bz/6Awp. 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 him some challenging questions lest his interest stray! The forum and the archives of previous discussions are accessible from the publisher’s website as long as the book is in print.

Other online resources

Additional resources include the Spring Security Reference at http://mng.bz/7Gz7 and the Spring Security Fundamentals playlist on the author’s YouTube account at http://mng.bz/mN4W.

about the author

Laurenţiu Spilcă is a dedicated leader and trainer at Endava, where he heads the development of a project for the financial market of European Nordic countries. He has over nine years of experience. Previously, he was a software developer building one of the biggest enterprise resource planning solutions with worldwide installations.

Laurenţiu believes it’s important to not only deliver high-quality software but also to share knowledge and help others to upskill. That drives him to design and teach courses related to Java technologies and to deliver presentations and workshops throughout the United States and Europe. His speaking engagements include those for Voxxed Days, TechFlow, Bucharest Technology Week, JavaSkop, Oracle Code Explore, O’Reilly Software Architecture, and Oracle Code One.

about the cover illustration

The figure on the cover of Spring Security in Action is captioned “Homme de Murcie,” or Murcie man. The illustration is taken from a collection of dress costumes from various countries by Jacques Grasset de Saint-Sauveur (1757-1810), titled Costumes de Différents Pays, published in France in 1788. Each illustration is finely drawn and colored by hand. The rich variety of Grasset de Saint-Sauveur’s collection reminds us vividly of how culturally apart the world’s towns and regions were just 200 years ago. Isolated from each other, people spoke different dialects and languages. In the streets or in the countryside, it was easy to identify where they lived and what their trade or station in life was just by their dress.

The way we dress has changed since then and the diversity by region, so rich at the time, has faded away. It is now hard to tell apart the inhabitants of different continents, let alone different towns, regions, or countries. Perhaps we have traded cultural diversity for a more varied personal life--certainly for a more varied and fast-paced technological life.

At a time when it is hard to tell one computer book from another, Manning celebrates the inventiveness and initiative of the computer business with book covers based on the rich diversity of regional life of two centuries ago, brought back to life by Grasset de Saint-Sauveur’s pictures.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.160.43