O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Spring Security - Third Edition

Book Description

Learn how to secure your Java applications from hackers using Spring Security 4.2

About This Book

  • Architect solutions that leverage the full power of Spring Security while remaining loosely coupled.
  • Implement various scenarios such as supporting existing user stores, user sign up, authentication, and supporting AJAX requests,
  • Integrate with popular Microservice and Cloud services such as Zookeeper, Eureka, and Consul, along with advanced techniques, including OAuth, JSON Web Token's (JWS), Hashing, and encryption algorithms

Who This Book Is For

This book is intended for Java Web and/or RESTful webservice developers and assumes a basic understanding of creating Java 8, Java Web and/or RESTful webservice applications, XML, and the Spring Framework. You are not expected to have any previous experience with Spring Security.

What You Will Learn

  • Understand common security vulnerabilities and how to resolve them
  • Learn to perform initial penetration testing to uncover common security vulnerabilities
  • Implement authentication and authorization
  • Learn to utilize existing corporate infrastructure such as LDAP, Active Directory, Kerberos, CAS, OpenID, and OAuth
  • Integrate with popular frameworks such as Spring, Spring-Boot, Spring-Data, JSF, Vaaden, jQuery, and AngularJS.
  • Gain deep understanding of the security challenges with RESTful webservices and microservice architectures
  • Integrate Spring with other security infrastructure components like LDAP, Apache Directory server and SAML

In Detail

Knowing that experienced hackers are itching to test your skills makes security one of the most difficult and high-pressured concerns of creating an application. The complexity of properly securing an application is compounded when you must also integrate this factor with existing code, new technologies, and other frameworks. Use this book to easily secure your Java application with the tried and trusted Spring Security framework, a powerful and highly customizable authentication and access-control framework.

The book starts by integrating a variety of authentication mechanisms. It then demonstrates how to properly restrict access to your application. It also covers tips on integrating with some of the more popular web frameworks. An example of how Spring Security defends against session fixation, moves into concurrency control, and how you can utilize session management for administrative functions is also included.

It concludes with advanced security scenarios for RESTful webservices and microservices, detailing the issues surrounding stateless authentication, and demonstrates a concise, step-by-step approach to solving those issues. And, by the end of the book, readers can rest assured that integrating version 4.2 of Spring Security will be a seamless endeavor from start to finish.

Style and approach

This practical step-by-step tutorial has plenty of example code coupled with the necessary screenshots and clear narration so that grasping content is made easier and quicker.

Downloading the example code for this book. You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the code file.

Table of Contents

  1. Preface
    1. What this book covers
    2. What you need for this book
    3. Who this book is for
    4. Conventions
    5. Reader feedback
    6. Customer support
      1. Downloading the example code
      2. Errata
      3. Piracy
      4. Questions
  2. Anatomy of an Unsafe Application
    1. Security audit
      1. About the sample application
      2. The JBCP calendar application architecture
    2. Application technology
      1. Reviewing the audit results
    3. Authentication
    4. Authorization
      1. Database credential security
        1. Sensitive information
        2. Transport-level protection
        3. Using Spring Security 4.2 to address security concerns
        4. Why Spring Security?
    5. Summary
  3. Getting Started with Spring Security
    1. Hello Spring Security
      1. Importing the sample application
      2. Updating your dependencies
        1. Using Spring 4.3 and Spring Security 4.2
      3. Implementing a Spring Security XML configuration file
      4. Updating your web.xml file
        1. The ContextLoaderListener class
        2. ContextLoaderListener versus DispatcherServlet
        3. The springSecurityFilterChain filter
        4. The DelegatingFilterProxy class
        5. The FilterChainProxy class
      5. Running a secured application
      6. Common problems
    2. A little bit of polish
      1. Customizing login
        1. Configuring logout
        2. The page isn't redirecting properly
        3. Basic role-based authorization
        4. Expression-based authorization
        5. Conditionally displaying authentication information
        6. Customizing behavior after login
    3. Summary
  4. Custom Authentication
    1. JBCP calendar architecture
      1. The CalendarUser object
      2. The Event object
      3. The CalendarService interface
      4. The UserContext interface
      5. The SpringSecurityUserContext interface
    2. Logging in new users using SecurityContextHolder
      1. Managing users in Spring Security
      2. Logging in a new user to an application
      3. Updating SignupController
    3. Creating a custom UserDetailsService object
      1. The CalendarUserDetailsService class
      2. Configuring UserDetailsService
      3. Removing references to UserDetailsManager
      4. The CalendarUserDetails object
      5. The SpringSecurityUserContext simplifications
        1. Displaying custom user attributes
    4. Creating a custom AuthenticationProvider object
      1. CalendarUserAuthenticationProvider
      2. Configuring the CalendarUserAuthenticationProvider object
      3. Authenticating with different parameters
        1. The DomainUsernamePasswordAuthenticationToken class
        2. Updating CalendarUserAuthenticationProvider
        3. Adding domain to the login page
        4. The DomainUsernamePasswordAuthenticationFilter class
        5. Updating our configuration
    5. Which authentication method to use?
    6. Summary
  5. JDBC-Based Authentication
    1. Required dependencies
    2. Using the H2 database
      1. Provided JDBC scripts
      2. Configuring the H2 embedded database
      3. Configuring a JDBC UserDetailsManager implementation
    3. The default user schema of Spring Security
      1. Defining users
      2. Defining user authorities
    4. The UserDetailsManager interface
      1. Group-based access control
      2. Configuring group-based access control
        1. Configuring JdbcUserDetailsManager to use groups
        2. Utilizing GBAC JDBC scripts
        3. The group-based schema
        4. Group authority mappings
    5. Support for a custom schema
      1. Determining the correct JDBC SQL queries
      2. Updating the SQL scripts that are loaded
      3. The CalendarUser authority SQL
      4. Inserting custom authorities
      5. Configuring JdbcUserDetailsManager to use custom SQL queries
    6. Configuring secure passwords
    7. The PasswordEncoder method
      1. Configuring password encoding
      2. Configuring the PasswordEncoder method
      3. Making Spring Security aware of the PasswordEncoder method
        1. Hashing the stored passwords
        2. Hashing the passwords of new users
        3. Not quite secure
    8. Using salt in Spring Security
      1. Updating the Spring Security configuration
      2. Migrating existing passwords
      3. Updating DefaultCalendarUserService 
    9. Trying out the salted passwords
    10. Summary
  6. Authentication with Spring Data
    1. Spring Data JPA
      1. Updating our dependencies
      2. Updating the JBCP calendar to use Spring Data JPA
      3. Reconfiguring the database configuration
      4. Initializing the database
    2. Refactoring from SQL to ORM
      1. Mapping domain objects using JPA
      2. Spring Data repositories
      3. Data access objects
    3. Application services
    4. The UserDetailsService object
      1. Refactoring from an RDBMS to a document database
    5. Document database implementation with MongoDB
      1. Updating our dependencies
      2. Reconfiguring the database configuration in MongoDB
      3. Initializing the MongoDB database
      4. Mapping domain objects with MongoDB
        1. Spring Data repositories of MongoDB
      5. Data access objects in MongoDB
    6. Summary
  7. LDAP Directory Services
    1. Understanding LDAP
      1. LDAP
        1. Common LDAP attribute names
        2. Updating our dependencies
        3. Configuring an LDAP server reference
        4. Enabling the LDAP AuthenticationProviderNext interface
      2. Troubleshooting embedded LDAP
    2. Understanding how Spring LDAP authentication works
      1. Authenticating user credentials
      2. Demonstrating authentication with Apache Directory Studio
        1. Binding anonymously to LDAP
        2. Searching for the user
        3. Binding as a user to LDAP
        4. Determining user role membership
    3. Determining roles with Apache Directory Studio
      1. Mapping additional attributes of UserDetails
      2. Advanced LDAP configuration
        1. Sample JBCP LDAP users
        2. Password comparison versus bind authentication
        3. Configuring basic password comparison
      3. LDAP password encoding and storage
        1. The drawbacks of a password comparison authenticator
    4. Configuring the UserDetailsContextMapper object
      1. Implicit configuration of UserDetailsContextMapper
      2. Viewing additional user details
        1. Using an alternate password attribute
        2. Using LDAP as UserDetailsService
      3. Configuring LdapUserDetailsService
    5. Updating AccountController to use LdapUserDetailsService
      1. Integrating Spring Security with an external LDAP server
    6. Explicit LDAP bean configuration
      1. Configuring an external LDAP server reference
      2. Configuring the LdapAuthenticationProvider interface
      3. Delegating role discovery to UserDetailsService
    7. Integrating with Microsoft Active Directory via LDAP
      1. Built-in AD support in Spring Security 4.2
    8. Summary
  8. Remember-Me Services
    1. What is remember-me?
      1. Dependencies
      2. The token-based remember-me feature
        1. Configuring the token-based remember-me feature
        2. How the token-based remember-me feature works
    2. MD5
      1. Remember-me signature
        1. Token-based remember-me configuration directives
    3. Is remember-me secure?
      1. Authorization rules for remember-me
      2. Persistent remember-me
        1. Using the persistent-based remember-me feature
        2. Adding SQL to create the remember-me schema
        3. Initializing the data source with the remember-me schema
    4. Configuring the persistent-based remember-me feature
      1. How does the persistent-based remember-me feature work?
      2. JPA-based PersistentTokenRepository
      3. Custom RememberMeServices
      4. Cleaning up the expired remember-me sessions
    5. The remember-me architecture
      1. Remember-me and the user life cycle
      2. Restricting the remember-me feature to an IP address
    6. Custom cookie and HTTP parameter names
    7. Summary
  9. Client Certificate Authentication with TLS
    1. How does client certificate authentication work?
      1. Setting up the client certificate authentication infrastructure
        1. Understanding the purpose of a public key infrastructure
        2. Creating a client certificate key pair
        3. Configuring the Tomcat trust store
        4. Configuring Tomcat in Spring Boot
      2. Importing the certificate key pair into a browser
        1. Using Firefox
        2. Using Chrome
        3. Using Internet Explorer
        4. Wrapping up testing
      3. Troubleshooting client certificate authentication
      4. Configuring client certificate authentication in Spring Security
      5. Configuring client certificate authentication using the security namespace
        1. How does Spring Security use certificate information?
        2. How Spring Security certificate authentication works
        3. Handling unauthenticated requests with AuthenticationEntryPoint
        4. Supporting dual-mode authentication
    2. Configuring client certificate authentication using Spring beans
      1. Additional capabilities of bean-based configuration
      2. Considerations when implementing client certificate authentication
    3. Summary
  10. Opening up to OAuth 2
    1. The promising world of OAuth 2
      1. Signing up for an OAuth 2 application
      2. Enabling OAuth authentication with Spring Security
      3. Additional required dependencies
    2. Configuring OAuth 2 support in Spring Security
      1. Local UserConnectionRepository
      2. Creating local database entries for provider details 
      3. The custom UserConnectionRepository interface
      4. The ConnectionSignup flow
    3. Executing the OAuth 2 provider connection workflow
      1. Adding OAuth 2 users
      2. OAuth 2 controller sign-in flow
        1. Automatic user authentication
    4. Additional OAuth 2 providers
      1. The OAuth 2 user registration problem
      2. Registering non-standard OAuth 2 providers
    5. Is OAuth 2 secure?
      1. Summary
  11. Single Sign-On with the Central Authentication Service
    1. Introducing the Central Authentication Service
    2. High-level CAS authentication flow
    3. Spring Security and CAS
      1. Required dependencies
      2. Installing and configuring CAS
    4. Configuring basic CAS integration
      1. Creating the CAS ServiceProperties object
      2. Adding the CasAuthenticationEntryPoint object
      3. Enabling CAS ticket verification
      4. Proving authenticity with the CasAuthenticationProvider object
    5. Single logout
      1. Configuring single logout
    6. Clustered environments
      1. Proxy ticket authentication for stateless services
      2. Configuring proxy ticket authentication
    7. Using proxy tickets
      1. Authenticating proxy tickets
    8. Customizing the CAS server
      1. CAS WAR overlay
      2. How does the CAS internal authentication work?
      3. Configuring CAS to connect to our embedded LDAP server
    9. Getting the UserDetails object from a CAS assertion
      1. Returning LDAP attributes in the CAS response
      2. Mapping LDAP attributes to CAS attributes
      3. Authorizing CAS services to access custom attributes
      4. Acquiring a UserDetails from CAS
      5. The GrantedAuthorityFromAssertionAttributesUser object
      6. Alternative ticket authentication using SAML 1.1
      7. How is attribute retrieval useful?
    10. Additional CAS capabilities
    11. Summary
  12. Fine-Grained Access Control
    1. Gradle dependencies
      1. Integrating Spring Expression Language (SpEL)
        1. The WebSecurityExpressionRoot class
        2. Using the request attribute
        3. Using the hasIpAddress method
        4. The MethodSecurityExpressionRoot class
          1. Page-level authorization
    2. Conditional rendering with the Thymeleaf Spring Security tag library
      1. Conditional rendering based on URL access rules
      2. Conditional rendering using SpEL
      3. Using controller logic to conditionally render content
      4. The WebInvocationPrivilegeEvaluator class
      5. What is the best way to configure in-page authorization?
      6. Method-level security
      7. Why we secure in layers?
        1. Securing the business tier
        2. Adding the @PreAuthorize method annotation
        3. Instructing Spring Security to use method annotations
        4. Validating method security
    3. Interface-based proxies
    4. JSR-250 compliant standardized rules
      1. Method security using Spring's @Secured annotation
      2. Method security rules incorporating method parameters
      3. Method security rules incorporating returned values
      4. Securing method data using role-based filtering
      5. Prefiltering collections with @PreFilter
      6. Comparing method authorization types
      7. Practical considerations for annotation-based security
    5. Summary
  13. Access Control Lists
    1. The conceptual module of ACL
    2. Access control lists in Spring Security
    3. Basic configuration of Spring Security ACL support
      1. Gradle dependencies
      2. Defining a simple target scenario
      3. Adding ACL tables to the H2 database
      4. Configuring SecurityExpressionHandler
      5. The AclPermissionCacheOptimizer object
        1. Optimizing AclPermission Cache
        2. The JdbcMutableAclService object
        3. The BasicLookupStrategy class
          1. Querying with the lowest common denominator
        4. EhCacheBasedAclCache
        5. The ConsoleAuditLogger class
        6. The AclAuthorizationStrategyImpl interface
      6. Creating a simple ACL entry
      7. Advanced ACL topics
        1. How permissions work
      8. The custom ACL permission declaration
      9. Enabling ACL permission evaluation
      10. Mutable ACLs and authorization
        1. Adding ACLs to newly created events
      11. Considerations for a typical ACL deployment
        1. ACL scalability and performance modeling
        2. Do not discount custom development costs
      12. Should I use Spring Security ACL?
    4. Summary
  14. Custom Authorization
    1. Authorizing the requests
      1. Configuration of access decision aggregation
      2. Configuring a UnanimousBased access decision manager
      3. Expression-based request authorization
        1. Customizing request authorization
    2. Dynamically defining access control to URLs
      1. Configuring the RequestConfigMappingService
      2. Custom SecurityMetadataSource implementation
      3. Registering a custom SecurityMetadataSource
      4. Removing our antMatchers() method
    3. Creating a custom expression
      1. Configuring a custom SecurityExpressionRoot
      2. Configuring a custom SecurityExpressionHandler
      3. Configuring and using CustomWebSecurityExpressionHandler
      4. Alternative to a CustomWebSecurityExpressionHandler
        1. How does method security work?
        2. Creating a custom PermissionEvaluator
        3. CalendarPermissionEvaluator
        4. Configuring CalendarPermissionEvaluator
        5. Securing our CalendarService
        6. Benefits of a custom PermissionEvaluator
    4. Summary
  15. Session Management
    1. Configuring session fixation protection
      1. Understanding session fixation attacks
      2. Preventing session fixation attacks with Spring Security
      3. Simulating a session fixation attack
      4. Comparing the session-fixation-protection options
    2. Restricting the number of concurrent sessions per user
      1. Configuring concurrent session control
        1. Understanding concurrent session control
      2. Testing concurrent session control
    3. Configuring expired session redirect
    4. Common problems with concurrency control
      1. Preventing authentication instead of forcing logout
    5. Other benefits of concurrent session control
    6. Displaying active sessions for a user
      1. How Spring Security uses the HttpSession method?
      2. The HttpSessionSecurityContextRepository interface
      3. Configuring how Spring Security uses HttpSession
      4. Debugging with Spring Security's DebugFilter
    7. Summary
  16. Additional Spring Security Features
    1. Security vulnerabilities
    2. Cross-Site Scripting 
    3. Cross-Site Request Forgery
      1. Synchronizer tokens
        1. Synchronizer token support in Spring Security
      2. When to use CSRF protection
        1. CSRF protection and JSON
        2. CSRF and stateless browser applications
        3. Using Spring Security CSRF protection
          1. Using proper HTTP verbs
          2. Configuring CSRF protection
      3. Default CSRF support
        1. Including the CSRF token in the <Form> submissions
        2. Including the CSRF token using the Spring Security JSP tag library
        3. Default CSRF token support
        4. Ajax and JSON requests
        5. The csrfMetaTags tag
        6. jQuery usage
        7. Using the cujoJS's rest.js module
      4. CSRF caveats
        1. Timeouts
        2. Logging in
        3. Logging out
    4. Security HTTP response headers
      1. Default security headers
        1. Cache-Control
        2. Content-Type Options
        3. HTTP Strict Transport Security 
        4. X-Frame-Options
      2. Custom Headers
        1. Static headers
        2. The HeadersWriter instance
        3. The DelegatingRequestMatcherHeaderWriter class
    5. Summary
  17. Migration to Spring Security 4.2
    1. Introduction
    2. Sample migration
      1. Enhancements in Spring Security 4.2
        1. Web improvements:
        2. Spring Security Configuration improvements:
      2. Miscellaneous changes in Spring Security 4.x
      3. Changes to configuration in Spring Security 4
    3. Deprecations
      1. The spring-security-core deprecations
        1. org.springframework.security.access.SecurityConfig
        2. UserDetailsServiceWrapper
        3. UserDetailsWrapper
        4. AbstractAccessDecisionManager
        5. AuthenticationException
        6. AnonymousAuthenticationProvider
        7. AuthenticationDetailsSourceImpl
        8. ProviderManager
        9. RememberMeAuthenticationProvider
        10. GrantedAuthorityImpl
        11. InMemoryDaoImpl
      2. The spring-security-web deprecations
        1. FilterChainProxy
        2. ExceptionTranslationFilter
        3. AbstractAuthenticationProcessingFilter
        4. AnonymousAuthenticationFilter
        5. LoginUrlAuthenticationEntryPoint
        6. PreAuthenticatedGrantedAuthoritiesUserDetailsService
        7. AbstractRememberMeServices
        8. PersistentTokenBasedRememberMeServices
        9. RememberMeAuthenticationFilter
        10. TokenBasedRememberMeServices
        11. ConcurrentSessionControlStrategy
        12. SessionFixationProtectionStrategy
        13. BasicAuthenticationFilter
        14. SecurityContextPersistenceFilter
        15. RequestCacheAwareFilter
        16. ConcurrentSessionFilter
        17. SessionManagementFilter
        18. RequestMatcher
        19. WebSecurityExpressionHandler
        20. @AuthenticationPrincipal
      3. Migrating default filter URLs
      4. JAAS
    4. Summary
  18. Microservice Security with OAuth 2 and JSON Web Tokens
    1. What are microservices?
      1. Monoliths
      2. Microservices
    2. Service-oriented architectures
    3. Microservice security
      1. Service communication
      2. Tight coupling
      3. Technical complexity
    4. The OAuth 2 specification
      1. Access tokens
        1. Access token
        2. Refresh token
      2. Grant types
        1. Authorization code
        2. Implicit
        3. Password credentials
        4. Client credentials
    5. JSON Web Tokens 
      1. Token structure
        1. Encoded JWT 
        2. Header
        3. Payload
        4. Signature
    6. OAuth 2 support in Spring Security
      1. Resource owner
      2. Resource server
      3. Authorization server
      4. RSA JWT access token converter keypair
      5. OAuth 2 resource configuration properties
      6. OAuth 2 client configuration properties
      7. JWT access token converter
      8. The UserDetailsService object
      9. Running the OAuth 2 server application
        1. Server requests
        2. Token requests
    7. Microservices client
      1. Configuring the OAuth 2 client
    8. Summary
  19. Additional Reference Material
    1. Getting started with the JBCP calendar sample code
      1. Gradle Build Tool
      2. Gradle IDE plugins
        1. IntelliJ IDEA
        2. Spring Tool Suite or Eclipse
      3. Creating a new workspace
      4. A sample code structure
      5. Importing the samples
      6. Running the samples
        1. Starting the samples within IDEA
        2. Gradle tasks
        3. Starting the samples within STS
        4. Using HTTPS within STS
      7. HTTPS setup in Tomcat
        1. Generating a server certificate
        2. Configuring Tomcat connector to use SSL
        3. Basic Tomcat SSL termination guide
      8. Supplementary materials