Leverage the power of Spring Security 6 to protect your modern Java applications from hackers Key Features Architect solutions that leverage Spring Security while remaining loosely coupled Implement authentication and authorization with SAML2, OAuth 2, hashing, and encryption algorithms Integrate
Spring Security: Effectively secure your web apps, RESTful services, cloud apps, 4th Edition
β Scribed by Badr Nasslahsen
- Publisher
- Packt Publishing Pvt Ltd
- Year
- 2024
- Tongue
- English
- Leaves
- 596
- Edition
- 4
- Category
- Library
No coin nor oath required. For personal study only.
β¦ Synopsis
Leverage the power of Spring Security 6 to protect your modern Java applications from hackers Key Features Architect solutions that leverage Spring Security while remaining loosely coupled Implement authentication and authorization with SAML2, OAuth 2, hashing, and encryption algorithms Integrate Spring Security with technologies such as microservices, Kubernetes, the cloud, and GraalVM native images Purchase of the print or Kindle book includes a free PDF eBook Book Description Knowing that experienced hackers are constantly on the prowl to attack your apps can make security one of the most challenging concerns of creating an app. The complexity of properly securing an app is compounded when you must also integrate this factor with legacy code, new technologies, and other frameworks. This book will help you easily secure your Java apps with Spring Security, a trusted and highly customizable authentication and access control framework.The book starts by showing you how to implement different authentication mechanisms before demonstrating how to properly restrict access to your app. You'll then cover tips for integrating Spring Security with popular web frameworks such as Thymeleaf. The book also features an example of how Spring Security defends against session fixation, moves into concurrency control, and how you can use session management for administrative functions. This fourth edition aligns with Java 17/21 and Spring Security 6, covering advanced security scenarios for RESTful web services and microservices. This ensures you gain a complete understanding of the issues surrounding stateless authentication and discover a concise approach to solving those issues.By the end of this book, you'll be able to integrate Spring Security 6 with GraalVM native images seamlessly, from start to finish. What you will learn Understand common security vulnerabilities and how to resolve them Implement authentication and authorization and learn how to map users to roles Integrate Spring Security with LDAP, Kerberos, SAML 2, OpenID, and OAuth Get to grips with the security challenges of RESTful web services and microservices Configure Spring Security to use Spring Data for authentication Integrate Spring Security with Spring Boot, Spring Data, and web applications Protect against common vulnerabilities like XSS, CSRF, and Clickjacking Who this book is for If you're a Java web developer or an architect with fundamental knowledge of Java 17/21, web services, and the Spring Framework, this book is for you. No previous experience with Spring Security is needed to get started with this book.
β¦ Table of Contents
Spring Security
Contributors
About the author
About the reviewer
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Code in Action
Conventions used
Get in touch
Share Your Thoughts
Download a free PDF copy of this book
Part 1: Fundamentals of Application Security
1
Anatomy of an Unsafe Application
Exploring software architecture styles
Monolithic architecture
N-Tier architecture (layered architecture)
SOA
Microservices architecture
Choosing between traditional web applications and Single-Page Applications
Understanding security audit
Exploring the example application
The JBCP calendar application architecture
Reviewing the audit results
Addressing the security audit findings
Authentication
Authorization
Database credential security
Sensitive information
Transport-level protection
Using Spring Security 6 to address security concerns
Technical requirements
Summary
2
Getting Started with Spring Security
Hello Spring Security
Importing the sample application
Updating your dependencies
Implementing a Spring Security configuration
Updating your web configuration
Running a secured application
Common problems
A little bit of polish
Customizing login
Summary
3
Custom Authentication
Authentication architecture in Spring Security
The SecurityContextHolder class
The SecurityContext interface
The Authentication interface
The AuthenticationManager interface
The ProviderManager class
The AuthenticationProvider interface
Exploring the JBCP calendar architecture
The CalendarUser object
The Event object
The CalendarService interface
The UserContext interface
The SpringSecurityUserContext interface
Logging in new users using SecurityContextHolder
Managing users in Spring Security
Logging in a new user to an application
Updating SignupController
Creating a custom UserDetailsService object
The CalendarUserDetailsService class
Configuring UserDetailsService
Removing references to UserDetailsManager
The CalendarUserDetails object
The SpringSecurityUserContext simplifications
Creating a custom AuthenticationProvider object
Creating CalendarUserAuthenticationProvider
Configuring the CalendarUserAuthenticationProvider object
Authenticating with different parameters
Which authentication method should you use?
Summary
Part 2: Authentication Techniques
4
JDBC-based Authentication
Installing the required dependencies
Using the H2 database
Provided JDBC scripts
Configuring the H2 embedded database
Configuring a JDBC UserDetailsManager implementation
The default user schema of Spring Security
Defining users
Defining user authorities
Exploring UserDetailsManager interface
Group-based access control
Configuring group-based access control
Support for a custom schema
Determining the correct JDBC SQL queries
Updating the SQL scripts that are loaded
The CalendarUser authority SQL
Inserting custom authorities
Configuring JdbcUserDetailsManager to use custom SQL queries
Configuring secure passwords
Exploring the PasswordEncoder interface
The DelegatingPasswordEncoder implementation
Configuring password encoding
Configuring the PasswordEncoder method
Making Spring Security aware of the PasswordEncoder method
Using salt in Spring Security
Updating the Spring Security configuration
Migrating existing passwords
Updating DefaultCalendarUserService
Trying out salted passwords
Summary
5
Authentication with Spring Data
Spring Data JPA
Updating our dependencies
Reconfiguring the database configuration
Initializing the database
Refactoring from SQL to ORM
Mapping domain objects using JPA
Spring Data repositories
Data access objects
Application services
The UserDetailsService object
Refactoring from an RDBMS to a document database
Document database implementation with MongoDB
Updating our dependencies
Reconfiguring the database configuration in MongoDB
Initializing the MongoDB database
Mapping domain objects with MongoDB
Data access objects in MongoDB
Summary
6
LDAP Directory Services
Understanding LDAP
LDAP
Troubleshooting embedded LDAP
Understanding how Spring LDAP authentication works
Authenticating user credentials
Demonstrating authentication with JXplorer
Determining roles with Jxplorer
Mapping additional attributes of UserDetails
Advanced LDAP configuration
LDAP password encoding and storage
Configuring the UserDetailsContextMapper object
Implicit configuration of UserDetailsContextMapper
Viewing additional user details
Configuring LdapUserDetailsService
Updating AccountController to use LdapUserDetailsService
Integrating Spring Security with an external LDAP server
Explicit LDAP bean configuration
Configuring an external LDAP server reference
Performing a search to locate the user in the LDAP directory
Delegating role discovery to UserDetailsService
Integrating with Microsoft Active Directory via LDAP
Built-in AD support in Spring Security 6.1
Summary
7
Remember-me Services
What is remember-me?
Dependencies
The token-based remember-me feature
SHA-256 Algorithm
Remember-me signature
Is remember-me secure?
Authorization rules for remember-me
Persistent remember-me
Configuring the persistent-based remember-me feature
How does the persistent-based remember-me feature work?
JPA-based PersistentTokenRepository
Custom RememberMeServices
Are database-backed persistent tokens more secure?
Cleaning up the expired remember-me sessions
The remember-me architecture
Remember-me and the user life cycle
Restricting the remember-me feature to an IP address
Custom cookie and HTTP parameter names
Summary
8
Client Certificate Authentication with TLS
How does client certificate authentication work?
Setting up the client certificate authentication infrastructure
Importing the certificate key pair into a browser
Troubleshooting client certificate authentication
Configuring client certificate authentication in Spring Security
Configuring client certificate authentication using the security namespace
Configuring client certificate authentication using Spring beans
Additional capabilities of bean-based configuration
Considerations when implementing client certificate authentication
Summary
Part 3: Exploring OAuth 2 and SAML 2
9
Opening up to OAuth 2
The Promising World of OAuth 2
Why do we need OpenID Connect?
How OpenID Connect Works
Signing up for an OAuth 2 application
Enabling OAuth 2.0 Login with Spring Security
Customize the Login Page
Additional OAuth 2 providers
Configuring Custom Provider Properties
Enabling Proof Key for Code Exchange (PKCE) support
OpenID Connect 1.0 Logout
Automatic User Registration
Mapping User Authorities
Is OAuth 2 secure?
Summary
10
SAML 2 Support
What is SAML?
SAML 2.0 Login with Spring Security
Add a SAML application on OKTA
Creating the user principal in OKTA
Additional required dependencies
Specifying IdP Metadata
Retrieving the SAML 2 Authenticated Principal
Parsing SAML 2 metadata
Generating SAML 2 Metadata
Adapting RelyingPartyRegistration lookup
Overriding SAML Spring Boot Auto Configuration
Creating a custom RelyingPartyRegistrationRepository
Creating custom authorities with Spring Security SAML
Performing Single Logout
Summary
Part 4: Enhancing Authorization Mechanisms
11
Fine-Grained Access Control
Integrating Spring Expression Language (SpEL)
The WebSecurityExpressionRoot class
The MethodSecurityExpressionRoot class
Page-level authorization
Conditional rendering with the Thymeleaf Spring Security tag library
Conditional rendering based on URL access rules
Conditional rendering using SpEL
Using controller logic to conditionally render content
The WebInvocationPrivilegeEvaluator class
What is the best way to configure in-page authorization?
Method-level security
Interface-based proxies
JSR-250 compliant standardized rules
Gradle dependencies
Method security using Springβs @Secured annotation
Method security rules incorporating method parameters
Method security rules incorporating returned values
Securing method data using role-based filtering
Prefiltering collections with @PreFilter
Comparing method authorization types
Practical considerations for annotation-based security
Summary
12
Access Control Lists
The conceptual module of an ACL
ACLs in Spring Security
Basic configuration of Spring Security ACL support
Gradle dependencies
Defining a simple target scenario
Adding ACL tables to the H2 database
Configuring SecurityExpressionHandler
The AclPermissionCacheOptimizer object
Optimizing AclPermission Cache
The JdbcMutableAclService object
The BasicLookupStrategy class
Creating a simple ACL entry
Advanced ACL topics
How permissions work
The custom ACL permission declaration
Enabling ACL permission evaluation
Mutable ACLs and authorization
Considerations for a typical ACL deployment
ACL scalability and performance modeling
Do not discount custom development costs
Should I use Spring Security ACL?
Summary
13
Custom Authorization
Authorizing the Requests
Handling of Invocations
The AuthorizationManager class
Delegate-based AuthorizationManager Implementations
Modifying AccessDecisionManager and AccessDecisionVoter
Legacy Authorization Components
The AccessDecisionManager
AccessDecisionManager Implementations Based on Voting
Dynamically defining access control to URLs
Configuring the RequestConfigMappingService
Registering a custom SecurityMetadataSource
Creating a custom expression
Configuring a custom SecurityExpressionRoot
Configuring a custom SecurityExpressionHandler
Configuring and using CustomWebSecurityExpressionHandler
Alternative to a CustomWebSecurityExpressionHandler
Declaring a custom AuthorizationManager
Summary
Part 5: Advanced Security Features and Deployment Optimization
14
Session Management
Configuring session fixation protection
Understanding session fixation attacks
Preventing session fixation attacks with Spring Security
Simulating a session fixation attack
Comparing the session-fixation-protection options
Restricting the number of concurrent sessions per user
Configuring concurrent session control
Understanding concurrent session control
Testing concurrent session control
Configuring expired session redirect
Common problems with concurrency control
Preventing authentication instead of forcing logout
Other benefits of concurrent session control
Displaying active sessions for a user
How Spring Security use the HttpSession method?
The HttpSessionSecurityContextRepository interface
Configuring how Spring Security uses HttpSession
Debugging with Spring Securityβs DebugFilter
Summary
15
Additional Spring Security Features
Security vulnerabilities
Cross-Site Scripting
Cross-Site Request Forgery
Synchronizer token pattern
When to use CSRF protection
Default CSRF support
CSRF caveats
Security HTTP response headers
Cache-Control
Content-Type Options
HTTP Strict Transport Security
HTTP Public Key Pinning (HPKP)
X-Frame-Options
CSP
Referrer Policy
Feature Policy
Permissions Policy
Clear Site Data
Static headers
The HeadersWriter instance
The DelegatingRequestMatcherHeaderWriter class
Testing Spring Security Applications
Reactive Applications Support
Summary
16
Migration to Spring Security 6
Exploit Protection
Protecting against CSRF attacks
CSRF attack with WebSocket support
Configuration Migrations
Adding @Configuration annotation to @Enable* annotations
Using the new requestMatchers methods
Using the new securityMatchers methods
Replacing the WebSecurityConfigurerAdapter class
Password Encoding Updates
Session Management Updates
Authentication Updates
Authorization Updates
Leveraging AuthorizationManager for Message Security
Deprecating AbstractSecurityWebSocketMessageBrokerConfigurer
Employing AuthorizationManager for Request Security
OAuth Updates
SAML Updates
Applying the migration steps from Spring Security 5.x to Spring Security 6.x
Reviewing Application dependencies
Migrating from the javax to jakarta namespace
Replacing WebSecurityConfigurerAdapter and exposing SecurityFilterChain Bean
Summary
17
Microservice Security with OAuth 2 and JSON Web Tokens
What are microservices?
Monoliths
Microservices
Service-oriented architectures
Microservice security
The OAuth 2 specification
Access tokens
Grant types
JSON Web Tokens
Token structure
JWT Authentication in Spring Security
OAuth 2 support in Spring Security
Resource owner
Resource server
Authorization server
OAuth 2 resource minimal configuration properties
Defining the JWK Set URI for the authorization server
Providing Audience Information
Configuring Authorization using SecurityFilterChain
Token requests
Endpoints requests
Configuring Authorization using @PreAuthorize annotation
Summary
18
Single Sign-On with the Central Authentication Service
Introducing the Central Authentication Service
High-level CAS authentication flow
Spring Security and CAS
Required dependencies
Installing and configuring CAS
Configuring basic CAS integration
Configuring the CAS properties
Adding the CasAuthenticationEntryPoint object
Enabling CAS ticket verification
Single Logout
Configuring Single Logout
Clustered environments
Proxy ticket authentication for stateless services
Configuring proxy ticket authentication
Using proxy tickets
Authenticating proxy tickets
Customizing the CAS server
CAS WAR overlay
How does the CAS internal authentication work?
Configuring CAS to connect to our embedded LDAP server
Getting the UserDetails object from a CAS assertion
Returning LDAP attributes in the CAS response
Mapping LDAP attributes to CAS attributes
Acquiring a UserDetails from CAS
The GrantedAuthorityFromAssertionAttributesUser object
How is attribute retrieval useful?
Additional CAS capabilities
Summary
19
Build GraalVM Native Images
Introducing GraalVM
What are native images?
Key features of GraalVM
Security benefits of GraalVM
GraalVM images using Buildpacks
Building GraalVM images using Buildpacks and Gradle
Building GraalVM images using Buildpacks and Maven
Running GraalVM images from Buildpacks
Building a native image using Native Build Tools
Prerequisites
Building GraalVM images using Native Build Tools and Maven
Building GraalVM images using Native Build Tools and Gradle
Running GraalVM images from Native Build Tools
Method Security in GraalVM Native Image
Summary
Appendix β Additional Reference Material
Build tools
Gradle build tool
Maven build tool
Getting started with the JBCP calendar sample code
Sample code structure
Using the samples in IntelliJ IDEA
Using the samples in Eclipse
Starting the samples from the command line
Generating a server certificate
Supplementary materials
Index
Why subscribe?
Other Books You May Enjoy
Packt is searching for authors like you
Share Your Thoughts
Download a free PDF copy of this book
π SIMILAR VOLUMES
This book was written using Swift 2.0, Alamofire 3.1, Xcode 7, and iOS 9.<br><br>All code samples included.<br><br>This book is for:<br><br>- Software developers getting started with iOS but experienced in other languages<br><br>- Front-end devs looking to implement native UIs for iOS apps (no CSS,
Pack; 2018; ISBN: 978-1788995979; 268 ΡΡΡ. Learn effective ways to secure your apps with Spring and Spring WebFlux. Key Features - Provide authentication, authorization and other security features for Java applications. - Learn how to secure microservices, cloud, and serverless applications
This book will serve as a practical companion for you to learn about common vulnerabilities when using RESTful services, and will provide you with an indispensable knowledge of the tools you can use to implement and test security on your applications. It will cover the fine details of setting up RES
Practical and precise, this hands-on IIS guide with ready answers is designed for IT professionals. Inside, you'll find expert insights, tips, tricks and workarounds that will show you how to make the most of IIS in the shortest amount of time possible. During the course of reading this book, you wi
Effective Physical Security, Fourth Edition is a best-practices compendium that details the essential elements to physical security protection. The book contains completely updated sections that have been carefully selected from the authorsβ work that set the standard: <i>Handbook of Loss Prevention