100% found this document useful (5 votes)
222 views

Pro Spring Security: Securing Spring Framework 5 and Boot 2-based Java Applications 2nd Edition Carlo Scarioni download pdf

Applications

Uploaded by

toreskezar37
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (5 votes)
222 views

Pro Spring Security: Securing Spring Framework 5 and Boot 2-based Java Applications 2nd Edition Carlo Scarioni download pdf

Applications

Uploaded by

toreskezar37
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Download the Full Version of textbook for Fast Typing at textbookfull.

com

Pro Spring Security: Securing Spring Framework 5


and Boot 2-based Java Applications 2nd Edition
Carlo Scarioni

https://textbookfull.com/product/pro-spring-security-
securing-spring-framework-5-and-boot-2-based-java-
applications-2nd-edition-carlo-scarioni/

OR CLICK BUTTON

DOWNLOAD NOW

Download More textbook Instantly Today - Get Yours Now at textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Pro Spring MVC with WebFlux: Web Development in Spring


Framework 5 and Spring Boot 2 2nd Edition Marten Deinum

https://textbookfull.com/product/pro-spring-mvc-with-webflux-web-
development-in-spring-framework-5-and-spring-boot-2-2nd-edition-
marten-deinum/
textboxfull.com

Pro Spring MVC with WebFlux: Web Development in Spring


Framework 5 and Spring Boot 2 2nd Edition Marten Deinum

https://textbookfull.com/product/pro-spring-mvc-with-webflux-web-
development-in-spring-framework-5-and-spring-boot-2-2nd-edition-
marten-deinum-2/
textboxfull.com

Pro Spring MVC with WebFlux Web Development in Spring


Framework 5 and Spring Boot 2 Second Edition Marten Deinum
Iuliana Cosmina
https://textbookfull.com/product/pro-spring-mvc-with-webflux-web-
development-in-spring-framework-5-and-spring-boot-2-second-edition-
marten-deinum-iuliana-cosmina/
textboxfull.com

Spring Boot Persistence Best Practices: Optimize Java


Persistence Performance in Spring Boot Applications 1st
Edition Anghel Leonard
https://textbookfull.com/product/spring-boot-persistence-best-
practices-optimize-java-persistence-performance-in-spring-boot-
applications-1st-edition-anghel-leonard/
textboxfull.com
Practical Microservices Architectural Patterns: Event-
Based Java Microservices with Spring Boot and Spring Cloud
Christudas
https://textbookfull.com/product/practical-microservices-
architectural-patterns-event-based-java-microservices-with-spring-
boot-and-spring-cloud-christudas/
textboxfull.com

Pro Spring 5: an in-depth guide to the Spring framework


and its tools Cosmina

https://textbookfull.com/product/pro-spring-5-an-in-depth-guide-to-
the-spring-framework-and-its-tools-cosmina/

textboxfull.com

Practical Microservices Architectural Patterns - Event-


Based Java Microservices with Spring Boot and Spring Cloud
1st Edition Binildas Christudas
https://textbookfull.com/product/practical-microservices-
architectural-patterns-event-based-java-microservices-with-spring-
boot-and-spring-cloud-1st-edition-binildas-christudas/
textboxfull.com

Spring Quick Reference Guide: A Pocket Handbook for Spring


Framework, Spring Boot, and More Adam L. Davis

https://textbookfull.com/product/spring-quick-reference-guide-a-
pocket-handbook-for-spring-framework-spring-boot-and-more-adam-l-
davis/
textboxfull.com

Spring Boot 2 0 Projects Build production grade reactive


applications and microservices with Spring Boot English
Edition Mohamed Shazin Sadakath
https://textbookfull.com/product/spring-boot-2-0-projects-build-
production-grade-reactive-applications-and-microservices-with-spring-
boot-english-edition-mohamed-shazin-sadakath/
textboxfull.com
Pro Spring
Security
Securing Spring Framework 5 and
Boot 2-based Java Applications

Second Edition

Carlo Scarioni
Massimo Nardone
Pro Spring Security
Securing Spring Framework 5 and
Boot 2-based Java Applications
Second Edition

Carlo Scarioni
Massimo Nardone
Pro Spring Security: Securing Spring Framework 5 and Boot 2-based
Java Applications
Carlo Scarioni Massimo Nardone
Surbiton, UK HELSINKI, Finland

ISBN-13 (pbk): 978-1-4842-5051-8 ISBN-13 (electronic): 978-1-4842-5052-5


https://doi.org/10.1007/978-1-4842-5052-5

Copyright © 2019 by Carlo Scarioni and Massimo Nardone


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not
identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Steve Anglin
Development Editor: Matthew Moodie
Coordinating Editor: Mark Powers
Cover designed by eStudioCalamar
Cover image designed by Freepik (www.freepik.com)
Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street,
6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-
sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member
(owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a
Delaware corporation.
For information on translations, please e-mail editorial@apress.com; for reprint, paperback, or audio rights,
please email bookpermissions@springernature.com.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub via the book’s product page, located at www.apress.com/9781484250518. For more
detailed information, please visit www.apress.com/source-code.
Printed on acid-free paper
I would like to dedicate this book to the memory of my
beloved late mother, Maria Augusta Ciniglio. Thanks, Mom,
for all the great things you have taught me, for making me a
good person, for making me study to become a computing scientist,
and for the great memories you left me. You will be loved and
missed forever. I love you, Mom. RIP.
—Massimo
Table of Contents
About the Authors���������������������������������������������������������������������������������������������������� ix

About the Technical Reviewer��������������������������������������������������������������������������������� xi


Acknowledgments������������������������������������������������������������������������������������������������� xiii

Introduction�������������������������������������������������������������������������������������������������������������xv

Chapter 1: The Scope of Security����������������������������������������������������������������������������� 1


The Network Security Layer���������������������������������������������������������������������������������������������������������� 2
The Operating System Layer��������������������������������������������������������������������������������������������������������� 3
The Application Layer�������������������������������������������������������������������������������������������������������������������� 3
Authentication������������������������������������������������������������������������������������������������������������������������� 4
Authorization��������������������������������������������������������������������������������������������������������������������������� 5
ACLs���������������������������������������������������������������������������������������������������������������������������������������� 6
Authentication and Authorization: General Concepts�������������������������������������������������������������������� 6
What to Secure��������������������������������������������������������������������������������������������������������������������������� 10
More Security Concerns�������������������������������������������������������������������������������������������������������������� 11
Java Options for Security������������������������������������������������������������������������������������������������������������ 12
Summary������������������������������������������������������������������������������������������������������������������������������������ 14

Chapter 2: Introducing Spring Security������������������������������������������������������������������ 15


What Is Spring Security?������������������������������������������������������������������������������������������������������������� 15
Where Does Spring Security Fit In?�������������������������������������������������������������������������������������������� 17
Spring Security Overview����������������������������������������������������������������������������������������������������������� 20
Spring Framework 5: A Quick Overview�������������������������������������������������������������������������������������� 23
Dependency Injection������������������������������������������������������������������������������������������������������������ 25
Aspect-Oriented Programming���������������������������������������������������������������������������������������������� 26

v
Table of Contents

What’s New in Spring Security 5?����������������������������������������������������������������������������������������������� 28


Summary������������������������������������������������������������������������������������������������������������������������������������ 34

Chapter 3: Setting Up the Scene����������������������������������������������������������������������������� 35


Setting Up the Development Environment���������������������������������������������������������������������������������� 35
Creating a New Java Web Application Project���������������������������������������������������������������������������� 42
Creating a New Spring Security v5 Project��������������������������������������������������������������������������������� 46
Spring Security v5 Source����������������������������������������������������������������������������������������������������� 46
Spring Security Taglibs��������������������������������������������������������������������������������������������������������������� 50
Introducing Cross-Site Request Forgery������������������������������������������������������������������������������������� 51
Adding Spring Security v5 (and Spring Core Itself) to the Project���������������������������������������������� 51
Configuring the Web Project to Be Aware of Spring Security v5������������������������������������������������� 56
Summary������������������������������������������������������������������������������������������������������������������������������������ 68

Chapter 4: Spring Security Architecture and Design���������������������������������������������� 69


What Components Make Up Spring Security?���������������������������������������������������������������������������� 69
The 10,000-Foot View������������������������������������������������������������������������������������������������������������ 69
The 1,000-Foot View�������������������������������������������������������������������������������������������������������������� 70
The 100-Foot View����������������������������������������������������������������������������������������������������������������� 71
Good Design and Patterns in Spring Security��������������������������������������������������������������������������� 113
Strategy Pattern������������������������������������������������������������������������������������������������������������������ 114
Decorator Pattern���������������������������������������������������������������������������������������������������������������� 114
SRP�������������������������������������������������������������������������������������������������������������������������������������� 115
DI����������������������������������������������������������������������������������������������������������������������������������������� 115
Summary���������������������������������������������������������������������������������������������������������������������������������� 115

Chapter 5: Web Security��������������������������������������������������������������������������������������� 117


Introducing the Simple Example Application���������������������������������������������������������������������������� 117
The Special URLs���������������������������������������������������������������������������������������������������������������������� 135
Custom Login Form������������������������������������������������������������������������������������������������������������� 135
Basic HTTP Authentication�������������������������������������������������������������������������������������������������� 143
Digest Authentication���������������������������������������������������������������������������������������������������������� 145

vi
Table of Contents

Remember-Me Authentication��������������������������������������������������������������������������������������������� 148


Logging Out������������������������������������������������������������������������������������������������������������������������� 151
Session Management���������������������������������������������������������������������������������������������������������� 154
Forcing the Request to HTTPS��������������������������������������������������������������������������������������������� 155
Summary���������������������������������������������������������������������������������������������������������������������������������� 157

Chapter 6: Configuring Alternative Authentication Providers������������������������������ 159


Database-Provided Authentication�������������������������������������������������������������������������������������������� 160
Creating the Basic Tables���������������������������������������������������������������������������������������������������� 173
Using Groups����������������������������������������������������������������������������������������������������������������������� 175
Using Existing Schemas������������������������������������������������������������������������������������������������������ 177
LDAP Authentication������������������������������������������������������������������������������������������������������������������ 179
Installing and Configuring LDAP������������������������������������������������������������������������������������������ 180
X.509 Authentication����������������������������������������������������������������������������������������������������������������� 199
OAuth 2������������������������������������������������������������������������������������������������������������������������������������� 215
JSON Web Token����������������������������������������������������������������������������������������������������������������������� 216
Spring WebSockets������������������������������������������������������������������������������������������������������������������� 217
JAAS Authentication������������������������������������������������������������������������������������������������������������������ 218
Central Authentication Service Authentication�������������������������������������������������������������������������� 218
Overview������������������������������������������������������������������������������������������������������������������������������ 218
Summary���������������������������������������������������������������������������������������������������������������������������������� 219

Chapter 7: Business Object Security with ACLs��������������������������������������������������� 221


The Security Example Application��������������������������������������������������������������������������������������������� 221
Accessing Secured Objects������������������������������������������������������������������������������������������������������� 256
Filtering Returned Objects�������������������������������������������������������������������������������������������������������� 263
Test Scenario 7-7���������������������������������������������������������������������������������������������������������������� 268
Securing the View Layer with ACLs������������������������������������������������������������������������������������������� 273
The Cost of ACLs����������������������������������������������������������������������������������������������������������������������� 275
Summary���������������������������������������������������������������������������������������������������������������������������������� 277

vii
Table of Contents

Chapter 8: Customizing and Extending Spring Security��������������������������������������� 279


Spring Security Extension Points���������������������������������������������������������������������������������������������� 279
Plugging into the Spring Security Event System����������������������������������������������������������������������� 280
Authorization-Related Events���������������������������������������������������������������������������������������������� 282
Authentication-Related Events�������������������������������������������������������������������������������������������� 284
Session-Related Events������������������������������������������������������������������������������������������������������� 288
Your Own AuthenticationProvider and UserDetailsService�������������������������������������������������� 290
Password Encryption���������������������������������������������������������������������������������������������������������������� 332
Handling Errors and Entry Points����������������������������������������������������������������������������������������� 334
Changing the Security Interceptor��������������������������������������������������������������������������������������� 340
Spring Security Extensions Project������������������������������������������������������������������������������������� 344
Summary���������������������������������������������������������������������������������������������������������������������������������� 344

Chapter 9: Integrating Spring Security with Other Frameworks and


Languages������������������������������������������������������������������������������������������������������������ 345
Spring Security with Struts 2���������������������������������������������������������������������������������������������������� 346
Spring Security with Spring Web Flow�������������������������������������������������������������������������������������� 357
Spring Security in Other JVM Languages��������������������������������������������������������������������������������� 371
Spring Security and Ruby (JRuby)�������������������������������������������������������������������������������������������� 372
Web-Layer Security in Rails������������������������������������������������������������������������������������������������������ 374
Spring Security, Groovy, and Grails������������������������������������������������������������������������������������������� 381
Using Grails to Secure the Web Layer with URL Rules������������������������������������������������������������� 382
Using Grails Security at the Method Level�������������������������������������������������������������������������������� 386
Spring Security and Scala��������������������������������������������������������������������������������������������������������� 387
Summary���������������������������������������������������������������������������������������������������������������������������������� 399

Appendix A: Reference Material��������������������������������������������������������������������������� 401

Index��������������������������������������������������������������������������������������������������������������������� 403

viii
About the Authors
Carlo Scarioni is a passionate software developer, motivated
by learning and applying innovative and interesting software
development tools, techniques, and methodologies.
His professional objectives are the following: to be in a
technology-oriented enterprise where the technical staff is
the soul of the company; to be on an important IT team; to
be able to design and develop state-of-the-art software; to
be able to apply new knowledge every day, in innovative
ways, and with a great degree of freedom; to architect,
design, and develop software that uses the best practices of
the field; and to play with the latest technologies, learn every day, and participate in the
research and innovation of software products. His specialties are TDD, object-oriented
principles and design patterns, Java/JEE, Spring, application servers, SQL and NoSQL
(MongoDB), multithreading, messaging, Enterprise Integration Patterns, Ruby, and
RoR. His certifications are Sun Certified Enterprise Architect (Part I), Sun Certified Java
Programmer, Sun Certified Business Component Developer, SpringSource Certified
Professional, and IBM SOA Certified Associate.

Massimo Nardone has more than 24 years of experience


in security, web/mobile development, cloud, and IT
architecture. His true IT passions are security and Android.
He has been programming and teaching how to program with
Android, Perl, PHP, Java, VB, Python, C/C++, and MySQL for
more than 20 years. He holds a Master of Science degree in
Computing Science from the University of Salerno, Italy.
His technical skills include security, Android, cloud, Java,
MySQL, Drupal, Cobol, Perl, web and mobile development,
MongoDB, Couchbase, C/C++, WebGL, Python, Pro Rails,
Django CMS, Jekyll, Scratch, etc.

ix
About the Authors

He has worked as a visiting lecturer and supervisor for exercises at the Networking
Laboratory of the Helsinki University of Technology (Aalto University). He holds four
international patents (in the PKI, SIP, SAML, and Proxy areas). He currently works as
an Executive Security Consultant, OT Security Leader, and Chief Information Security
Office (CISO) for IBM, and he is member of ISACA Finland Chapter Board.
Massimo is the coauthor of Pro JPA in Java EE 8 (Apress, 2018), Beginning EJB in Java
EE 8 (Apress, 2018), and Pro Android Games (Apress, 2015); he also reviewed more than
45 IT books for different publishers.

x
About the Technical Reviewer
Iuliana Cosmina is a Spring-certified Web Application Developer and a Spring-certified
Spring Professional, as defined by Pivotal, the makers of Spring Framework, Boot, and
other tools. She is the author of books with Apress on core Spring certification and
Spring-certified web development. She is a software architect at Bearing Point Software
and is an active coder and software contributor on GitHub, Stack Overflow, and more.

xi
Acknowledgments
This book is definitely the work of more than one person. The people involved in the
preparation of this book have brought so much experience and quality to the final
version that the end product is many times better than if I had done all the work myself.
Their input ranged from improving text style, to introducing better ways to present
concepts, to performing code reviews and suggesting general improvements that have
made this book a much better reading experience.
I am talking, of course, about the great people at Apress who have been with me
along the full journey of writing this book. I’m talking about Steve Anglin, who initiated
me into the project, kept an eye from afar on the progress of the book, and tried to make
sure I kept on track as much as possible. I’m talking about Kevin Shea, who was my main
editorial contact and made sure that I stayed on schedule with the book and helped
with advice and support. I’m talking about Tom Welsh, who had the great responsibility
of reading every chapter as I was writing it; he gave me great input on each section,
including helping with my use of English grammar as well as ways to make the different
parts more attractive to potential readers. I am talking about Manuel Jordan, who not
only read every single chapter in a very detailed way, but also took on the laborious job
of evaluating and executing every single line of code and making sure that the book
provides code samples that can be reproduced by the readers in their own environments.
His input is greatly appreciated, and it is the difference between having a full book or
a half a book. There were, of course, many more people at Apress involved in the full
review phases of the book, and I want to say “thank you for your help” to all of them.
I would like to also thank the creators, committers, and community of Spring and
Spring Security for creating such an amazing piece of software and making it available to
everyone. A big thank you to them for letting all developers share their knowledge and
ways of work by freely distributing the source code of the different projects covered by
the SpringSource umbrella. They make us all wiser and better developers.
Finally, I want to thank my wife for being with me all the time and motivating me to
keep going forward.

—Carlo Scarioni

xiii
Acknowledgments

Many thanks go to my wonderful family—my wife, Pia, and my children, Luna,


Leo, and Neve—for supporting me while I was working on this book. You are the most
beautiful reason of my life.
I want to thank my beloved late mother, Maria Augusta Ciniglio, who always
supported and loved me so much. I will love and miss you forever, my dearest mom.
Thanks to my beloved father, Giuseppe, and my brothers, Mario and Roberto, for
your endless love and for being the best dad and brothers in the world.
I also want to dedicate this book to my late, dearest cousin, Gerardo “Amerigo”
Nardone. You will be missed.
Thanks a lot to Steve Anglin and Matthew Moodie for giving me the opportunity
to work as writer on this book, as well as to Mark Powers for doing such a great job
during the editorial process and supporting me all the time, and of course the technical
reviewers of this book for helping me to make a better book.

—Massimo Nardone

xiv
Introduction
Denying the impact of the Spring Framework in the Java world would be simply
impossible. Spring has brought so many advantages to the Java developer that we could
say it has made better developers of all of us. The good ones, the average ones. All of us.
The previous version of this book utilized Spring Security 3. Therefore, it is very
important to note, in this new edition of the book, the most important changes from v3
to v5. Spring Security v5 is now part of Pivotal since SpringSource is no longer used.
Spring Framework 5 was published in September of 2017 and it can be considered the
first major Spring Framework release since version 4 was released in December of 2013.
Spring’s core building blocks of dependency injection and aspect-oriented
programming are widely applicable to many business and infrastructure concerns, and
certainly application security can benefit from these core functionalities. So this is Spring
Security: an application-level security framework built on top of the powerful Spring
Framework that deals mainly with the core security concepts of authentication and
authorization, which are some of the fundamental functionalities of Spring Security v5.
Spring Security aims to be a full-featured security solution for your Java applications.
Although its main focus is on web applications and the Java programming language, you
will see that it goes beyond these two domains.
What we wanted to do in writing this book was to expose some of the internal works
of Spring Security along with the standard explanations of how to use certain features.
The idea is to teach beyond the basics of how to do something in particular, and instead
focus on the plumbing inside the framework. We find that this is the best way of learning
something: actually seeing how it is built in the core. That’s not to say, of course, that the
book doesn’t cover basic setups and give quick, practical advice on using the framework,
because it certainly does. The point is that instead of saying, “Use this to do that,” we say,
“This works like this… and this allows you to….” This is a point of view that only tools like
Spring afford (because they are open source).
With that said, we suggest that the best way to use this book is to have the Spring
Security source code checked out on your computer and go through the examples with
both the code from the book and the code from Spring Security itself. This will not only
help you understand each concept as it is introduced, but will also teach more than

xv
Introduction

one good programming trick and good practice. We recommend this approach for
studying any software whenever you have the chance. If the source code is out there,
grab it. Sometimes a couple lines of code teach more than a thousand words. In this
book, we will mainly introduce Spring Boot, analyze Spring Framework, and develop
Java Web Applications with Spring Security v5.1.5, Java v11, and Servlet v4. Also, Spring
Security v5 supports many different authentication mechanisms which are introduced
and developed in this book, like Database (MongoDB and hsqldb), LDAP, X.509, OAuth
2/OpenID, WebSockets, SON Web Token (JWT), JAAS, and CAS. Web development
frameworks like Grails and JRuby in the context of Rails and Scala are also introduced in
this book.

Who This Book Is For


This book is written mainly for Java developers who use Spring in their work and need
to add security to their applications in a way that leverages Spring’s proven concepts
and techniques. The book will also be helpful to developers who want to add web-layer
security to their applications, even if those applications are not fully Spring-powered
at their core. The book assumes you have knowledge of Java and some of its tools and
libraries, such as Servlets and Maven. It also assumes that you know what you want to
use security for and in what context you want to use it. This means, for example, we
won’t explain protocols like LDAP in much depth; instead, we’ll concentrate on showing
you how to integrate Spring Security with an LDAP user store. An in-depth knowledge of
Spring is not essential because many of the concepts are introduced as we go along, but
the more you understand about Spring, the more you are likely to get out of this book.

How This Book Is Structured


The book is divided into nine chapters that embody a progressive study of Spring
Security. Starting from a summary of basic applications and an explanation of how
the framework is structured, the content moves on to more advanced topics, such as
using Spring Security in different JVM languages. The book follows a sequence that
corresponds to the way this framework is normally used in real life.

xvi
Introduction

The chapters in the book cover the following:

• Chapter 1: Introduces security in general and how to approach


security problems at the application level

• Chapter 2: Introduces Spring Security v5, how to use it, when to use
it, and all of its security functionalities

• Chapter 3: Introduces Spring Security with a simple example


application that secures web access at the URL level

• Chapter 4: Provides a full introduction to the architecture of Spring


Security, including the main components and how they interact with
each other

• Chapter 5: Gives in-depth coverage of the web-layer security options


available in Spring Security

• Chapter 6: Covers a wide array of authentication providers, including


LDAP and JASS, which can be plugged into Spring Security

• Chapter 7: Covers access control lists (ACLs), which are used to


secure individual domain objects, and how they fit into the general
security concerns

• Chapter 8: Explains how to extend the core Spring Security


functionality by making use of the many extension points supported
by its modular architecture

• Chapter 9: Shows how to integrate Spring Security with different Java


frameworks and some important JVM programming languages

P
 rerequisites
The examples in this book are all built with Java 11 and Maven 3.6.1. The latest Spring
versions are used if possible. Spring Security 5.1.5 was the version used throughout the
book. Tomcat Web Server v9 was used for the different web applications in the book,
mainly through its Maven plugin, and the laptop used was a ThinkPad Yoga 360 with
8GB of RAM. All the projects were developed using the IntelliJ IDEA Ultimate 2019.2.
You are free to use your own tools and operating system. Because everything is Java
based, you should be able to compile your programs on any platform without problems.
xvii
Introduction

D
 ownloading the Code
The code for the examples shown in this book is available via the Download Source Code
button located at www.apress.com/9781484250518.

C
 ontacting the Authors
You are more than welcome to send us any feedback regarding this book or any other
subject we might help you with. You can contact Carlo Scarioni via his blog at http://
cscarioni.blogspot.com, or you can send him email at carlo.scarioni@gmail.com.
You can contact Massimo Nardone via email at massimonardonedevchannel@gmail.com.

xviii
CHAPTER 1

The Scope of Security


Security. An incredibly overloaded word in the IT world. It means so many different
things in so many different contexts, but in the end, it is all about protecting sensitive
and valuable resources against malicious usage.
In IT, we have many layers of infrastructure and code that can be subject to malicious
attacks, and arguably we should ensure that all these layers get the appropriate levels of
protection.
Of course, the growth of the Internet and the pursuit of reaching more people with
our applications have opened more and more doors to cyber criminals trying to access
these applications in illegitimate ways.
It is also true that good care is not always taken to ensure that a properly secured
set of services is being offered to the public. And sometimes, even when good care
is taken, some hackers are still smart enough to overcome security barriers that,
superficially, appear adequate.
The first step is to define defense in depth (DiD) and its security layers. In general,
DiD is a way to define how to develop the cybersecurity of the IT infrastructure by
defining how all the defensive mechanisms are layered in order to protect and secure
data and information. A failing DiD or too weak development might be a consequence of
a cybersecurity attack on the IT infrastructure.
Let’s understand a bit more about the mechanisms part of DiD. First of all, DiD is
made of three major controls:

• Administrative controls: Policies, procedures, guidelines, awareness


programs, etc.

• Technical controls: Firewalls, antivirus, intrusion prevention


systems (IPS), etc.
• Physical Controls: Network and server rooms, video surveillance, etc.

1
© Carlo Scarioni and Massimo Nardone 2019
C. Scarioni and M. Nardone, Pro Spring Security, https://doi.org/10.1007/978-1-4842-5052-5_1
Chapter 1 The Scope of Security

Figure 1-1 shows the typical DiD mechanisms that define the IT infrastructure
security layers.

Figure 1-1. DiD mechanisms and IT infrastruxture layers

The three major security layers in an IT infrastructure are the network, the operating
system (part of the endpoint security layer), and the application itself.

The Network Security Layer


The network security layer is probably the most familiar one in the IT world. When
people talk about IT security, they normally think of network-level security—in
particular, security that uses firewalls.
Even though people often associate security with the network level, this is only a
very limited layer of protection against attackers. Generally speaking, it can do no more
than defend IP addresses and filter network packets addressed to certain ports in certain
machines in the network.

2
Chapter 1 The Scope of Security

This is clearly not enough in the vast majority of cases, as traffic at this level is
normally allowed to enter the publicly open ports of your various exposed services with
no restriction at all. Different attacks can be targeted at these open services, as attackers
can execute arbitrary commands that could compromise your security constraints.
There are tools like the popular nmap (http://nmap.org/) that can be used to scan a
machine to find open ports. The use of such tools is an easy first step to take in preparing
an attack, because well-known attacks can be used against such open ports if they are
not properly secured.
A very important part of the network-layer security, in the case of web applications,
is the use of Secure Sockets Layer (SSL) to encode all sensitive information sent along
the wire, but this is related more to the network protocol at the application level than to
the network physical level at which firewalls operate.

The Operating System Layer


The operating system layer is probably the most important one in the whole security
schema, as a properly secured operating system (OS) environment can at least prevent a
whole host machine from going down if a particular application is compromised.
If an attacker is somehow allowed to have unsecured access to the operating system,
they can basically do whatever they want—from spreading viruses to stealing passwords
or deleting your whole server’s data and making it unusable. Even worse perhaps, they
could take control of your computer without you even noticing, and use it to perform
other malicious acts as part of a botnet. This layer can include the deployment model of
the applications since you need to know your operating system’s permission scheme to
ensure that you don’t give your applications unnecessary privileges over your machine.
Applications should run as isolated as possible from the other components of the host
machine.

The Application Layer


The main focus of this book will be on the application layer. The application security
layer refers to all the constraints we establish in our applications to make sure that only
the right people can do only the right things when working through the application.

3
Chapter 1 The Scope of Security

Applications, by default, are open to countless avenues of attack. An improperly


secured application can allow an attacker to steal information from the application,
impersonate other users, execute restricted operations, corrupt data, gain access to the
operating system level, and perform many other malicious acts.
In this book, we will cover application-level security, which is the domain of Spring
Security. Application-level security is achieved by implementing several techniques,
and there are a few concepts that will help you understand better what the rest of the
book will cover. They are the main concerns that Spring Security addresses to provide
your applications with comprehensive protection against threats. In the following three
subsections, we shall introduce

• Authentication

• Authorization

• ACLs

A
 uthentication
The process of authentication allows an application to validate that a particular user is
who they claim they are. In the authentication process, a user presents the application
with information about herself (normally, a username and a password) that no one else
knows. The application takes this information and tries to match it against information
it has stored—normally, in a database or LDAP1 (Lightweight Directory Access Protocol)
server. If the information provided by the user matches a record in the authentication
server, the user is successfully authenticated in the system. The application will normally
create an internal abstraction representing this authenticated user in the system.
Figure 1-2 shows the authentication mechanism.

1
 DAP will be explained in some detail in Chapter 8, where various authentication providers are
L
covered.

4
Chapter 1 The Scope of Security

Figure 1-2. Simple, standard authentication mechanism

Authorization
When a user is authenticated, that only means that the user is known to the system
and has been recognized by it. It doesn’t mean that the user is free to do whatever she
wants in said system. The next logical step in securing an application is to determine
which actions the user is allowed to perform, and which resources she has access to,
and make sure that if the user doesn’t have the proper permissions she cannot carry
out that particular action. This is the work of the authorization process. In the most
common case, the authorization process compares the user’s set of permissions against
the permissions required to execute a particular action in the application, and if a match
is found, access is granted. On the other hand, if no match is found, access is denied.
Figure 1-3 shows the authorization mechanism.

5
Chapter 1 The Scope of Security

Figure 1-3. Simple authorization process. The authenticated user tries to access a
secured resource

ACLs
Access control lists (ACLs) are part of the authorization process explained in the
previous section. The key difference is that ACLs normally work at a finer grained level
in the application. ACLs are simply a collection of mappings between resources, users,
and permissions. With ACLs, you can establish rules like “User John has administrative
permission on the blog post X” or “User Luis has read permission on blog post X.” You
can see the three elements: user, permission, and resource. Figure 1-3 shows how ACLs
work; they are just a special case of the general authorization process.

Authentication and Authorization: General Concepts


In this section, we shall introduce and explain some fundamental security concepts that
you will be coming across frequently in the rest of the book:

• User: The first step in securing a system from malicious attackers


is to identify legitimate users and allow access to them alone. User
abstractions are created in the system and given their own identity.
They are the users that will later be allowed to use the system.

6
Chapter 1 The Scope of Security

• Credentials: Credentials are the way a user proves who they are.
Normally, in the shape of passwords (certificates are also a common
way of presenting credentials), they are data that only the owner of it
knows.

• Role: In an application security context, a role can be seen as a logical


grouping of users. This logical grouping is normally done so the
grouped users share a set of permissions in the application to access
certain resources. For example, all users with the role of admin will
have the same access and permissions to the same resources. Roles
serve simply as a way to group permissions to execute determined
actions, making users with those roles inherit such permissions.

• Resource: By a resource, we mean, in this context, any part of the


application that we want to access and that needs to be properly
secured against unauthorized access—for example, a URL, a business
method, or a particular business object.

• Permissions: Permissions refer to the access level needed to access


a particular resource. For example, two users may be allowed to read
a particular document, but only one of them is allowed to write to it.
Permissions can apply either to individual users or to users that share
a particular role.

• Encryption: This allows you to encrypt sensible information


(normally passwords, but it can be something else, like cookies) so
as to make it incomprehensible to attackers even if they get access to
the encrypted version. The idea is that you never store the plain text
version of a password, but instead store an encrypted version so that
nobody but the owner of such a password knows the original one.
There are three main kinds of encryption algorithms:

• One-way encryption: These algorithms, referred as hashing


algorithms, take an input string and generate an output number
known as the message digest. This output number cannot be
converted back into the original string. This is why the technique
is referred to as one-way encryption. Here is the way to use it:
A requesting client encrypts a string and sends the encrypted
string to the server. The server may have access to the original
7
Chapter 1 The Scope of Security

information from a previous registration process, for example,


and if it does, it can apply the same hash function to it. Then
it compares the output from this hashing to the value sent by
the client. If they match, the server validates the information.
Figure 1-4 shows this scheme. Usually, the server doesn’t even
need the original data. It can simply store the hashed version and
then compare it with the incoming hash from the client.

Figure 1-4. One-way encryption or hashing

• Symmetric encryption: These algorithms provide two functions:


encrypt and decrypt. A string of text is converted into an encrypted
form and then can be converted back to the original string. In this
scheme, a sender and a receiver share the same keys so that they can
encrypt and decrypt messages on both ends of the communication.

8
Chapter 1 The Scope of Security

One problem with this scheme is how to share the key between the
endpoints of the communication. A common approach is to use a
parallel secure channel to send the keys. Figure 1-5 shows symmetric
encryption at work.

Figure 1-5. Symmetric encryption. The two endpoints share the same encryption/
decryption key

• Public key cryptography: These techniques are based on


asymmetric cryptography. In this scheme, a different key is used
for encryption than for decryption. These two keys are referred as
the public key, which is used to encrypt messages, and the private
key, which is used to decrypt messages. The advantage of this
approach over symmetric encryption is that there is no need to
share the decryption key, so no one but the intended receiver of the
information is able to decrypt the message. So the normal scenario is
the following:

• The intended recipient of messages shares her public key with


everyone interested in sending information to her.

• A sender encrypts the information with the receiver’s public key,


and sends a message.

• The receiver uses her private key to decrypt the message.

• No one else is able to decrypt the message because they don’t


have the receiver’s private key.
9
Chapter 1 The Scope of Security

Figure 1-6 shows the public key cryptography scheme.

Figure 1-6. Public key cryptography

The use of encryption achieves, among other things, two other security goals:

• Confidentiality: Potentially sensitive information belonging to one


user, or group of users, should be accessible only to this user or
group. Encryption algorithms are the main helper in achieving
this goal.

• Integrity: Data sent by a valid user shouldn’t be altered by a third


entity on its way to the server, or in its storage. This is normally
accomplished through the use of one-way cryptographic algorithms
that make it almost impossible to alter an input and produce a
corrupted message whose encrypted hash is the same as the original
message (thus deceiving the receiver into thinking it is valid).

What to Secure
Not every part of the application requires a strong security model, or even any security
at all. If, for example, one part of your application is supposed to serve static content
to everyone interested in it, you can simply serve this content. There probably are no
security concerns to handle here.

10
Chapter 1 The Scope of Security

Anyway, when starting to work on a new application, you should think about the
security constraints that your application will have. You should think about concerns like
those in the following list and whether or not they apply to your particular use case:

• Identity management: More than likely, your application will need


to establish the identities of the different users that will be using it.
Usually, your application will do different things for different users,
so you need a way to associate users with certain functionality. You
also need to be sure to protect each user’s identity information so
that it can’t be compromised.

• Secured connections: In an internet environment, where anyone in


the world can potentially access your system and eavesdrop on other
users accessing your system, you most likely will want to secure the
communication of sensitive data using some kind of transport layer
security, such as SSL.

• Sensitive data protection: Sensitive data will need to be protected


against malicious attacks. This applies to the communication layer
and to individual message transmission, as well as to credentials
datastores. Encryption should be used in different layers to achieve
the most secure application possible.

More Security Concerns


There are many more security concerns than the ones explained so far. Because this is
a Spring Security book and not a general application-security book, we will cover only
things related to Spring Security. However, we think it is important that you understand
that there are many more security concerns than those addressed directly by Spring
Security. The following is a quick overview of some of the most common ones. This is
only intended to make you aware of their existence, and we recommend you consult
a different source (such as a general software security textbook) to gain a better
understanding of all these concerns.

11
Chapter 1 The Scope of Security

• SQL (and other code) injection: Validating user input is a very


important part of application security. If data is not validated, an
attacker could potentially write any kind of string as input (including
SQL or server-side code) and send that information to the server. If the
server code is not properly written, the attacker could wreak significant
havoc because she could execute any arbitrary code on the server.

• Denial of service attacks: These attacks consist of making the target


system unresponsive to its intended users. This is normally done by
saturating the server with requests so that it utilizes all the server’s
resources and makes it unresponsive to legitimate requests.

• Cross-site scripting and output sanitation: A kind of injection can


be done where the target is the client part of the application. The
idea is that the attacker can make an application return malicious
code inside the web pages returned, and thus execute it in the user’s
browser. This way, the attacker invisibly executes actions using the
real user’s authenticated session.

Java Options for Security


Java and Java EE out-of-the-box security solutions are very comprehensive. They cover
areas ranging from a low-level permission system, through cryptography APIs, to an
authentication and authorization scheme.
The list of security APIs offered in Java is very extensive, as the following list of the
main ones shows:

• Java Cryptography Architecture (JCA): This API offers support


for cryptographic algorithms, including hash-digest and digital-­
signature support.

• Java Cryptographic Extensions (JCE): This API mainly provides


facilities for the encryption and decryption of strings and also secret
key generation for symmetric algorithms.
• Java Certification Path API (CertPath): This API provides
comprehensive functionality for integrating the validation and
verification of digital certificates into an application.

12
Other documents randomly have
different content
These fallacies, lodged in certain minds, generated, long ago, grand,
ambitious, and bold schemes of conquest and wealth. The people of
the North stood in the way of these schemes. In the minds of the
schemers, labour had been associated with servility, meekness,
cowardice; and they were persuaded that all men not degraded by
labour at the North “kept aloof from politics,” or held their judgment in
entire subjection to the daily wants of a working population, of no
more spirit and no more patriotism than their own working men—
slaves. They believed this whole people to be really in a state of
dependence, and that they controlled that upon which they
depended. So, to a hitherto vague and inert local partisanship, they
brought a purpose of determination to overcome the North, and, as
this could not be safely avowed, there was the necessity for a
conspiracy, and for the cloak of a conspiracy. By means the most
mendacious, the ignorant, proud, jealous, and violent free population
of the cotton States and their dependencies, were persuaded that
less consideration was paid to their political demands than the
importance of their contentment entitled them to expect from their
government, and were at length decoyed into a state of angry
passion, in which they only needed leaders of sufficient audacity to
bring them into open rebellion. Assured that their own power if used
would be supreme, and that they had but to offer sufficient evidence
of a violent and dangerous determination to overawe the sordid
North, and make it submit to a “reconstruction” of the nation in a form
more advantageous to themselves, they were artfully led along in a
constant advance, and constant failure of attempts at intimidation,
until at length they must needs take part in a desperate rebellion, or
accept a position which, after the declarations they had made for the
purpose of intimidation, they could not do without humiliation.
The conspirators themselves have, until recently, been able, either
directly or by impositions upon patriotic, but too confiding and
generous instruments, to control the treasury of the United States, its
post-office, its army and navy, its arsenals, workshops, dockyards
and fortresses, and, by the simple means of perjury, to either turn
these agencies against the government, or at least render them
ineffectual to aid it, and this at a time, when its very existence, if it
were anything but a democratic republican government, and, as we
think for all good purposes, by far the strongest that ever existed,
would have depended on a perfect instant and unquestionable
command of them. Yet I doubt not that the conspirators themselves,
trust at this moment, as they ever have trusted, even less to the
supposed helpless condition of the government than to the supposed
advantages of the cotton monopoly to the Slave States, and to the
supposed superiority of a community of privileged classes over an
actual democracy.

“No! you dare not make war upon cotton; no power on earth dares to
make war upon it. Cotton is king; until lately the Bank of England
was king; but she tried to put her screws, as usual, the fall before the
last, on the cotton crop, and was utterly vanquished. The last power
has been conquered: who can doubt, that has looked at recent
events, that cotton is supreme?”

These are the defiant and triumphant words of Governor Hammond,


of South Carolina, addressed to the Senate of the United States,
March 4th, 1858. Almost every important man of the South, has at
one time or other, within a few years, been betrayed into the
utterance of similar exultant anticipations; and the South would never
have been led into the great and terrible mistake it has made, had it
not been for this confident conviction in the minds of the men who
have been passing for its statesmen. Whatever moral strength the
rebellion has, abroad or at home, lies chiefly in the fact that this
conviction is also held, more or less distinctly, by multitudes who
know perfectly well that the commonly assigned reasons for it are
based on falsehoods.
Recently, a banker, who is and always has been a loyal union man,
said, commenting upon certain experiences of mine narrated in this
book: “The South cannot be poor. Why their last crop alone was
worth two hundred million. They must be rich:” ergo, say the
conspirators, adopting the same careless conclusion, they must be
powerful, and the world must feel their power, and respect them and
their institutions.
My own observation of the real condition of the people of our Slave
States, gave me, on the contrary, an impression that the cotton
monopoly in some way did them more harm than good; and,
although the written narration of what I saw was not intended to set
this forth, upon reviewing it for the present publication, I find the
impression has become a conviction. I propose here, therefore, to
show how the main body of the observations of the book arrange
themselves in my mind with reference to this question, and also to
inquire how far the conclusion to which I think they tend is
substantiated by the Census returns of those States.[1]
Coming directly from my farm in New York to Eastern Virginia, I was
satisfied, after a few weeks’ observation, that the most of the people
lived very poorly; that the proportion of men improving their condition
was much less than in any Northern community; and that the natural
resources of the land were strangely unused, or were used with poor
economy. It was “the hiring season,” and I had daily opportunities of
talking with farmers, manufacturers, miners, and labourers, with
whom the value of labour and of wages was then the handiest
subject of conversation. I soon perceived that labour was much more
readily classified and measured with reference to its quality than at
the North. The limit of measure I found to be the ordinary day’s work
of a “prime field-hand,” and a prime field-hand, I found universally
understood to mean, not a man who would split two cords of wood,
or cradle two acres of grain in a day, but a man for whom a “trader”
would give a thousand dollars, or more, to take on South, for sale to
a cotton planter. I do not mean that the alternative of a sale to a
trader was always had in view in determining how a man should be
employed. To be just, this seldom appeared to be the case—but that,
in estimating the market value of his labour, he was viewed, for the
time, from the trader’s point of view, or, as if the question were—
What is he worth for cotton?
I soon ascertained that a much larger number of hands, at much
larger aggregate wages, was commonly reckoned to be required to
accomplish certain results, than would have been the case at the
North. Not all results, but certain results, of a kind in which it
happened that I could most readily make a confident comparison. I
have been in the habit of watching men at work, and of judging of
their industry, their skill, their spirit; in short, of whatever goes to
make up their value to their employers, or to the community, as
instruments of production; and from day to day I saw that, as a
landowner, or as a citizen, in a community largely composed, or
dependent upon the productive industry, of working people of such
habits and disposition as I constantly saw evinced in those of
Virginia, I should feel disheartened, and myself lose courage, spirit,
and industry. The close proximity of the better and cheaper labour—
labour seeking a field of labour—which I had left behind me, added
greatly to my interest in the subject, and stimulated close inquiry. It
seemed, indeed, quite incredible that there really could be such a
want of better labour in this region as at first sight there appeared to
be, when a supply was so near at hand. I compared notes with every
Northern man I met who had been living for some time in Virginia,
and some I found able to give me quite exact statements of personal
experience, with which, in the cases they mentioned, it could not be
doubted that labourers costing, all things considered, the same
wages, had taken four times as long to accomplish certain tasks of
rude work in Virginia as at the North, and that in house service, four
servants accomplished less, while they required vastly more looking
after, than one at the North.
I left Virginia, having remained much longer than I at first intended, in
trying to satisfy myself about this matter—quite satisfied as to the
general fact, not at all satisfied with any theories of demand and
supply which had been offered me, or which had occurred to me, in
the way of explanation of it.
My perplexity was increased by certain apparent exceptions to the
general rule; but they were, all things considered, unimportant, and
rather served as affording contrasts, on the ground, to satisfy me of
the correctness of my general conclusion.
I subsequently returned, and spent another month in Virginia, after
visiting the cotton States, and I also spent three months in Kentucky
and other parts of the Slave States where the climate is unsuitable
for the production of cotton, and with the information which I had in
the meantime obtained, I continued to study both the question of
fact, and the question of cause. The following conclusions to which
my mind tended strongly in the first month, though I did not then
adopt them altogether with confidence, were established at length in
my convictions.
1. The cash value of a slave’s labour in Virginia is,
practically, the cash value of the same labour minus the
cost of its transportation, acclimatizing, and breaking in to
cotton-culture in Mississippi.
2. The cost of production, or the development of natural
wealth in Virginia, is regulated by the cost of slave-labour:
(that is to say) the competition of white labour does not
materially reduce it; though it doubtless has some effect,
at least in certain districts, and with reference to certain
productions or branches of industry.
3. Taking infants, aged, invalid, and vicious and knavish
slaves into account, the ordinary and average cost of a
certain task of labour is more than double in Virginia what
it is in the Free States adjoining.
4. The use of land and nearly all other resources of wealth
in Virginia is much less valuable than the use of similar
property in the adjoining Free States, these resources
having no real value until labour is applied to them. (The
Census returns of 1850 show that the sale value of farm
lands by the acre in Virginia is less than one-third the
value of farm lands in the adjoining Free State of
Pennsylvania, and less than one-fifth than that of the farm
lands of the neighbouring Free State of New Jersey.)[2]
5. Beyond the bare necessities of existence, poor shelter,
poor clothing, and the crudest diet, the mass of the citizen
class of Virginia earn very little and are very poor—
immeasurably poorer than the mass of the people of the
adjoining Free States.
6. So far as this poverty is to be attributed to personal
constitution, character, and choice, it is not the result of
climate.
7. What is true of Virginia is measurably true of all the
border Slave States, though in special cases the
resistance of slavery to a competition of free labour is
more easily overcome. In proportion as this is the case,
the cost of production is less, the value of production
greater, the comfort of the people is greater; they are
advancing in wealth as they are in intelligence, which is
the best form or result of wealth.
I went on my way into the so-called cotton States, within which I
travelled over, first and last, at least three thousand miles of roads,
from which not a cotton plant was to be seen, and the people living
by the side of which certainly had not been made rich by cotton or
anything else. And for every mile of road-side upon which I saw any
evidence of cotton production, I am sure that I saw a hundred of
forest or waste land, with only now and then an acre or two of poor
corn half smothered in weeds; for every rich man’s house, I am sure
that I passed a dozen shabby and half-furnished cottages, and at
least a hundred cabins—mere hovels, such as none but a poor
farmer would house his cattle in at the North. And I think that, for
every man of refinement and education with whom I came in contact,
there were a score or two superior only in the virtue of silence, and in
the manner of self-complacency, to the sort of people we should
expect to find paying a large price for a place from which a sight
could be got at a gallows on an execution day at the North, and a
much larger number of what poor men at the North would
themselves describe as poor men: not that they were destitute of
certain things which are cheap at the South,—fuel for instance,—but
that they were almost wholly destitute of things the possession of
which, at the North, would indicate that a man had begun to
accumulate capital—more destitute of these, on an average, than
our day-labourers. In short, except in certain limited districts, mere
streaks by the side of rivers, and in a few isolated spots of especially
favoured soil away from these, I found the same state of things
which I had seen in Virginia, but in a more aggravated form.
At least five hundred white men told me something of their own lives
and fortunes, across their own tables, and with the means of
measuring the weight of their words before my eyes; and I know that
white men seldom want an abundance of coarse food in the cotton
States: the proportion of the free white men who live as well in any
respect as our working classes at the North, on an average, is small,
and the citizens of the cotton States, as a whole, are poor. They
work little, and that little, badly; they earn little, they sell little; they
buy little, and they have little—very little—of the common comforts
and consolations of civilized life. Their destitution is not material only;
it is intellectual and it is moral. I know not what virtues they have that
rude men everywhere have not; but those which are commonly
attributed to them, I am sure that they lack: they are not generous or
hospitable; and, to be plain, I must say that their talk is not the talk of
even courageous men elsewhere. They boast and lack self-restraint,
yet, when not excited, are habitually reserved and guarded in
expressions of opinion very much like cowardly men elsewhere.
But, much cotton is produced in the cotton States, and by the labour
of somebody; much cotton is sold and somebody must be paid for it;
there are rich people; there are good markets; there is hospitality,
refinement, virtue, courage, and urbanity at the South. All this is
proverbially true. Who produces the cotton? who is paid for it? where
are, and who are, the rich and gentle people?
I can answer in part at least.
I have been on plantations on the Mississippi, the Red River, and the
Brazos bottoms, whereon I was assured that ten bales of cotton to
each average prime field-hand had been raised. The soil was a
perfect garden mould, well drained and guarded by levees against
the floods; it was admirably tilled; I have seen but few Northern
farms so well tilled: the labourers were, to a large degree, tall,
slender, sinewy, young men, who worked from dawn to dusk, not
with spirit, but with steadiness and constancy. They had good tools;
their rations of bacon and corn were brought to them in the field, and
eaten with efficient despatch between the cotton plants. They had
the best sort of gins and presses, so situated that from them cotton
bales could be rolled in five minutes to steamboats, bound direct to
the ports on the gulf. They were superintended by skilful and vigilant
overseers. These plantations were all large, so large as to yet
contain much fresh land, ready to be worked as soon as the
cultivated fields gave out in fertility. If it was true that ten bales of
cotton to the hand had been raised on them, then their net profit for
the year had been, not less than two hundred and fifty dollars for
each hand employed. Even at seven bales to the hand the profits of
cotton planting are enormous. Men who have plantations producing
at this rate, can well afford to buy fresh hands at fourteen hundred
dollars a head. They can even afford to employ such hands for a
year or two in clearing land, ditching, leveeing, fencing, and other
preparatory work, buying, meantime, all the corn and bacon they
need, and getting the best kind of tools and cattle, and paying fifteen
per cent. per annum interest on all the capital required for this, as
many of them do. All this can be well afforded to establish new
plantations favourably situated, on fresh soil, if there is a reasonable
probability that they can after all be made to produce half a dozen
seven-bale crops. And a great many large plantations do produce
seven bales to the hand for years in succession. A great many more
produce seven bales occasionally. A few produce even ten bales
occasionally, though by no means as often as is reported.
Now, it is not at a Roman lottery alone that one may see it, but all
over the world, where a few very large prizes are promised and
many very small ones, and the number of tickets is limited; these are
always speculated on, and men will buy them at third and fourth
hand at prices which, it is useless to demonstrate to them, must be
extravagant. They go to the Jews and pledge the clothes on their
back to get another biacchi to invest; they beggar themselves; they
ruin their families; they risk damnation in their passionate eagerness
to have a chance, when they know perfectly well that the average of
chances is not worth a tithe of what they must pay for it.
The area of land on which cotton may be raised with profit is
practically limitless; it is cheap; even the best land is cheap; but to
the large planter it is much more valuable when held in large parcels,
for obvious reasons, than when in small; consequently the best land
can hardly be obtained in small tracts or without the use of a
considerable capital. But there are millions of acres of land yet
untouched, which if leveed and drained and fenced, and well
cultivated, might be made to produce with good luck seven or more
bales to the hand. It would cost comparatively little to accomplish it—
one lucky crop would repay all the outlay for land and improvements
—if it were not for “the hands.” The supply of hands is limited. It does
not increase in the ratio of the increase of the cotton demand. If
cotton should double in price next year, or become worth its weight
in gold, the number of negroes in the United States would not
increase four per cent. unless the African slave-trade were re-
established. Now step into a dealer’s “jail” in Memphis, Montgomery,
Vicksburg, or New Orleans, and you will bear the Mezzano of the
cotton lottery crying his tickets in this way: “There’s a cotton nigger
for you! Genuine! Look at his toes! Look at his fingers! There’s a pair
of legs for you! If you have got the right sile and the right sort of
overseer, buy him, and put your trust in Providence! He’s just as
good for ten bales as I am for a julep at eleven o’clock.” And this is
just as true as that any named horse is sure to win the Derby. And so
the price of good labourers is constantly gambled up to a point,
where, if they produce ten bales to the hand, the purchaser will be as
fortunate as he who draws the high prize of the lottery; where, if they
produce seven bales to the hand, he will still be in luck; where, if rot,
or worm, or floods, or untimely rains or frosts occur, reducing the
crop to one or two bales to the hand, as is often the case, the
purchaser will have drawn a blank.
That, all things considered, the value of the labour of slaves does
not, on an average, by any means justify the price paid for it, is
constantly asserted by the planters, and it is true. At least beyond
question it is true, and I think that I have shown why, that there is no
difficulty in finding purchasers for all the good slaves that can be got
by traders, at prices considerably more than they are worth for the
production of cotton under ordinary circumstances. The supply being
limited, those who grow cotton on the most productive soils, and with
the greatest advantages in all other respects, not only can afford to
pay more than others, for all the slaves which can be brought into
market, but they are driven to a ruinous competition among
themselves, and slaves thus get a fictitious value like stocks “in a
corner.” The buyers indeed are often “cornered,” and it is only the
rise which almost annually has occurred in the value of cotton that
has hitherto saved them from general bankruptcy. Nearly all the
large planters carry a heavy load of debt from year to year, till a lucky
crop coincident with a rise in the price of cotton relieves them.
The whole number of slaves engaged in cotton culture at the Census
of 1850 was reckoned by De Bow to be 1,800,000,[3] the crops at
2,400,000 bales, which is a bale and a third to each head of slaves.
This was the largest crop between 1846 and 1852. Other things
being equal, for reasons already indicated, the smaller the estate of
slaves, the less is their rate of production per head; and, as a rule,
the larger the slave estate the larger is the production per head. The
number of slaves in cotton plantations held by owners of fifty and
upwards is, as nearly as it can be fixed by the Census returns,
420,000.
If these produce on an average only two and a half bales per head
(man, woman, and child), and double this is not extraordinary on the
large plantations of the South-west,[4] it leaves an average for the
smaller plantations of seven-eighths of a bale per head. These
plantations are mostly in the interior, with long haulage and boatage
to market. To the small planter in the interior, his cotton crop does
not realize, as an average plantation price, more than seven cents a
pound, or thirty dollars the bale.[5] Those who plant cotton in this
small way usually raise a crop of corn, and some little else, not
enough, take the country through, one year with another, to supply
themselves and their slaves with food; certainly not more than
enough to do so, on an average. To this the Southern agricultural
periodicals frequently testify. They generally raise nothing for sale,
but cotton. And of cotton their sale, as has been shown, amounted in
1849—a favourable year—to less than the value of twenty-five
dollars for each slave, young and old, which they had kept through
the year.[6] Deducting those who hold slaves only as domestic
servants from the whole number of slaveholders returned by the
Census, more than half of all the slaveholders, and fully half of all the
cotton-sellers, own each, not more than one family, on an average,
of five slaves of all ages.[7] The ordinary total cash income, then, in
time of peace, of fully half our cotton-planters, cannot be reckoned at
more than one hundred and twenty-five dollars, or, in extraordinary
years, like the last, at, say, one hundred and fifty dollars. From this
they must purchase whatever clothing and other necessaries they
require for the yearly supply of an average of more than ten persons
(five whites and five slaves), as well as obtain tools, mechanics’ work
and materials, and whatever is necessary for carrying on the work of
a plantation, usually of some hundred acres,[8] and must yet save
enough to pay the fees of doctors, clergy, and lawyers, if they have
had occasion to employ them, and their county and state taxes (we
will say nothing of the education of their children, or of accumulations
for the war expenses of the Confederation). My personal experience
of the style of living of the greater number of cotton-planters leads
me to think this not an unfair estimate. It is mainly based upon the
official returns and calculations of the United States Census of 1850,
as prepared by Mr. De Bow, a leading secessionist, and it assumes
nothing which is not conceded in the article on cotton in his
Resources of the South. A majority of those who sell the cotton crop
of the United States must be miserably poor—poorer than the
majority of our day-labourers at the North.
A similar calculation will indicate that the planters who own on an
average two slave families each, can sell scarcely more than three
hundred dollars’ worth of cotton a year, on an average; which also
entirely agrees with my observations. I have seen many a workman’s
lodging at the North, and in England too, where there was double the
amount of luxury that I ever saw in a regular cotton-planter’s house
on plantations of three cabins.
The next class of which the Census furnishes us means of
considering separately, are planters whose slaves occupy, on an
average, seven cabins, lodging five each on an average, including
the house servants, aged invalids, and children. The average income
of planters of this class, I reckon from similar data, to be hardly more
than that of a private of the New York Metropolitan Police Force. It is
doubtless true that cotton is cultivated profitably, that is to say, so as
to produce a fair rate of interest on the capital of the planter, on
many plantations of this class; but this can hardly be the case on an
average, all things considered.
It is not so with many plantations of the next larger class even, but it
would appear to be so with these on an average; that is to say,
where the quarters of a cotton plantation number half a score of
cabins or more, which method of classification I use that travellers
may the more readily recall their observations of the appearance of
such plantations, when I think that their recollections will confirm
these calculations. There are usually other advantages for the
cultivation, cleaning, pressing, shipping, and disposing of cotton, by
the aid of which the owner obtains a fair return for the capital
invested, and may be supposed to live, if he knows how, in a
moderately comfortable way. The whole number of slaveholders of
this large class in all the Slave States is, according to De Bow’s
Compendium of the Census, 7,929, among which are all the great
sugar, rice, and tobacco-planters. Less than seven thousand,
certainly, are cotton-planters.
A large majority of these live, when they live on their plantations at
all, in districts, almost the only white population of which consists of
owners and overseers of the same class of plantations with their
own. The nearest other whites will be some sand-hill vagabonds,
generally miles away, between whom and these planters, intercourse
is neither intimate nor friendly.
It is hardly worth while to build much of a bridge for the occasional
use of two families, even if they are rich. It is less worth while to go
to much pains in making six miles of good road for the use of these
families. A school-house will hardly be built for the children of six rich
men who will all live on an average six miles away from it, while
private tutors or governesses can be paid by the earnings of a single
field-hand. If zeal and fluency can be obtained in a preacher coming
occasionally within reach, the interest on the cost of a tolerable
education is not likely to be often paid by all who would live within
half a day’s journey of a house of worship, which can be built
anywhere in the midst of a district of large plantations. It is not
necessary to multiply illustrations like these. In short, then, if all the
wealth produced in a certain district is concentrated in the hands of a
few men living remote from each other, it may possibly bring to the
district comfortable houses, good servants, fine wines, food and
furniture, tutors and governesses, horses and carriages, for these
few men, but it will not bring thither good roads and bridges, it will
not bring thither such means of education and of civilized comfort as
are to be drawn from libraries, churches, museums, gardens,
theatres, and assembly rooms; it will not bring thither local
newspapers, telegraphs, and so on. It will not bring thither that subtle
force and discipline which comes of the myriad relations with and
duties to a well-constituted community which every member of it is
daily exercising, and which is the natural unseen compensation and
complement of its more obvious constraints and inconveniences.
There is, in fact, a vast range of advantages which our civilization
has made so common to us that they are hardly thought of, of which
the people of the South are destitute. They chiefly come from or
connect with acts of co-operation, or exchanges of service; they are
therefore possessed only in communities, and in communities where
a large proportion of the people have profitable employment. They
grow, in fact, out of employments in which the people of the
community are associated, or which they constantly give to and
receive from one another, with profit. The slaves of the South,
though often living in communities upon plantations, fail to give or
receive these advantages because the profits of their labour are not
distributed to them; the whites, from not engaging in profitable
employment. The whites are not engaged in profitable employment,
because the want of the advantages of capital in the application of
their labour, independently of the already rich, renders the
prospective result of their labour so small that it is inoperative in
most, as a motive for exerting themselves further than is necessary
to procure the bare means of a rude subsistence; also because
common labour is so poorly rewarded in the case of the slaves as to
assume in their minds, as it must in the minds of the slaves
themselves, a hateful aspect.
In the late act of treason of the usurpers of government in Louisiana,
the commercial demand which induces a man to go to work is
considered to be equivalent to slavery; and the fear that the election
of Lincoln, by its tendency to open a way for the emancipation of the
negroes, may lead on to a necessity for the whites to go to work, is
gravely set forth as a justification for the surrender of the State to the
conspiracy. Thus:—
“Fully convinced as we are that slavery * * * * * leaves to the black
labourer a more considerable sum of comfort, happiness, and liberty
than the inexorable labour required from the free servants of the
whole universe, and that each emancipation of an African, without
being of any benefit to him, would necessarily condemn to slavery
one of our own race, etc.”
To work industriously and steadily, especially under directions from
another man, is, in the Southern tongue, to “work like a nigger;” and,
from childhood, the one thing in their condition which has made life
valuable to the mass of whites has been that the niggers are yet their
inferiors. It is this habit of considering themselves of a privileged
class, and of disdaining something which they think beneath them,
that is deemed to be the chief blessing of slavery. It is termed “high
tone,” “high spirit,” and is supposed to give great military advantages
to those who possess it. It should give advantages of some sort, for
its disadvantages are inexpressibly great.
But if the poor whites were ever so industriously disposed, the rich
planter has a natural distaste to exchange absolute for partial
authority over the instruments by which he achieves his purpose;
and the employment of free and slave labour together, is almost as
difficult as working, under the same yoke, an unbroken horse and a
docile ox. Again, however repugnant it may be to the self-esteem,
and contrary to the habits of the rich man to treat his labourers with
respect, he has to do it when employing white men, from motives of
self-interest which lie below the surface, and he consequently
habitually avoids arranging his affairs in such a way as will make it
necessary for him to offer them employment.
It may be said that on the more profitable cotton plantations, where
little is raised except cotton, supplies for the maintenance of the
slaves, and for carrying on the work of the plantation, are largely
bought, which are raised elsewhere at the South; and that those who
supply the commodities, thus required by the cotton-planter, draw
from his profits which are thus distributed throughout the South, even
to the non-cotton-producing States, the people of which are thus
enriched. As far as all articles are concerned, in the production of
which labour is a comparatively unimportant item of cost,—mules for
instance, and in certain circumstances, within certain limits, swine,—
this is true. But these are of small consequence. It is constantly
assumed by nearly all writers on this subject, that the labour directed
to the cultivation of Indian corn for the necessary sustenance of
slaves engaged in cotton culture, must be just as profitably directed
as if it were devoted to the cultivation of cotton itself. This is not true,
although the Southern agricultural journals, and to a large extent our
national agriculture reports, have for years been assuming it to be
so. It is frequently spoken of, indeed, as a mystery, that the cotton-
planters cannot be induced to raise the food required by their force.
The reason of it is a very simple one; namely, that in the cultivation
of corn their labour must come into competition with the free labour
of the Northern States, as it does not in the production of cotton: and
the corn-raisers of the Northern Slave States, without enjoying any
monopoly of production, like that of the cotton-raisers, have to share
with these, all the manifold inconveniences which result from the
scarcity of good workmen, and the necessary concentration of all the
effective working force of the country, limited as it is, upon the one
purpose of getting cotton.
The interests of the owners of all soil in the Slave States which is not
adapted to cotton culture, and of all capital not engaged in cotton
culture, or in supplying slaves for it, are thus injured by the demand
for cotton, they being, in fact, forced to be co-partners in an
association in which they do not share the profits.
And as to what are commonly called the Cotton States, if we assume
that cotton cultivation is profitable only where the production is equal
to two bales for each slave employed, it will be seen that wherever
the land will not yield as much as this, the owner of it suffers all the
disadvantages of the difficulty of getting good labourers as much as
the owner of the land which produces seven or ten bales to the
hand, although none of the profits of supplying the cotton demand,
which gives this extraordinary price to labour, come to him.
According to the Census,[9] the whole crop of cotton is produced on
5,000,000 acres. It could be produced, at the rate common on good
South-western plantations, on less than half that area. The rest of
the land of the Slave States, which amounts to over 500,000,000
acres, is condemned, so far as the tendencies I have indicated are
not overweighed here and there by some special advantages, to
non-cultivation, except for the hand-to-mouth supply of its people.
And this is true not only of its agricultural but of all other of its
resources.
That for all practical purposes this is not an exaggerated statement is
clearly enough shown by the difference in the market value of land,
which as officially given by De Bow, is, notwithstanding the
extraordinary demand of the world upon the cotton land, between
four and five hundred per cent. higher in the Free than in the Slave
States, the frontier and unsettled districts, Texas, California, and the
territories not being considered.
One of the grand errors, out of which this rebellion has grown, came
from supposing that whatever nourishes wealth and gives power to
an ordinary civilized community, must command as much for a slave-
holding community. The truth has been overlooked that the
accumulation of wealth and the power of a nation are contingent not
merely upon the primary value of the surplus of productions of which
it has to dispose, but very largely also upon the way in which the
income from its surplus is distributed and reinvested. Let a man be
absent from almost any part of the North twenty years, and he is
struck, on his return, by what we call the “improvements” which have
been made. Better buildings, churches, school-houses, mills,
railroads, etc. In New York city alone, for instance, at least two
hundred millions of dollars have been reinvested merely in an
improved housing of the people; in labour-saving machinery,
waterworks, gasworks, etc., as much more. It is not difficult to see
where the profits of our manufacturers and merchants are. Again, go
into the country, and there is no end of substantial proof of twenty
years of agricultural prosperity, not alone in roads, canals, bridges,
dwellings, barns and fences, but in books and furniture, and
gardens, and pictures, and in the better dress and evidently higher
education of the people. But where will the returning traveller see the
accumulated cotton profits of twenty years in Mississippi? Ask the
cotton-planter for them, and he will point in reply, not to dwellings,
libraries, churches, school-houses, mills, railroads, or anything of the
kind; he will point to his negroes—to almost nothing else. Negroes
such as stood for five hundred dollars once, now represent a
thousand dollars. We must look then in Virginia and those Northern
Slave States which have the monopoly of supplying negroes, for the
real wealth which the sale of cotton has brought to the South. But
where is the evidence of it? where anything to compare with the
evidence of accumulated profits to be seen in any Free State? If
certain portions of Virginia have been a little improving, others
unquestionably have been deteriorating, growing shabbier, more
comfortless, less convenient. The total increase in wealth of the
population during the last twenty years shows for almost nothing.
One year’s improvements of a Free State exceed it all.
It is obvious that to the community at large, even in Virginia, the
profits of supplying negroes to meet the wants occasioned by the
cotton demand, have not compensated for the bar which the high
cost of all sorts of human service, which the cotton demand has also
occasioned, has placed upon all other means of accumulating
wealth; and this disadvantage of the cotton monopoly is fully
experienced by the negro-breeders themselves, in respect to
everything else they have to produce or obtain.[10]
I say all sorts of human service. What the South will have to pay for
the service of true statesmanship, the world has now to see.
Whither the profits of cotton go, it is not my purpose, here, to
undertake to show. I will barely notice the hypocritical statement
made for the English market as an apology for this mad crime of the
slaveholders, that they are greatly absorbed in contributions made
by the planting States to our national treasury in payment of duties
on importations. The cotton-planters pay duties only on what they
consume of foreign goods. A very large part of all our duties are
collected on a class of goods for which there is almost no demand at
all from the South, either directly or indirectly—woollen and fur
goods, for instance: of the goods required for the South not a few
have been practically free. The whole slave population of the South
consumes almost nothing imported (nor would it, while slave, under
any circumstances). The majority of the white population habitually
makes use of no foreign production except chickory, which, ground
with peas, they call coffee. I have never seen reason to believe that
with absolute free trade the cotton States would take a tenth part of
the value of our present importations. And as far as I can judge from
observation of the comparative use of foreign goods at the South
and at the North, not a tenth part of our duties have been defrayed
by the South in the last twenty years. The most indefensible
protective duty we have is one called for by the South, and which
has been maintained solely to benefit the South. Our protective
system had a Southern origin; its most powerful advocates have
been Southerners; and there has not been a year in the last twenty,
in which it could have been maintained but for Southern votes.
CHAPTER II.
THE JOURNEY FROM WASHINGTON.

Washington, Dec. 10th.—To accomplish the purposes which brought


me to Washington, it was necessary, on arriving here, to make
arrangements to secure food and shelter while I remained. There are
two thousand visitors now in Washington under a similar necessity.
There are a dozen or more persons who, for a consideration,
undertake to provide what they want. Mr. Dexter is reported to be the
best of them, and really seems a very obliging and honestly-
disposed person. To Mr. Dexter, therefore, I commit myself.
I commit myself by inscribing my name in a Register. Five minutes
after I have done so, Clerk No. 4, whose attention I have hitherto
been unable to obtain, suddenly catches the Register by the corner,
swings it round with a jerk, and throws a hieroglyph at it, which
strikes near my name. Henceforth, I figure as Boarder No. 201 (or
whatever it may be). Clerk No. 4 pipes “Boarder away!” and throws
key No. 201 upon the table. Turnkey No. 3 takes it, and me, and my
travelling bag, up several flights of stairs, along corridors and
galleries, and finally consigns me to this little square cell.
I have faith that there is a tight roof above the much-cracked ceiling;
that the bed is clean; and that I shall, by-and-by, be summoned,
along with hundreds of other boarders, to partake, in silent sobriety,
of a “splendid” dinner.
Food and shelter. Therewith should a man be content. But my
perverse nature will not be content: will be wishing things were
otherwise. They say this uneasiness—this passion for change—is a
peculiarity of our diseased Northern nature. The Southern man finds
Providence in all that is: Satan in all that might be. That is good; and,
as I am going South, when I have accomplished my purposes at
Washington, I will not here restrain the escape of my present
discontent.
In my perversity I wish the dinner were not going to be so grand. My
idea is that, if it were not, Mr. Dexter would save moneys, which I
would like to have him expend in other ways. I wish he had more
clerks, so that they would have time to be as polite to an unknown
man as I see they are to John P. Hale; and, at least, answer civil
questions, when his boarders ask them. I don’t like such a fearful
rush of business as there is down stairs. I wish there were men
enough to do the work quietly.
I don’t like these cracked and variegated walls; and, though the roof
may be tight, I don’t like this threatening aspect of the ceiling. It
should be kept for boarders of Damoclesian ambition: I am humble.
I am humble, and I am short, and soon curried; but I am not satisfied
with a quarter of a yard of towelling, having an irregular vacancy in
its centre, where I am liable to insert my head. I am not proud; but I
had rather have something else, or nothing, than these three yards
of ragged and faded quarter-ply carpeting. I also would like a curtain
to the window, and I wish the glass were not so dusty, and that the
sashes did not rattle so in their casements; though, as there is no
other ventilation, I suppose I ought not to complain. Of course not;
but it is confoundedly cold, as well as noisy.
I don’t like that broken latch; I don’t like this broken chair; I would
prefer that this table were not so greasy; I would rather the ashes
and cinders, and the tobacco juice around the grate, had been
removed before I was consigned to the cell.
I wish that less of my two dollars and a half a day went to pay for
game at dinner, and interest on the cost of the mirrors and
mahogany for the public parlours, and of marble for the halls, and
more of it for providing me with a private room, which should be
more than a barely habitable cell, which should also be a little bit
tasteful, home-like, and comfortable.
I wish more of it could be expended in servants’ wages.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like