Statistics
61
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2025-12-10

AuthorLaurentiu Spilca

Spring Security in Action shows you how to prevent cross-site scripting and request forgery attacks before they do damage. You’ll start with the basics, simulating password upgrades and adding multiple types of authorization. As your skills grow, you'll adapt Spring Security to new architectures and create advanced OAuth2 configurations. By the time you're done, you'll have a customized Spring Security configuration that protects against threats both common and extraordinary. Summary While creating secure applications is critically important, it can also be tedious and time-consuming to stitch together the required collection of tools. For Java developers, the powerful Spring Security framework makes it easy for you to bake security into your software from the very beginning. Filled with code samples and practical examples, Spring Security in Action teaches you how to secure your apps from the most common threats, ranging from injection attacks to lackluster monitoring. In it, you'll learn how to manage system users, configure secure endpoints, and use OAuth2 and OpenID Connect for authentication and authorization. About the technology Security is non-negotiable. You rely on Spring applications to transmit data, verify credentials, and prevent attacks. Adopting "secure by design" principles will protect your network from data theft and unauthorized intrusions. About the book Spring Security in Action shows you how to prevent cross-site scripting and request forgery attacks before they do damage. You’ll start with the basics, simulating password upgrades and adding multiple types of authorization. As your skills grow, you'll adapt Spring Security to new architectures and create advanced OAuth2 configurations. By the time you're done, you'll have a customized Spring Security configuration that protects against threats both common and extraordinary. What's inside • Encoding passwords and authenticating users • Securing endpoints • Automating security testing • Setting

Tags
No tags
ISBN: 1617297739
Publisher: Manning Publications
Publish Year: 2020
Language: 英文
Pages: 560
File Format: PDF
File Size: 13.6 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

M A N N I N G Laurentiu Spilcă`
AuthenticationManager AuthenticationProvider objects Do you know if this authentication is valid? Sorry, I don’t understand this kind of authentication! I understand this kind of authentication but not the object itself, and I cannot tell if it’s valid or not. Yes. This is a valid authentication. Authentication 1 2 3
Spring Security in Action
ii
Spring Security in Action LAURENŢIU SPILCĂ M A N N I N G SHELTER ISLAND
For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2020 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. Manning Publications Co. Development editor: Marina Michaels 20 Baldwin Road Technical development editor: Nick Watts PO Box 761 Review editor: Mihaela Batinić Shelter Island, NY 11964 Production editor: Deirdre S. Hiam Copy editor: Frances Buran Proofreader: Katie Tennant Technical proofreader: Jean-François Morin Typesetter and cover designer: Marija Tudor ISBN 9781617297731 Printed in the United States of America
brief contents PART 1 FIRST STEPS ................................................................... 1 1 ■ Security today 3 2 ■ Hello Spring Security 33 PART 2 IMPLEMENTATION ......................................................... 59 3 ■ Managing users 61 4 ■ Dealing with passwords 86 5 ■ Implementing authentication 102 6 ■ Hands-on: A small secured web application 135 7 ■ Configuring authorization: Restricting access 153 8 ■ Configuring authorization: Applying restrictions 172 9 ■ Implementing filters 195 10 ■ Applying CSRF protection and CORS 213 11 ■ Hands-on: A separation of responsibilities 244 12 ■ How does OAuth 2 work? 284 13 ■ OAuth 2: Implementing the authorization server 316 14 ■ OAuth 2: Implementing the resource server 338 15 ■ OAuth 2: Using JWT and cryptographic signatures 360 16 ■ Global method security: Pre- and postauthorizations 387 17 ■ Global method security: Pre- and postfiltering 413 18 ■ Hands-on: An OAuth 2 application 433 19 ■ Spring Security for reactive apps 467 20 ■ Spring Security testing 490v
BRIEF CONTENTSvi
contents foreword xv preface xvii acknowledgments xix about this book xx about the author xxvi about the cover illustration xxvii PART 1 FIRST STEPS .................................................... 1 1 Security today 3 1.1 Spring Security: The what and the why 5 1.2 What is software security? 7 1.3 Why is security important? 12 1.4 Common security vulnerabilities in web applications 14 Vulnerabilities in authentication and authorization 15 What is session fixation? 16 ■ What is cross-site scripting (XSS)? 16 ■ What is cross-site request forgery (CSRF)? 18 Understanding injection vulnerabilities in web applications 18 Dealing with the exposure of sensitive data 19 ■ What is the lack of method access control? 22 ■ Using dependencies with known vulnerabilities 23 1.5 Security applied in various architectures 24 Designing a one-piece web application 24 ■ Designing security for a backend/frontend separation 26 ■ Understanding the OAuth 2 vii
CONTENTSviiiflow 27 ■ Using API keys, cryptographic signatures, and IP validation to secure requests 29 1.6 What will you learn in this book? 31 2 Hello Spring Security 33 2.1 Starting with the first project 34 2.2 Which are the default configurations? 38 2.3 Overriding default configurations 43 Overriding the UserDetailsService component 44 ■ Overriding the endpoint authorization configuration 48 ■ Setting the configuration in different ways 50 ■ Overriding the AuthenticationProvider implementation 53 ■ Using multiple configuration classes in your project 56 PART 2 IMPLEMENTATION .......................................... 59 3 Managing users 61 3.1 Implementing authentication in Spring Security 62 3.2 Describing the user 65 Demystifying the definition of the UserDetails contract 65 Detailing on the GrantedAuthority contract 66 ■ Writing a minimal implementation of UserDetails 67 ■ Using a builder to create instances of the UserDetails type 70 ■ Combining multiple responsibilities related to the user 71 3.3 Instructing Spring Security on how to manage users 74 Understanding the UserDetailsService contract 74 Implementing the UserDetailsService contract 75 Implementing the UserDetailsManager contract 78 4 Dealing with passwords 86 4.1 Understanding the PasswordEncoder contract 86 The definition of the PasswordEncoder contract 87 Implementing the PasswordEncoder contract 88 Choosing from the provided implementations of PasswordEncoder 90 ■ Multiple encoding strategies with DelegatingPasswordEncoder 93 4.2 More about the Spring Security Crypto module 97 Using key generators 97 ■ Using encryptors for encryption and decryption operations 99
CONTENTS ix5 Implementing authentication 102 5.1 Understanding the AuthenticationProvider 104 Representing the request during authentication 105 Implementing custom authentication logic 106 ■ Applying custom authentication logic 108 5.2 Using the SecurityContext 113 Using a holding strategy for the security context 114 ■ Using a holding strategy for asynchronous calls 116 ■ Using a holding strategy for standalone applications 118 ■ Forwarding the security context with DelegatingSecurityContextRunnable 119 Forwarding the security context with DelegatingSecurityContext- ExecutorService 121 5.3 Understanding HTTP Basic and form-based login authentications 124 Using and configuring HTTP Basic 124 ■ Implementing authentication with form-based login 127 6 Hands-on: A small secured web application 135 6.1 Project requirements and setup 136 6.2 Implementing user management 141 6.3 Implementing custom authentication logic 146 6.4 Implementing the main page 148 6.5 Running and testing the application 151 7 Configuring authorization: Restricting access 153 7.1 Restricting access based on authorities and roles 155 Restricting access for all endpoints based on user authorities 157 Restricting access for all endpoints based on user roles 165 Restricting access to all endpoints 169 8 Configuring authorization: Applying restrictions 172 8.1 Using matcher methods to select endpoints 173 8.2 Selecting requests for authorization using MVC matchers 178 8.3 Selecting requests for authorization using Ant matchers 185 8.4 Selecting requests for authorization using regex matchers 190
CONTENTSx9 Implementing filters 195 9.1 Implementing filters in the Spring Security architecture 198 9.2 Adding a filter before an existing one in the chain 199 9.3 Adding a filter after an existing one in the chain 203 9.4 Adding a filter at the location of another in the chain 205 9.5 Filter implementations provided by Spring Security 210 10 Applying CSRF protection and CORS 213 10.1 Applying cross-site request forgery (CSRF) protection in applications 213 How CSRF protection works in Spring Security 214 ■ Using CSRF protection in practical scenarios 220 ■ Customizing CSRF protection 226 10.2 Using cross-origin resource sharing 235 How does CORS work? 236 ■ Applying CORS policies with the @CrossOrigin annotation 240 ■ Applying CORS using a CorsConfigurer 242 11 Hands-on: A separation of responsibilities 244 11.1 The scenario and requirements of the example 245 11.2 Implementing and using tokens 248 What is a token? 248 ■ What is a JSON Web Token? 252 11.3 Implementing the authentication server 253 11.4 Implementing the business logic server 263 Implementing the Authentication objects 268 ■ Implementing the proxy to the authentication server 270 ■ Implementing the AuthenticationProvider interface 272 ■ Implementing the filters 274 ■ Writing the security configurations 280 Testing the whole system 281 12 How does OAuth 2 work? 284 12.1 The OAuth 2 framework 285 12.2 The components of the OAuth 2 authentication architecture 287 12.3 Implementation choices with OAuth 2 288 Implementing the authorization code grant type 289 Implementing the password grant type 293 ■ Implementing the
CONTENTS xiclient credentials grant type 295 ■ Using refresh tokens to obtain new access tokens 297 12.4 The sins of OAuth 2 299 12.5 Implementing a simple single sign-on application 299 Managing the authorization server 300 ■ Starting the implementation 303 ■ Implementing ClientRegistration 304 Implementing ClientRegistrationRepository 307 ■ The pure magic of Spring Boot configuration 309 ■ Obtaining details about an authenticated user 311 ■ Testing the application 311 13 OAuth 2: Implementing the authorization server 316 13.1 Writing your own authorization server implementation 318 13.2 Defining user management 319 13.3 Registering clients with the authorization server 322 13.4 Using the password grant type 325 13.5 Using the authorization code grant type 327 13.6 Using the client credentials grant type 333 13.7 Using the refresh token grant type 335 14 OAuth 2: Implementing the resource server 338 14.1 Implementing a resource server 341 14.2 Checking the token remotely 343 14.3 Implementing blackboarding with a JdbcTokenStore 350 14.4 A short comparison of approaches 358 15 OAuth 2: Using JWT and cryptographic signatures 360 15.1 Using tokens signed with symmetric keys with JWT 361 Using JWTs 361 ■ Implementing an authorization server to issue JWTs 363 ■ Implementing a resource server that uses JWT 367 15.2 Using tokens signed with asymmetric keys with JWT 370 Generating the key pair 372 ■ Implementing an authorization server that uses private keys 373 ■ Implementing a resource server that uses public keys 375 ■ Using an endpoint to expose the public key 377 15.3 Adding custom details to the JWT 380 Configuring the authorization server to add custom details to tokens 381 ■ Configuring the resource server to read the custom details of a JWT 383
CONTENTSxii16 Global method security: Pre- and postauthorizations 387 16.1 Enabling global method security 388 Understanding call authorization 389 ■ Enabling global method security in your project 391 16.2 Applying preauthorization for authorities and roles 392 16.3 Applying postauthorization 397 16.4 Implementing permissions for methods 401 17 Global method security: Pre- and postfiltering 413 17.1 Applying prefiltering for method authorization 414 17.2 Applying postfiltering for method authorization 420 17.3 Using filtering in Spring Data repositories 425 18 Hands-on: An OAuth 2 application 433 18.1 The application scenario 434 18.2 Configuring Keycloak as an authorization server 436 Registering a client for our system 441 ■ Specifying client scopes 442 ■ Adding users and obtaining access tokens 444 Defining the user roles 448 18.3 Implementing the resource server 453 18.4 Testing the application 462 Proving an authenticated user can only add a record for themself 462 ■ Proving that a user can only retrieve their own records 464 ■ Proving that only admins can delete records 465 19 Spring Security for reactive apps 467 19.1 What are reactive apps? 468 19.2 User management in reactive apps 473 19.3 Configuring authorization rules in reactive apps 477 Applying authorization at the endpoint layer in reactive apps 477 Using method security in reactive apps 484 19.4 Reactive apps and OAuth 2 486 20 Spring Security testing 490 20.1 Using mock users for tests 493 20.2 Testing with users from a UserDetailsService 500 20.3 Using custom Authentication objects for testing 501
CONTENTS xiii20.4 Testing method security 505 20.5 Testing authentication 507 20.6 Testing CSRF configurations 510 20.7 Testing CORS configurations 511 20.8 Testing reactive Spring Security implementations 512 appendix A Creating a Spring Boot project 515 index 519
CONTENTSxiv
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 inter- esting one? How times have changed! As the list of damaging, expensive, and simply embar- rassing 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 com- munities 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 secu- rity, 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.xv
FOREWORDxviUsing Spring Security won’t address every security concern in your application, but fol- lowing 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,xvii
PREFACExviiiand that might even expose security vulnerabilities. Too many times, I’ve been con- sulted 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 under- standing 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.