
Introduction to the course.
Detail the topics of this course including:
Introduction to Security
Introduction to the Spring Ecosystem
Introduction to Spring Security
How to perform security-based tests in Spring
Testing support for Spring-based Applications
Customizing Authentication
Leveraging JDBC for Authentication and Authorization
Leveraging Spring-Data for Authentication and Authorization
Leveraging MongoDB and Spring-Data for Authentication and Authorization
Introduction to the course.
Detail the topics of this course including:
Introduction to Security
Introduction to the Spring Ecosystem
Introduction to Spring Security
How to perform security-based tests in Spring
Testing support for Spring-based Applications
Customizing Authentication
Leveraging JDBC for Authentication and Authorization
Leveraging Spring-Data for Authentication and Authorization
Leveraging MongoDB and Spring-Data for Authentication and Authorization
IMPORTANT NOTES FOR STARTING THIS COURSE
Notify me of any issues ASAP!
Allow me to fix issues before leaving review < 5 star
Read the video titles for all sections
Review the Documentation
Extensive Markdown (.md) documentation
Review the JavaDocs
Extensive @since notes.
Review the SonarCloud Quality Metrics
Video player speed can be adjusted faster and slower
Please please please: Review the planned changes for this course
Section: Miscellaneous course details
Where to get the project code from.
Guide to setting up your IDE for this course.
Overview of the codebase for the project that will be used for this course.
Topics covered:
Code structure
Maven build structure
Test Code Coverage
Sonar Cloud Analysis
Running the Maven spring-boot plugin to start individual applications.
Overview of the base Spring Boot Project that will be used as an example throughout this course.
Overview of the H2 database that will be used for most of this course, as well as how to use the embedded database administration tool for managing the database.
Introduction to this video series.
Does anyone have any questions before we begin?
APPLICATION AUDIT RESULTS
This application exhibits the following insecure behavior:
Inadvertent privilege escalation due to lack of URL protection and general authentication
Inappropriate or non-existent use of authorization
Missing database credential security
Personally-identifiable or sensitive information is easily accessible or unencrypted
Insecure transport-level protection due to lack of SSL encryption
The risk level is high
What is Authentication and how Credential-based, Two-factor, and Hardware authentication relate to modern software applications?
Authentication is one of two key security concepts that you must internalize when developing secure applications (the other being authorization).
Authentication identifies who is attempting to request a resource.
Authorization is the second of two core security concepts that are crucial in implementing
and understanding application security. Authorization uses the information that was
validated during authentication to determine whether access should be granted to a
particular resource.
Database credentials are not secure or easily accessible. Through the examination of the
application source code and configuration files, the auditors noted that user passwords
were stored in plain text in the configuration files, making it very easy for a malicious user
with access to the server to gain access to the application.
As the application contains personal and financial data, a rogue user being able to access
any data could expose the company to identity theft or tampering. Protecting access to the
credentials used to access the application should be a top priority for us, and an important
first step is ensuring that one point of failure in security does not compromise the entire
system.
Personally identifiable or sensitive information is easily accessible or unencrypted. The
auditors noted that some significant and sensitive pieces of data were completely
unencrypted or masked anywhere in the system. Fortunately, there are some simple design
patterns and tools that allow us to protect this information securely, with annotation-based
AOP support in Spring Security.
There is insecure transport-layer protection due to lack of TLS encryption.
While, in the real world, it's unthinkable that an online application containing private information would operate without TLS protection.
TLS protection ensures that communication between the browser client and the web application server is secure against many kinds of tampering and snooping.
With Spring Security, we'll be able to make the following changes to increase our application's security:
Segment users of the system into user classes
Assign levels of authorization to user roles
Assign user roles to user classes
Apply authentication rules globally across application resources
Apply authorization rules at all levels of the application architecture
Prevent common types of attacks intended to manipulate or steal a user's session
Summary
In this section, we have reviewed the common points of risk in an unsecured web application and the basic architecture of the sample application. We have also discussed the strategies for securing the application.
Understand some basics of creating Spring Boot Junit 5 test cases
Spring Boot provides a number of utilities and annotations to help when testing your application. Test support is provided by two modules: spring-boot-test contains core items, and spring-boot-test-autoconfigure supports auto-configuration for tests.
Most developers use the spring-boot-starter-test “Starter”, which imports both Spring Boot test modules as well as JUnit Jupiter, AssertJ, Hamcrest, and a number of other useful libraries.
Learn to create Behavior-driven development (BDD) based Mock test cases with Mockito.
Spring MVC Test Framework
The Spring MVC Test framework provides first-class support for testing Spring MVC code with a fluent API that you can use with JUnit, TestNG, or any other testing framework. It is built on the Servlet API mock objects from the spring-test module and, hence, does not use a running Servlet container. It uses the DispatcherServlet to provide full Spring MVC runtime behavior and provides support for loading actual Spring configuration with the TestContext framework in addition to a standalone mode, in which you can manually instantiate controllers and test them one at a time.
Spring MVC Test also provides client-side support for testing code that uses the RestTemplate. Client-side tests mock the server responses and also do not use a running server.
Server-Side Tests
You can write a plain unit test for a Spring MVC controller by using JUnit or TestNG. To do so, instantiate the controller, inject it with mocked or stubbed dependencies, and call its methods (passing MockHttpServletRequest, MockHttpServletResponse, and others, as necessary). However, when writing such a unit test, much remains untested: for example, request mappings, data binding, type conversion, validation, and much more. Furthermore, other controller methods such as @InitBinder, @ModelAttribute, and @ExceptionHandler may also be invoked as part of the request processing lifecycle.
The goal of Spring MVC Test is to provide an effective way to test controllers by performing requests and generating responses through the actual DispatcherServlet.
Spring MVC Test builds on the familiar “mock” implementations of the Servlet API available in the spring-test module. This allows performing requests and generating responses without the need for running in a Servlet container.
Spring provides integration between MockMvc and HtmlUnit. This simplifies performing end-to-end testing when using HTML-based views. This integration lets you:
Easily test HTML pages by using tools such as HtmlUnit, WebDriver, and Geb without the need to deploy to a Servlet container.
Test JavaScript within pages.
Optionally, test using mock services to speed up testing.
Share logic between in-container end-to-end tests and out-of-container integration tests.
Why HtmlUnit Integration?
The most obvious question that comes to mind is “Why do I need this?” The answer is best found by exploring a very basic sample application. Assume you have a Spring MVC web application that supports CRUD operations on a Message object. The application also supports paging through all messages. How would you go about testing it?
HtmlUnit is a "GUI-Less browser for Java programs". It models HTML documents and provides an API that allows you to invoke pages, fill out forms, click links, etc... just like you do in your "normal" browser.
It has fairly good JavaScript support (which is constantly improving) and is able to work even with quite complex AJAX libraries, simulating Chrome, Firefox or Internet Explorer depending on the configuration used.
Executing tests with "mvn clean verify" command
In this section, we'll apply a minimal Spring Security configuration to start addressing our first finding—inadvertent privilege escalation due to a lack of URL protection.
In this section, we will cover the following topics:
Implementing a basic level of security on the Event Manager application, using the automatic configuration option in Spring Security
Learning how to customize both the login and logout experience
Configuring Spring Security to restrict access differently, depending on the URL
Leveraging the expression-based access controls of Spring Security
Conditionally displaying basic information about the logged-in user using the Thymeleaf library in Spring Security
Determining the user's default location after login, based on their role
Section Documentation Review
Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications.
Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements
Features
Comprehensive and extensible support for both Authentication and Authorization
Protection against attacks like session fixation, clickjacking, cross-site request forgery, etc
Servlet API integration
Optional integration with Spring Web MVC
Much more…
The Proxy pattern and Spring Aspect-Oriented Programming (AOP)
Servlet Filter
A filter is not servlet. A filter is something we do behind the scenes, behind the servlet. A filter is not a front-end or presentation layer task but an administrator task. Additionally, a filter is the preprocessor of a request and postprocessor of a response.
As the treatment of data, a filter allows modification, alteration, encryption, decryption, and compression of the data. These filters run as a program on the server before the servlet or JSP page associated with that filter runs.
Filter Chain
Spring Security provides security control for web resources using Servlet Filter technology, and several Filters are combined into a Filter Chain to apply each security function when necessary. Filters used in Spring Security are Beans that are managed by Spring container and they are used in a special Dependency Bean format managed in Spring by flexibly abstracting detail security functions needed for main security functions such as user authentication and secured resource authority.
The below Filters (AuthenticationProcessingFilter, HttpSessionContextIntegrationFilter, ExceptionTranslationFilter, FilterSecurityInterceptor) are essential for Spring Security, and when necessary, various Filters basically implemented in Spring Security can be added/changed.
In this lecture, we add 'spring-boot-starter-security' dependency. Then we discuss the changes to the application by adding this one dependency.
chapter02.00
chapter02.01
Enabling Spring Security
Use the AuthenticationManagerBuilder to create an in-memory Authentication with custom credentials
chapter02.01
Implement base HttpSecurity
chapter02.01
Running application with custom configuration
Applying the base Spring Security implementation was blindingly fast and has provided us with a login page, username, and password-based authentication, as well as the automatic interception of URLs in our application. However, there are gaps between what the automatic configuration setup provides and what our end goal is, which are listed as follows:
We should add a login form that's integrated with our application's look and feel.
There is no obvious way for a user to log out. We've locked down all pages in the application, including the Welcome page, which a potential user may want to browse anonymously. We'll need to redefine the roles required to accommodate anonymous, authenticated, and administrative users.
We do not display any contextual information to indicate to the user that they are authenticated. It would be nice to display a greeting
We've had to hardcode the username, password, and role information of the user in the SecurityConfig configuration file.
You can see that the username and password are right there in the file. It's unlikely that we'd want to add a new declaration to the file for every user of the system! To address this, we'll need to update the configuration with another type
of authentication.
chapter02.02
chapter02.02
The HttpSecurity configuration of Spring Security automatically adds support for logging the user out.
The page isn't redirecting properly
If you have not already, restart the application and visit http://localhost:8080 in
Firefox; you will see an error, as shown in the following screenshot:
Basic role-based authorization
We can expand on the Spring Security configuration from Hello Spring Security to vary the access controls by URL. In this section, you will find a configuration that allows more granular control over how resources can be accessed. In the configuration, Spring Security does the following tasks:
It completely ignores any request that starts with /resources/. This is beneficial
since our images, CSS, and JavaScript do not need to use Spring Security.
It allows anonymous users to access the Welcome, Login, and Logout pages.
It only allows administrators access to the All Events page.
It adds an administrator that can access the All Events page.
Configuring basic role-based authorization in SecurityConfig.java
chapter02.03
? matches a single character.
* matches zero or more characters, excluding /.
** matches zero or more directories in a path.
The pattern "/events/**" matches "/events", "/events/",
"/events/1", and "/events/1/form?test=1"; it does not match "/events123".
The pattern "/events*" matches "/events", and "/events123"; it does not match "/events/" or "/events/1".
The pattern "/events*/**" matches "/events", "/events/", "/events/1","/events123", "/events123/456", and "/events/1/form?test=1".
Need to run both user1 and admin1
Expression-based authorization
You may have noticed that granting access to everyone was not nearly as concise as we may
have liked. Fortunately, Spring Security can leverage Spring Expression Language (SpEL)
to determine whether a user has authorization.
Need to run both user1 and admin1
Conditionally displaying authentication information
Currently, our application has no indication as to whether we are logged in or not. In fact, it
appears as though we are always logged in since the Logout link is always displayed. In
this section, we will demonstrate how to display the authenticated user's username and
conditionally display portions of the page using Thymeleaf’s Spring Security tag library.
Need to run both user1 and admin1
Customizing behavior after login and run chapter02.06
We have already discussed how to customize a user's experience during login, but
sometimes it is necessary to customize the behavior after login. In this section, we will
discuss how Spring Security behaves after login and will provide a simple mechanism to
customize this behavior.
In the default configuration, Spring Security has two different flows after successful
authentication. The first scenario occurs if a user never visits a resource that requires
authentication. In this instance, after a successful login attempt, the user will be sent to the
defaultSuccessUrl() method chained to the formLogin() method. If left undefined,
defaultSuccessUrl() will be the context root of the application.
Summary
In this chapter, we have applied a very basic Spring Security configuration, explained how to customize the user's login and logout experience, and demonstrated how to display basis information, such as a username, in our web application.
Enabling Spring Security debugging and logging
(in SecurityConfig.java)
@EnableWebSecurity(debug = true)
(in the application.properties)
logging.level.org.springframework.security=DEBUG
Spring Security Testing Support
Including the following:
MockMvc Test Integration
Method Security
Mocking Security Users
MockMvc RequestPostProcessor
MockMvc RequestBuilders
MockMvc ResultMatchers
Mocking Security Users
SecurityMockMvcRequestPostProcessors support
SecurityMockMvcRequestPostProcessors is a MockMv RequestPostProcessor implementations for Spring Security.
SecurityMockMvcRequestBuilders fluent security support
SecurityMockMvcRequestBuilders contains Spring Security related MockMvc RequestBuilder's
SecurityMockMvcResultMatchers for security assertions
SecurityMockMvcResultMatchers contains Security related MockMvc ResultMatcher's.
In this section, we'll explore how to solve some common, real-world problems by extending Spring Security's authentication support to use our existing set of APIs. Through this exploration, we'll get an understanding of each of the building blocks that Spring Security uses in order to authenticate users.
During the course of this chapter, we will cover the following topics:
Leverage Spring Security’s annotations and Java-based configuration
Discovering how to obtain the details of the currently logged-in user
Adding the ability to log in after creating a new account
Learning the simplest method for indicating to Spring Security, that a user is authenticated
Creating custom UserDetailsService and AuthenticationProvider implementations that properly decouple the rest of the application from Spring Security
Adding domain-based authentication to demonstrate how to authenticate with more than just a username and password
We need to introduce the following components:
AppUser Object
Event Object
EventService Interface
UserContext Interface
Like most applications, our application requires us to interact with the currently logged-in user. We have created a very simple interface called UserContext to manage the currently logged-in user.
Remove UserContextStub.java
Add or Refactor SpringSecurityUserContext.java to get user from SecurityContextHolder
Create InMemoryUserDetailsManager outside of the WebSecurityConfigurerAdapter
Creating new Authentication Users in Spring Security
Updating Registrationontroller to auto-login
Update EventUserDetailsService to return a UserDetails Object that extends AppUser and implements UserDetails in SpringSecurityUserContext
Update header.html to Displaying custom user attributes
Leverage the following annotations:
@WithUserDetails("admin1@baselogic.com")
Leverage the following annotations:
@WithSecurityContext
@WithMockEventUserDetailsUser1
@WithMockEventUserDetailsAdmin1
WithMockEventUserDetailsSecurityContextFactory
Configure EventUserAuthenticationProvider
Create Create a DomainUsernamePasswordAuthenticationToken Object
Update EventUserAuthenticationProvider to utilize the domain field
Refactor login.html file adding an additional parameter
Create DomainUsernamePasswordAuthenticationFilter
Update to our SecurityConfig file to support DomainUsernamePasswordAuthenticationFilter
In the previous section, we saw how we can extend Spring Security to utilize our AppUserDao interface and our existing domain model to authenticate users. In this section, we will see how we can use Spring Security's built-in JDBC support.
In this section, we will cover the following topics:
Using Spring Security's built-in JDBC-based authentication support
Utilizing Spring Security's group-based authorization to make administering users easier
Learning how to use Spring Security's UserDetailsManager interface
Configuring Spring Security to utilize the existing AppUser schema to authenticate users
Learning how we can secure passwords using Spring Security's new cryptography module
Using Spring Security's default JDBC authentication
If your application has not yet implemented security, or if your security infrastructure is using a database, Spring Security provides out-of-the-box support that can simplify the solving of your security needs. Spring Security provides a default schema for users, authorities, and groups. If that does not meet your needs, it allows for the querying and managing of users to be customized. In the next section, we are going to go through the basic steps for setting up JDBC authentication with Spring Security.
Configuring an H2 embedded database. Database schema authentication and authorization.
Defining user and authorities schema (DML) and data (DDL)
After the SQL is added to the embedded database configuration, we should be able to start the application and log in. Try logging in with the new user using disabled1@example.com as the username and disabled1 as the password. Notice that
Spring Security does not allow the user to log in and provides the error message Reason: User is disabled.
Reviewing the details for the new Password Encoder in Spring
https://spring.io/blog/2017/11/01/spring-security-5-0-0-rc1-released#password-encoding
Update existing user passwords with BCryptPasswordEncoderMain
In this chapter, we learned how to use Spring Security's built-in JDBC support. Specifically, we have learned that Spring Security provides a default schema for new applications.
We also explored how to implement GBAC and how it can make managing users easier.
We also learned how to integrate Spring Security's JDBC support with an existing database and also how to secure our passwords by hashing them and using a randomly-generated salt.
In the next chapter, we will explore the Spring Data project and how to configure Spring Security to use object-relational mapping (ORM) to connect to an RDBMS, as well as a document database.
Initializing the database
Need to modify some code used for Testing and test fixtures
MongoBD Configuration
Exciting news about this new Spring Security Master Class
Description
This course is a deep-dive into the Spring Security project. In this course, we will learn how to identify security issues with our applications and how Spring Security can help solve those issues.
This application has extensive testing and extensive documentation so you will completely understand each security task in each section and why that task is being done as well as what side-effects might occur due to the changes we make.
We will take a very incremental approach to each and every section task, so you will build your deep knowledge of Security and the Spring Security module and by the end of this course, you will have a deep theoretical as well as hands-on practical knowledge of all of the Security topics covered in this course.
Course Outline:
By the end of the course you will:
Detail the topics of this course including:
Introduction to Application Security
Introduction to the Spring Ecosystem
Introduction to Spring Security
How to perform security-based tests in Spring
Testing support for Spring-based Applications
Customizing Authentication
Leverage JDBC for Authentication and Authorization
Leverage Spring-Data JPA for Authentication and Authorization
Leverage MongoDB and Spring-Data for Authentication and Authorization
Course Overview:
Section 1: Introduction to this course
Section 2: Introduction To Security
Section 3: The Spring Ecosystem
Section 4: Getting Started with Spring Security
Section 5: Spring Security Testing
Section 6: Customizing Authentication
Section 7: Leveraging JDBC for Authentication and Authorization
Section 8: Leveraging JPA for Authentication and Authorization