Chapter 17 - Spring Security Flashcards
What is spring security
Spring Security is a powerful authentication and authorization framework for Java applications. It’s a part of the larger Spring ecosystem and provides comprehensive security solutions for web applications, RESTful services, and more.
What is Authentication
Authentication is the process of verifying the identity of a user or system to ensure they are who they claim to be. In the context of computer systems and applications, authentication confirms the legitimacy of a user’s credentials, such as a username and password, tokens, biometrics, or certificates.
what is Authorization
Authorization is the process of determining whether an authenticated user has the necessary permissions or rights to access a specific resource, perform an action, or use certain functionalities within a system or application.
Authentication mechanisms
Authentication:
Mechanisms:
Form-based: User authentication via a login form where users input their credentials (username/password).
HTTP Basic: Authentication through the HTTP Authorization header, sending credentials encoded in Base64.
OAuth: Protocol for delegated authorization, allowing third-party applications limited access.
JWT (JSON Web Tokens): A compact and self-contained way to securely transmit information between parties as a JSON object.
Authentication Sources:
Databases: Storing user credentials (username, encrypted password) in a database and verifying against these records during login.
LDAP (Lightweight Directory Access Protocol): Authenticating users against LDAP directories, commonly used in enterprise environments.
Custom Implementations: Developing custom authentication logic to validate users, which might involve external systems or unique business requirements.
Purpose:
Authentication ensures that users are who they claim to be before allowing access to protected resources or functionalities.
Understanding these mechanisms and sources allows developers to implement the most suitable authentication method based on security needs and application requirements.
Authorisation mechanisms
Authorization:
Access Control:
Role-Based Access Control (RBAC): Assigning permissions to users based on their roles within an organization. Users inherit permissions associated with their roles.
Permission-Based Access Control: Granting access based on specific permissions or rights associated directly with users.
Configuration:
Defining access rules for different endpoints or resources using:
Annotations: Using annotations like @PreAuthorize, @PostAuthorize, or method-level security annotations to enforce access control.
Configuration: Configuring access rules in XML, Java configurations, or using Spring Security’s DSL (Domain Specific Language).
Purpose:
Authorization determines what actions or resources an authenticated user can access within the system.
It allows administrators or developers to control and restrict access to sensitive functionalities or data based on predefined roles or permissions.
Authentication Workflow
Request for Access: A user attempts to access a secured resource in the application by sending an HTTP request (e.g., accessing a protected URL).
Security Filter Chain: The request is intercepted by the Security Filter Chain, which comprises multiple filters provided by Spring Security.
Authentication Filter: The appropriate authentication filter intercepts the request. For example:
For form-based authentication, UsernamePasswordAuthenticationFilter intercepts login requests.
For token-based authentication, TokenAuthenticationFilter handles token-based authentication.
AuthenticationManager: The filter delegates the authentication request to the AuthenticationManager.
AuthenticationProvider: The AuthenticationManager consults the configured AuthenticationProviders. Each provider handles a specific authentication method (e.g., DaoAuthenticationProvider for database-based authentication).
UserDetailsService: If using username/password authentication, the AuthenticationProvider interacts with the UserDetailsService to load user details (username, password, authorities) from the configured user repository (e.g., database).
Authentication: The AuthenticationProvider validates the credentials. If successful, it creates an Authentication object containing information about the authenticated user (principal) and their granted authorities (roles).
SecurityContextHolder: The Authentication object is stored in the SecurityContextHolder to represent the currently authenticated user. This context is typically associated with the current thread.
Security Filter chain
The Security Filter Chain in Spring Security is a fundamental concept that manages the security aspects of an application. It’s a series of filters responsible for handling various security-related tasks in the authentication and authorization process.
Filter Chain Configuration:
Defined within the Spring Security configuration, typically by extending WebSecurityConfigurerAdapter or using @EnableWebSecurity.
Specifies the order and types of security filters to be applied.
Filter Chain Execution:
When an HTTP request is made to a secured endpoint, it traverses through this chain of filters.
Filter Order:
Each filter in the chain has a specific responsibility and executes in a predefined order.
Filters are applied in sequence, and each filter may perform authentication, authorization, or other security-related tasks.
Authentication Filter
In Spring Security, the Authentication Filter plays a crucial role in handling the authentication process for incoming requests. It intercepts the request and initiates the authentication procedure based on the type of authentication configured in the application.
Key Aspects of Spring Authentication Filter:
Request Interception:
When a request hits a secured endpoint, the Authentication Filter intercepts it before it reaches the controller.
Different authentication filters are used based on the authentication mechanism configured (e.g., UsernamePasswordAuthenticationFilter, TokenAuthenticationFilter).
Specific Authentication Methods:
Each type of authentication mechanism (form-based, token-based, etc.) has its dedicated filter designed to handle that specific authentication flow.
Initiating Authentication Process:
The Authentication Filter initiates the authentication flow by examining the incoming request and extracting authentication details.
For instance, in form-based authentication, the UsernamePasswordAuthenticationFilter retrieves credentials from the login form fields.
Delegation to AuthenticationManager:
Once the Authentication Filter gathers authentication data, it delegates the actual authentication process to the AuthenticationManager.
Receiving Authentication Result:
The Authentication Filter receives the authentication result from the AuthenticationManager.
Success or Failure Handling:
On successful authentication, the filter generates an authentication token or updates the SecurityContext.
If authentication fails, appropriate error handling is triggered, such as returning an error response or redirecting to an error page.
The AuthenticationManager
The AuthenticationManager in Spring Security is a pivotal interface responsible for authenticating the credentials provided by a user during the authentication process. It serves as the central point for managing authentication within the security framework.
Key Responsibilities of AuthenticationManager:
Authentication Handling:
Receives authentication requests from authentication filters or providers.
Acts as a facade to multiple AuthenticationProvider instances.
Authentication Delegation:
Delegates the actual authentication process to its associated AuthenticationProvider(s).
Multiple Provider Support:
Supports multiple authentication providers, each specializing in different authentication mechanisms (e.g., database, LDAP, OAuth, custom implementations).
Verify Credentials:
Validates the user’s provided credentials against the user details stored in the configured authentication providers.
AuthenticationProvider
The AuthenticationProvider interface in Spring Security is responsible for the actual authentication process. It validates the credentials provided by the user and generates an Authentication object if the authentication is successful.
Key Responsibilities of AuthenticationProvider:
Authentication Processing:
Receives an Authentication request typically containing user credentials.
Performs authentication logic against the specified user data source.
Multiple Authentication Sources:
Supports various authentication methods or user data sources (e.g., database, LDAP, custom implementations).
Credentials Validation:
Validates the user-provided credentials (like username and password) against the stored user information.
Authentication Outcome:
On successful authentication, generates an Authentication object containing user details and granted authorities (roles, permissions).
UserDetailsService
The UserDetailsService interface in Spring Security is responsible for fetching user-specific data during the authentication process. It interacts with the authentication providers to retrieve user details necessary for authentication.
Key Responsibilities of UserDetailsService:
User Data Retrieval:
Loads user-specific data based on a username.
Fetches user details like username, password, granted authorities (roles), and other user-related information from a data source.
Integration with Authentication Providers:
Used by AuthenticationProviders to retrieve user details during the authentication process.
Custom User Data Sources:
Supports integration with various user data sources (e.g., databases, in-memory user stores, custom data repositories).
SecurityContextHolder
SecurityContextHolder in Spring Security is a fundamental component that provides access to the security context of an application. It manages the security-related information associated with the current thread of execution, primarily storing and providing access to the details of the currently authenticated user.
Key Aspects of SecurityContextHolder:
Security Context Management:
Manages the security context associated with the current thread throughout the request lifecycle.
Storage of Authentication Information:
Holds the Authentication object representing the currently authenticated user.
Thread-Local Storage:
Uses a ThreadLocal to store the security context, ensuring that security information is isolated to the current thread and not shared across different threads.
Methods in SecurityContextHolder:
getContext(): Retrieves the current security context associated with the executing thread.
setContext(): Sets the security context for the executing thread.
clearContext(): Clears the security context associated with the current thread.
DispatcherServlet
The DispatcherServlet in the Spring Framework is the central servlet that manages the entire request-handling workflow in a Spring MVC (Model-View-Controller) web application. It acts as the front controller, responsible for intercepting incoming HTTP requests and dispatching them to the appropriate handlers for processing.
When we make a request at an endpoint (say /helloworld), how the front controller (DispatcherServlet) would handle it?
DispatcherServlet creates an IOC container. The IOC container is a central component of the Spring Framework that manages the creation and dependencies of beans. The DispatcherServlet creates a WebApplicationContext, which is a specialized IOC container that is used for web applications. The WebApplicationContext is configured by the DispatcherServlet based on the configuration files.
The IOC container creates an instance of the controller beans. The DispatcherServlet will use the IOC container to lookup the controller bean and to delegate requests to it.
When we are not using Spring Security, the request is intercepted by the DispatcherServlet.