31,19 €
Spring Security enables developers to seamlessly integrate authorization, authentication, and a range of security features for complex enterprise applications. This book provides a hands-on approach to developing reactive applications using Spring and will help you get up and running in no time.
Complete with step-by-step explanations, practical examples, and self-assessment questions, the book begins by explaining the essential concepts of reactive programming, Spring Framework, and Spring Security. You’ll then learn about a variety of authentication mechanisms and how to integrate them easily with a Spring MVC application. You’ll also understand how to achieve authorization in a Spring WebFlux application using Spring Security. Furthermore, the book will take you through the configuration required to implement OAuth2 for securing REST APIs, and guide you in integrating security in microservices and serverless applications. Finally, you’ll be able to augment add-ons that will enhance any Spring Security module.
By the end of the book, you’ll be equipped to integrate Spring Security into your Java enterprise applications proficiently.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 235
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Richa TripathiAcquisition Editor: Chaitanya NairContent Development Editor: Zeeyan PinheiroTechnical Editor: Ruvika RaoCopy Editor: Safis EditingProject Coordinator: Vaidehi SawantProofreader: Safis EditingIndexer: Aishwarya GangawaneGraphics: Jason MonteiroProduction Coordinator: Shantanu Zagade
First published: July 2018
Production reference: 1310718
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78899-597-9
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Tomcy John is an enterprise Java specialist with over 16 years of several domain expertise. He is currently a part of the Emirates IT Group as a Principal Architect. Before this, he's worked with Oracle Corporation and Ernst & Young. He acts as a chief mentor to facilitate incorporating new technologies. Outside of work, he works closely with young developers and engineers as a mentor and speaks on topics ranging from web and middleware all the way to various persistence stores. Tomcy has also the co-authored a book on big data, Data Lake for Enterprises, which is published by Packt.
Ranga Rao Karanam is a programmer, trainer, and an architect. He is the founder of in28Minutes, helping 2 million learners re-skill on cloud-native applications, microservices, evolutionary design, high quality code, DevOps, BDD, TDD, and refactoring. He loves consulting for start-ups on developing scalable component-based cloud-native applications and following modern development practices such as BDD, Continuous Delivery, and DevOps. He loves the freedom the Spring framework brings to developing enterprise Java applications.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Hands-On Spring Security 5 for Reactive Applications
Dedication
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Overview of Spring 5 and Spring Security 5
How examples are structured
New-generation application requirements
Reactive programming
Reactive applications
Reactive Manifesto
Responsive
Resilient
Elastic
Message-driven
Spring Framework
Reactive Landscape in Java
Reactive Streams and Reactive Streams Specifications
Non-blocking
Backpressure
Reactive Extensions
RxJava
Reactive Streams and RxJava
JDK 9 additions
Important interfaces
The Publisher Interface
The Subscriber Interface
The Subscription interface
The Processor interface
Spring Framework and reactive applications
Modules in Reactor
Reactive types in Reactor Core
The Flux reative type
The Mono reactive type
Data stream types
Reactor and RxJava
Reactive Web Application
Spring WebFlux
Reactive Spring Web
WebClient
WebSockets
Application security
Spring Security
Spring Security terminologies
Spring Security's core features
Authentication
Authorization
Spring Security 5's new features
Working of Spring Security
Servlet Filter
Filter Chain
Security Interceptor (DelegatingFilterProxy)
Core Spring Security modules
Summary
Deep Diving into Spring Security
Authentication
Setting up AuthenticationManager
AuthenticationProvider
Custom AuthenticationProvider
Multiple AuthenticationProvider
Sample application
Base project setup
Step 1—Create a Maven project in IntelliJ IDEA
Step 2—pom.xml changes
Step 3—MySQL database schema setup
Step 4—Setting up MySQL database properties in your project
Step 5—Spring application configuration
Step 6—Web application configuration
Step 7—Spring MVC setup
Step 8—Controller setup
Step 9—JSP creation
Spring Security setup
Step 1—Spring Security configuration setup
Step 2—Spring Security setup for a web application
Running the application
In-memory user storage
Run as Spring Boot
Authorization
Web URL
Method invocation
Domain instance
Other Spring Security capabilities
Summary
Authentication Using SAML, LDAP, and OAuth/OIDC
Security Assertion Markup Language
Setting up an SSO provider
Setting up the project
The pom.xml file setup
The application.yml file setup
The Spring Security configuration files
The resources folder setup
Running and testing the application
Lightweight Directory Access Protocol
Set up dependencies in the pom.xml file
Spring Security configuration
LDAP server setup
Setting up users in the LDAP server
Running the application
Seeing the application in action on a browser
OAuth2 and OpenID Connect
Setting up a project
Bootstrap Spring project using Spring Initializr
Inclusion of OAuth libraries in pom.xml
Setting up provider details in application.properties
Provider setup
Default application change
The HomeController class
The home.jsp file
Spring Boot main application class change
Running the application
Summary
Authentication Using CAS and JAAS
CAS
CAS server setup
Git clone
Adding additional dependencies
Setting up the resources folder in the project
Creating the application.properties file
Creating a local SSL keystore
Creating the .crt file to be used by the client
Exporting the .crt file to Java and the JRE cacert keystore
Building a CAS server project and running it
Registering a client with the CAS server
JSON service configuration
Additional application.properties file changes
CAS client setup
Bootstrap Spring project using Spring Initializr
Including CAS libraries in pom.xml
Changing the application.properties file
Additional bean configuration
ServiceProperties bean
AuthenticationEntryPoint bean
TicketValidator bean
CasAuthenticationProvider bean
Setting up Spring Security
Creating the CasAuthenticationFilter bean
Setting up the controller
Running the application
Java Authentication and Authorization Service
Setting up a project
Setting up Maven project
Setting up LoginModule
Setting up a custom principal
Setting up a custom AuthorityGranter
Configuration files
Application configuration
Spring MVC configuration
Spring Security configuration
Controllers
Setting up pages
Running the application
Kerberos
Custom AuthenticationEntryPoint
Multiple AuthenticationEntryPoint
PasswordEncoder
Salt
Custom filters
Summary
Integrating with Spring WebFlux
Spring MVC versus WebFlux
When to choose what?
Reactive support in Spring 5
Reactive in Spring MVC
Spring WebFlux
HandlerFunction
RouterFunction
Spring WebFlux server support
Reactive WebClient
Reactive WebTestClient
Reactive WebSocket
Spring WebFlux authentication architecture
Spring WebFlux authorization
Sample project
WebFlux project setup
Maven setup
Configuration class
The SpringWebFluxConfig class
Repository
Handler and router
Bootstrap application
Running the application
Adding security
Configuration classes
The UserDetailsService bean
The SpringSecurityFilterChain bean
Running the application
CURL
Browser
WebClient
Maven setup
Creating a WebClient instance
Handling errors
Sending requests and retrieving responses
Running and testing the application
Unit testing (WebTestClient)
Maven dependency
Test class
Spring Data
Maven dependency
MongoDB configuration
Setting up a model
Implementing a repository
Implementing a controller
Running the application
Authorization
Method security
Customization
Writing custom filters
Using WebFilter
Using HandlerFilterFunction
Summary
REST API Security
Important concepts
REST
JSON Web Token (JWT)
Structure of a token
Header
Payload
Signature
Modern application architecture
SOFEA
Reactive REST API
Simple REST API security
Spring Security configuration
Authentication success handler
Custom WebFilter namely JWTAuthWebFilter
New controller classes
Running the application and testing
Advanced REST API security
OAuth2 roles
Resource owner
Resource server
Client
Authorization server
Authorization grant types
Authorization code flow
Implicit flow
Client credentials
Resource owner password credentials
Access Token and Refresh Token
Spring Security OAuth project
OAuth2 and Spring WebFlux
Spring Boot and OAuth2
Sample project
Authorization server
Maven dependencies
Spring Boot run class
Spring Security config
Authorization server config
Application properties
Resource server
Maven dependencies
Spring Boot run class
Resource server config
Spring Security config
Spring MVC config class
Controller class
Application properties
Client application
Maven dependencies
Spring Boot class
OAuth client config
Spring Security config
Controller classes
Templates
Application properties
Running the project
Summary
Spring Security Add-Ons
Remember-me authentication
Creating a new table in MySQL database
Spring Security configuration
The custom login page
Running the application and testing
Session management
CSRF
CSP
CSP using Spring Security
Channel security
CORS Support
The Crypto module
Password encoding
Encryption
Key generation
Secret management
Starting by unsealing Vault
The Spring Boot project
The Maven dependency
HTTP Data Integrity Validator
What is HDIV?
The Bootstrap project
Maven dependencies
Spring Security configuration
Spring MVC configuration
HDIV configuration
The Model class
The Controller class
Pages
Running the application
Custom DSL
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
Security is one of the most difficult and high-pressured concerns of creating an application. The complexity of properly securing an application is compounded when you must integrate this with existing code, new technologies, and other frameworks. This book will show readers how to easily secure their Java applications with the tied-and-tested Spring Security framework, the highly customizable and powerful authentication and authorization framework.
Spring Security is a well-known and established Java/JEE framework that can provide enterprise-grade security features for your application with no trouble. It also has modules that enable us to integrate with a variety of authentication mechanisms, and we will be delving into each of those using hands-on coding in this book.
Many examples will still be explained using the Spring MVC web application framework, but will still have a flavor of reactive programming to them.
Reactive programming is gaining traction, and this aspect of Spring Security will be covered by showcasing Spring Security integration with the Spring WebFlux web application framework. In addition to reactive programming, the book will also delve into other Spring Security features in detail.
Finally, we will also bring in some of the products available on the market that can be used along with Spring Security to achieve some of the security features needed in modern applications. These products offer new/enhanced security capabilities, and work in harmony with Spring Security in all aspects. Some of the products discussed are also fully endorsed and supported by the Spring community.
This book is for anyone who fits into the following groups:
Any Spring Framework enthusiast who would like to integrate Spring Security into their application
Any passionate Java developer who would like to start using one of the very core modules of Spring Framework; namely, Spring Security
Experienced Spring Framework developers who would like to get their hands dirty with the newest Spring Security module and would also like to start coding applications with the reactive paradigm
Chapter 1, Overview of Spring 5 and Spring Security 5, introduces you to the new application requirements and then introduces you to reactive programming concepts. It touches on application security and what Spring Security brings to the table to address security concerns in an application. The chapter then gets into a bit more into Spring Security and then finally closes by explaining how the examples in this book are structured.
Chapter 2, Deep Diving into Spring Security, deep dives into the technical capability of core Spring Security; namely, Authentication and Authorization. The chapter then gets your hands dirty with some example code, in which we will set up a project using Spring Security. Then, in due course introduces you to the approach by which the code samples will be explained throughout the book.
Chapter 3, Authentication Using SAML, LDAP, and OAuth/OIDC, introduces you to three authentication mechanisms; namely, SAML, LDAP, and OAuth/OIDC. This is the first of two main chapters, in which we will dive deep into various authentication mechanisms supported by Spring Security using hands-on coding. We will be explaining each authentication mechanism using a simple example to cover the crux of the topic, and we'll be keeping the example simple for easy understanding.
Chapter 4, Authentication Using CAS and JAAS, introduces you to two more authentication mechanisms that are very much prevalent in enterprises—CAS and JAAS. This is the second of the two main chapters, similar to Chapter 3, Authentication Using SAML, LDAP, and OAuth/OIDC, which will initially cover the theoretical aspects of these authentication mechanisms. This chapter concludes the topic by implementing a fully-fledged example using Spring Security.
Chapter 5, Integrating with Spring WebFlux, introduces you to one of the new modules introduced as part of Spring 5—Spring WebFlux. Spring WebFlux is a web application framework in the Spring ecosystem that was built from the ground up to be fully reactive. We will bring the reactive parts of Spring Security out in this chapter and will also detail the Spring WebFlux framework itself. First we will introduce you to Spring WebFlux using an example and then we will build on the additional technical capabilities on top of the base application.
Chapter 6, REST API Security, starts off by introducing you to some of the important concepts in regards to REST and JWT. It then introduces OAuth concepts and, using hands-on coding examples, explains simple and advanced REST API security, focusing on utilizing Spring Security and Spring Boot modules in Spring Framework. The examples will use the OAuth protocol and will be using Spring Security to the fullest to secure REST APIs. In addition to that, JWT will be used to exchange claims between the server and client.
Chapter 7, Spring Security Add-Ons, introduces many products (open source and paid versions) that can be considered for use alongside Spring Security. These products are strong contenders that can be used to achieve the technical capability that you are looking for in your application to cover various security requirements. We will introduce a product to you by giving you the gist of the technical capability that needs addressing in your application, before taking a look at the product in question and explaining how it provides the solutions you require..
The book contains a number of examples, all coded and executed in a Macintosh machine using an IDE (IntelliJ). So, to follow the examples easily, usage of macOS and IntelliJ would help a great deal. However, all code can be executed using Macintosh, Windows, and Linux systems.
Basic to intermediate experience working on applications built using Java and Spring Framework is required to progress through the book easily.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Hands-On-Spring-Security-5-for-Reactive-Applications. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/HandsOnSpringSecurity5forReactiveApplications_ColorImages.pdf.
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Flux<T> is a Publisher<T> with basic flow operations and supports 0..n elements."
A block of code is set as follows:
public abstract class Flux<T> extends Object implements Publisher<T>
Any command-line input or output is written as follows:
curl http://localhost:8080/api/movie -v -u admin:password
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Enter the username as admin and password as password and click on Sign in."
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
This book expects readers to be conversant with Spring Framework (any version) and Spring Security (any version). This is an ice-breaker chapter that introduces the reader to some of the most important concepts; we will expand on them in subsequent chapters.
The chapter will introduce you to new application requirements and then to reactive programming concepts. It touches on application security and how Spring Security addresses security concerns in an application.
We'll continue with Spring Security and then close the chapter by explaining how the examples in this chapter are structured. This is quite important as I expect readers to be comfortable whenever a new concept is introduced in code.
In this chapter, we will cover the following topics:
New-generation application requirements
Reactive programming
Reactive applications
Spring Framework
Reactive landscape in Java
Spring Framework and reactive applications
Application security
Spring Security
Spring Security's core features
Spring Security 5's new features
The working of Spring Security
Core Spring Security modules
It's important that you understand how we will be using examples in this book. Since the book tries to give lots of detail on Spring Security 5 and its reactive aspects, we will not have a single use case throughout the book. Instead, we will keep creating small projects to help you understand each of the core concepts covered. Here are some of the important aspects of the code base within this book:
Most concepts will be covered using a standalone Spring Boot project.
At times, we will use the famous Spring Initializr (
https://start.spring.io/
) to bootstrap our sample Spring Boot application. In other cases, we will start with a base project that we already have and introduce more concepts through code.
Generally, we will be using Java configuration. At times, we might use XML-based configurations.
We will keep our examples as simple as possible so that we don't lose focus on the core concept being introduced.
Even though this book is focused on reactive applications, we will not be covering this each time it is introduced. At times, we will just be doing plain, old imperative programming as it is more important to know reactive programming and use it when required. It's not that we have to use reactive code everywhere possible, just use it where you see fit.
We will be using VS Code for all the projects, and we'll be using the extensions available in VS Code to the fullest. We will also be using the Spring Initializr extension rather than using online Spring Initializr.
We will be using Maven most of the time in this book. There might be a case where we try
Gradle.
Sometimes, we might use IntelliJ IDE and you'll see some screenshots showing this.
We'll be using the latest Spring Boot release version, namely
2.0.0. RELEASE
. This is the latest release version of Spring Boot at the time of writing this book.
Here are some of the core new application requirements:
Highly scalable
: The social platform has grown exponentially over the last decade and people are more tech-savvy than ever.
Resilient, fault-tolerant, and highly available
: downtime in your application is something which enterprises are not ready to take in modern times; downtime of even seconds is now creating huge losses for many big businesses.
High performance
: If your site is slow, people have a tendency to leave and search for alternatives. People have a short attention span and will not stay or come back if your website performs poorly.
Hyper-personalization
: Users need personalized websites rather than generic websites, and this puts huge pressure on servers to do many intensive analyses in real time.
With technology in everyone's hands (in some form or another, most people use technology), users are quite well-versed in privacy policies and application security. They are aware of most of the security requirements, and companies take time to educate users about the importance of security and the ways they should look for security flaws in applications. You might already know that if a site runs on HTTP as opposed to HTTPS (SSL) and Chrome tags, these sites quite clearly show the users as Not Secure in the address bar. With more people becoming knowledgeable about technology, these aspects are well-known among the majority of users and security has become one of the most talked about subjects in the IT landscape.
Another important aspect is data privacy. Some users are not concerned about sharing their data but some are quite reticent. Many governments recognize this fear and have started making many rules and regulations in this space. One such data privacy rule is the well-known General Data Protection Regulation (GDPR), which has been enforced since May 25th, 2018.
The European Union (EU