Spring
Security
3
Secure
your web
applications against
malicious
intruders
with
this
easy
to
follow
practical
guide
Peter Mularien
rpAfKTl°Pen
source
II nv.IV I I communityexperiencedistilled
cfb
<A>
PUBLISHING
Table of Contents
Preface 1
Chapter
1:Anatomy
ofan Unsafe Application 9Security
audit 10About thesample
application
10The JBCP pets application architecture 11
Application
technology 12Reviewing
the audit results 13Authentication 15
Authorization 16
Database Credential
Security
16Sensitive Information 17
Transport-Level Protection 17
Using Spring
Security 3 to addresssecurity
concerns 18Why
Spring Security? 18Summary
19Chapter
2:Getting
Started withSpring Security
21Coresecurity concepts 22
Authentication 22
Authorization 23
Securing
ourapplication
in three easysteps 26Implementing
aSpring Security
XMLconfiguration file 26Adding
the Spring DelegatingFilterProxyto your web.xmlfile 27Adding
the SpringSecurity
XMLconfiguration
file referencetoweb.xml 28Mind the
gaps!
30Commonproblems 31
Security is complicated: The architecture of secured webrequests 32
Howrequests are
processed?
32How users areauthenticated? 37
What isspring_security_loginandhowdidwegethere? 41
Where do theuser's credentialsgetvalidated? 43 Whengoodauthenticationgoes bad? 44
How
requests
are authorized? 45Configurationofaccessdecisionaggregation 49
Accessconfiguration using spring expression language 51
Summary 55
Chapter
3:Enhancing
the UserExperience
57Customizing
thelogin
page 57Implementing a custom
login
page 59Implementingthelogincontroller 59
AddingtheloginJSP 60
ConfiguringSpring Securitytouse ourSpring MVClogin page 61
Understanding logout functionality
63Addinga Log Out linktothe site header 63
Howlogoutworks 64
ChangingthelogoutURL 66
Logoutconfigurationdirectives 66
Rememberme 67
Implementingthe remember me option 67
How rememberme works 68
Remembermeand theuserlifecycle 71
Remembermeconfigurationdirectives 72
Is remember mesecure? 73
Authorization rulesdifferentiatingremembered andfullyauthenticated sessions 74 Building an IP-aware remembermeservice 75
Customizingthe remembermesignature 79
Implementing password change
management 80Extending
thein-memory
credentialstore tosupportpassword change
80 Extending InMemoryDaolmpIwith InMemoryChangePasswordDaolmpI 81Configuring Spring Securitytouse InMemoryChangePasswordDaolmpI 82
Buildingachange password page 83
Addingachange passwordhandler to AccountController 84
Exercise notes 85
Summary 86
Chapter
4:Securing
Credential Storage 87Database-backed authentication with
Spring
Security 88Configuring
a database-resident authentication store 88Creatingthe defaultSpring Security schema 88
Configuringthe HSQL embedded database 89
Configuring JdbcDaolmpIauthenticationstore 89 Addinguserdefinitions to the schema 90
TableofContents Howdatabase-backed authentication works 90
Implementing
a customJDBC UserDetailsService 92Creating acustom JDBC UserDetailsService class 92
AddingaSpringBean declaration for the custom UserDetailsService 92
Out of thebox JDBC-based usermanagement 93
Advanced
configuration
ofJdbcDaolmpI 95Configuring
group-based authorization 96Configuring JdbcDaolmpItouse groups 97
Modifyingtheinitialload SQLscript 97
Modifyingtheembeddeddatabase creation declaration 98
Using a
legacy
orcustom schemawith database-resident authentication 98 Determiningthe correctJDBCSQLqueries 99ConfiguringtheJdbcDaolmpItouse customSQLqueries 100
Configuring
securepasswords 101Configuring password encoding
104ConfiguringthePasswordEncoder 104
ConfiguringtheAuthenticationProvider 104
Writingthe databasebootstrappassword encoder 105
Configuringthebootstrap password encoder 105
Would you likesomesalt withthat
password?
106Configuring
a saltedpassword 108Declaringthe SaltSourceSpringbean 109
Wiringthe PasswordEncoder to the SaltSource 109
Augmenting DatabasePasswordSecurerBean 109
Enhancing
thechange password functionality
111Configuring
a custom saltsource 111Extendingthe database schema 112
Tweaking configurationoftheCustomJdbcDaolmpIUserDetails service 112
Overridingthe baselineUserDetailsimplementation 113
ExtendingthefunctionalityofCustomJdbcDaolmpI 113
Moving remembermetothe database 115
Configuring
database-resident remember metokens 115AddingSQLto createtherememberme schema 115
Adding newSQLscripttotheembeddeddatabase declaration 116
Configuringremembermeservicestopersisttothedatabase 116 Are database-backed persistenttokens more secure? 116
Securing
your sitewith SSL 117Setting
upApache
Tomcat for SSL 117Generatinga serverkeystore 118
ConfiguringTomcat's SSL Connector 118
Automatically securing portions
of the site 119Secureport mapping 121
Chapter
5: Fine-Grained Access Control 123Re-thinking application
functionality
and security 124Planning for application
security
124Planning
user roles 124Planning page-level security
126Methods of Fine-Grained authorization 127
Using
Spring Security Tag Libraryto conditionally rendercontent 128 Conditionalrenderingbased onURLaccessrules 128Conditionalrendering based onSpring ELExpressions 129
ConditionallyrenderingtheSpringSecurity2way 130
Using
controllerlogic
toconditionally
render content 131Adding conditional displayof theLogIn link 131
Populatingmodeldatabased onusercredentials 132
Whatis the bestway to
configure in-page
authorization? 132Securing
the business tier 134The basics of
securing
businessmethods 135 Adding @PreAuthorizemethod annotation 136Instructing SpringSecurityto usemethod annotations 136
Validatingmethodsecurity 136 Several flavors of method security 137 JSR-250compliantstandardizedrules 137 Methodsecurity using Spring's ©Securedannotation 139 Methodsecurityrulesusing AspectOrientedProgramming 139
Comparingmethod authorizationtypes 140
How does method
security
work? 141 Advanced methodsecurity 144Method security rules using bean decorators 145
Method
security
rulesincorporating
method parameters 147 Howmethod parameterbinding
works 147Securing
method datathrough
Role-basedfiltering
149AddingRole-baseddatafilteringwith @PostFilter 150
Pre-filteringcollectionswith method @PreFilter 152
Whyuse a@PreFilteratall? 153 A fairwarning about method
security
154Summary 155
Chapter
6: AdvancedConfiguration
and Extension 157Writing
a custom security filter 158IP
filtering
at the servlet filter level 158Writingourcustom servlet filter 158
Configuring the IP servlet filter 160
TableofContents
Writing
a custom AuthenticationProvider 162Implementing simple single sign-on
with anAuthentication Provider 162Customizingthe authentication token 163
Writingtherequestheaderprocessing servlet filter 164
Writingtherequest header AuthenticationProvider 166
Combining AuthenticationProviders 167
Simulating single sign-on
withrequest
headers 169Considerations when
writing
acustom AuthenticationProvider 170Session managementandconcurrency 170
Configuring
session fixationprotection
171Understandingsession fixation attacks 171
Preventingsessionfixation attackswithSpring Security 172
Simulatingasession fixation attack 173
Comparing session-fixation-protection options 175
Enhancing
userprotection
with concurrent session control 176Configuringconcurrent session control 176
Understandingconcurrent session control 177
Testingconcurrent session control 178 Configuringexpiredsessionredirect 179
Other benefits ofconcurrent session control 179
Displayingacount ofactiveusers 179
Displayinginformation about allusers 180
Understanding
andconfiguring
exception handling 182Configuring
"Access Denied"handling
184Configuringan"Access Denied" destination URL 184
AddingcontrollerhandlingofAccessDeniedException 184
Writingthe Access Denied page 185 Whatcauses anAccessDeniedException 186
The
importance
of theAuthenticationEntryPoint
187Configuring Spring Security
infrastructure beansmanually 188 Ahigh level overviewofSpring Security
bean dependencies 189Reconfiguring the webapplication 189
Configuring
a minimal Spring Securityenvironment 190Configuringaminimal servlet filter set 191
Configuringaminimal supporting objectset 195
Advanced Spring Security bean-based
configuration
196Adjusting
factors related to sessionlifecycle
196Manual
configuration
of other common services 197Declaring remaining missingfilters 198
LogoutFilter 198
RememberMeAuthenticationFilter 199
ExceptionTranslationFilter 202
Bean-based
configuration
ofmethodsecurity
203Wrapping
upexplicit configuration
204Which type of
configuration
should I choose? 204 Authenticationevent handling 205Configuring
an authentication event listener 207Declaring requiredbeandependencies 207
Buildingacustomapplicationevent listener 207
Out of theboxApplicationListeners 208
Multitudes of
application
events 209Building
a custom implementation ofan SpEL expression handler 210Summary 211
Chapter
7: Access Control Lists 213Using
Access Control Lists for businessobject security
213Access Control Lists in
Spring
Security 215 Basicconfiguration
ofSpringSecurity
ACLsupport
217Defining asimple target scenario 217
AddingACLtablesto the HSQL database 218
Configuring
the Access DecisionManager
220Configuring supporting
ACL beans 221Creating
asimple
ACL entry 226Advanced ACLtopics 227
How permissionswork 228
Custom ACL
permission
declaration 231ACL-Enabling
yourJSPs with the SpringSecurity
JSPtag library
234Spring Expression
Languagesupport
forACLs 235Mutable ACLs and authorization 237 Configuringa Springtransaction manager 238
InteractingwiththeJdbcMutableAclService 239
Ehcache ACL
caching
241 Configuring Ehcache ACLcaching 241 HowSpringACLusesEhcache 242Considerations fora typicalACL deployment 243 About ACL
scalability
andperformancemodelling
243Do not discount customdevelopment costs 245
Should Iuse
Spring Security
ACL? 247Summary 247
Chapter
8:Opening
up toOpenID
249The
promising
world ofOpenID 249TableofContents
Enabling OpenID
authentication withSpring
Security 252Writing
anOpenID login
form 252Configuring OpenID
supportinSpring Security
253Adding
OpenIDusers 254The OpenIDuser registration problem 255
How
OpenID
identifiers are resolved 255Implementing user
registration
with OpenID 258AddingtheOpenID registration option 258
Differentiatingbetweenaloginandregistration request 259
Configuringacustom authentication failure handler 260
Addingthe OpenIDregistration functionalitytothe controller 260
Attribute
Exchange
264EnablingAX inSpring Security OpenID 265
Real-worldAXsupportand limitations 267
Is
OpenID
secure? 268Summary 269
Chapter9: LDAP
Directory
Services 271Understanding
LDAP 272LDAP 272
Common LDAP attribute names 273
Running anembedded LDAP server 275
Configuring
basic LDAP integration 275Configuring
an LDAPserverreference 275Enabling
the LDAP AuthenticationProvider 276Troubleshooting
embedded LDAP 276Understanding how
Spring
LDAP authentication works 277Authenticating usercredentials 278
Determining
userrolemembership 279Mapping
additional attributes of UserDetails 282Advanced LDAP
configuration
283SampleJBCP LDAP users 283
Password
comparison
versus Bind authentication 284Configuringbasicpassword comparison 285 LDAPpassword encoding andstorage 285 The drawbacks ofaPasswordComparisonAuthenticator 286
Configuringthe
UserDetailsContextMapper
287Implicit configurationofaUserDetailsContextMapper 287
Viewingadditionaluserdetails 287
Using
LDAP as a UserDetailsService 290 Notes about remembermewithan LDAP UserDetailsService 291ConfigurationforanIn-Memoryremembermeservice 291
Integrating
with an external LDAP server 292Explicit
LDAP beanconfiguration
292Configuring
an external LDAPserverreference 293Configuring an
LdapAuthenticationProvider
293Integrating
with Microsoft Active Directory via LDAP 294Delegating
role discoverytoa UserDetailsService 297Summary
298Chapter
10:Single Sign
On with Central Authentication Service 299Introducing Central AuthenticationService 299
High
levelCAS authentication flow 300Spring
Security and CAS 301CAS installation and
configuration
302Configuring
basic CASintegration
303Adding the
CasAuthenticationEntryPoint
304Enabling CAS ticket verification 305
Proving authenticity
with the CasAuthenticationProvider 307 Advanced CASconfiguration
309Retrievalofattributesfrom CAS assertion 309 How CAS internal authentication works 310
ConfiguringCAStoconnect toourembedded LDAPserver 311
GettingUserDetails froma CASassertion 314
Examiningthe CAS assertion 315
MappingLDAP attributes to CAS attributes 316
Finally,returningthe attributes in the CAS assertion 318 AlternativeTicketauthentication usingSAM L1.1 319 How isAttribute Retrieval useful? 320
Additional CAS
capabilities
321Summary
322Chapter
11: Client Certificate Authentication 323How ClientCertificate authentication works 324
Setting
upa Client Certificate authenticationinfrastructure 326Understanding
the purpose ofa public keyinfrastructure 326Creating
a client certificatekey
pair 327Configuring
the Tomcat trust store 328Importing
the certificatekey
pairinto a browser 330UsingFirefox 330
TableofContents
Wrapping
uptesting
331Troubleshooting ClientCertificateauthentication 332
Configuring
ClientCertificate authentication inSpring Security
333Configuring
Client Certificate authentication usingthe security namespace 333
How
Spring Security
usescertificate information 334HowSpring Securitycertificate authentication works 335
Other loose ends 337
Supporting
Dual-Mode authentication 338Configuring
Client CertificateauthenticationusingSpring
Beans 340 Additionalcapabilities
of bean-basedconfiguration
341 Considerationswhenimplementing
Client Certificate authentication 342Summary
343Chapter
12:Spring Security
Extensions 345Spring
Security
Extensions 345A
primer
on Kerberos and SPNEGO authentication 346Kerberos authentication in
Spring Security
349Overall Kerberos
Spring Security
authentication flow 349Getting prepared
350Assumptionsforourexamples 351
Creating akeytabfile 352
Configuring
Kerberos-relatedSpring
beans 353Wiring
SPNEGO beansto thesecurity
namespace 355AddingtheApplication Server machine to a Kerberos realm 357
Special
considerations for Firefox users 358Troubleshooting
358Verifying connectivitywith standard tools 359
EnablingJava GSS-APIdebugging 359
Othertroubleshooting steps 360
Configuring
LDAP UserDetailsServicewithKerberos 361Using
form login with Kerberos 362Summary
364Chapter
13:Migration
toSpring
Security 3 365Migrating
fromSpring Security
2 365Enhancements in Spring Security 3 366
Changes
toconfiguration
in Spring Security 3 367Rearranged AuthenticationManager
configuration 367Newconfiguration syntaxfor session
management options
368of
ChangestoCustomAfterlnvocationProvider 370
Minor
configuration changes
371Changes to
packages
and classes 371Summary 373
Appendix: Additional Reference Material 375
Getting
startedwith JBCP Petssample code 375Available
application
events 376Spring
Security
virtual URLs 379Methodsecurity