Spring Security Documentation
repository·main·Indexed 27 days ago
https://github.com/spring-projects/spring-securityA comprehensive security framework for the Spring IO Platform designed to handle authentication, authorization, and protection against common exploits. It provides built-in defenses against Cross-Site Request Forgery (CSRF) using the Synchronizer Token Pattern and SameSite attributes, as well as default security HTTP response headers to mitigate clickjacking, XSS, and content sniffing.
What's inside Spring Security
- Spring Security provides an implementation of the OAuth 2.1 Authorization Framework and OpenID Connect 1.0 specifications. It serves as a secure, lightweight, and customizable foundation for building Identity Providers (IdPs) and OAuth 2.1 Authorization Servers. It is particularly useful when you require full control over configuration, prefer a lightweight alternative to commercial products, or want to leverage the familiar Spring programming model for quick development.
Overview of Spring Security features
mainSpring Security is a comprehensive framework that provides core security capabilities including:
- Authentication: Verifying the identity of users or principals.
- Authorization: Controlling access to resources based on identity and permissions.
- Exploit Protection: Providing built-in defenses against common web-based security exploits.
Additionally, Spring Security offers integration with various other libraries to simplify its implementation within your application stack.
Understand DaoAuthenticationProvider authentication flow
mainThe
DaoAuthenticationProvideris an implementation ofAuthenticationProviderused to authenticate users via a username and password. It relies on two key components:UserDetailsService: Used to look up theUserDetailsassociated with a given username.PasswordEncoder: Used to validate the provided password against the stored password found in theUserDetails.
Authentication Workflow:
- An authentication
Filterpasses aUsernamePasswordAuthenticationTokento theAuthenticationManager(typically aProviderManager). - The
ProviderManagerdelegates to theDaoAuthenticationProvider. DaoAuthenticationProviderretrievesUserDetailsfrom the configuredUserDetailsService.DaoAuthenticationProvidervalidates the password using the configuredPasswordEncoder.- Upon success, a
UsernamePasswordAuthenticationTokenis returned. This token contains theUserDetailsas the principal and includes at least theROLE_USERauthority (note: the source text mentionsFACTOR_PASSWORD, but in standard Spring Security context this refers to the granted authorities). - The authentication
Filtersets this token in theSecurityContextHolder.
Explore Spring Security Authentication Mechanisms
mainSpring Security provides several concrete mechanisms for authenticating users in a Servlet-based application. Depending on your requirements, you can implement one of the following flows:
- Username and Password: Standard authentication using credentials.
- OAuth 2.0 Login: Supports OpenID Connect and non-standard OAuth 2.0 providers (e.g., GitHub).
- SAML 2.0 Login: Support for SAML 2.0 based identity providers.
- Central Authentication Server (CAS): Integration with CAS servers.
- Remember Me: Allows users to remain authenticated after their session expires.
- JAAS Authentication: Authentication via the Java Authentication and Authorization Service.
- Pre-Authentication Scenarios: Integration with external mechanisms like SiteMinder or Java EE security, while using Spring Security for authorization and exploit protection.
- X509 Authentication: Authentication using X.509 certificates.
OAuth 2.0 and OpenID Connect Modules
mainSpring Security provides several modules for OAuth 2.0 and OpenID Connect Core 1.0 support:
- OAuth 2.0 Core (
spring-security-oauth2-core): Contains core classes and interfaces for the OAuth 2.0 Authorization Framework and OpenID Connect Core 1.0. Required by clients, resource servers, and authorization servers. Package:org.springframework.security.oauth2.core. - OAuth 2.0 Client (
spring-security-oauth2-client): Provides client support for OAuth 2.0 and OpenID Connect Core 1.0. Package:org.springframework.security.oauth2.core. - OAuth 2.0 JOSE (
spring-security-oauth2-jose): Supports the JOSE (Javascript Object Signing and Encryption) framework, including JWT, JWS, JWE, and JWK. Packages:org.springframework.security.oauth2.jwt,org.springframework.security.oauth2.jose. - OAuth 2.0 Resource Server (
spring-security-oauth2-resource-server): Used to protect APIs by using OAuth 2.0 Bearer Tokens. Package:org.springframework.security.oauth2.server.resource.
- OAuth 2.0 Core (
Understand CSRF Attacks
mainA Cross-Site Request Forgery (CSRF) attack occurs when a malicious website tricks a user's browser into making an unwanted HTTP request to a different website where the user is currently authenticated. Because browsers automatically include cookies (likeJSESSIONID) with requests to the associated domain, the target server cannot distinguish between a legitimate user action and a forged request from an evil site.OAuth 2.0 Client Supported Features
mainSpring Security's OAuth 2.0 Client provides support for the following roles and grants:
Authorization Grant support:
- Authorization Code
- Refresh Token
- Client Credentials
- JWT Bearer
- Token Exchange
Client Authentication support:
- JWT Bearer
HTTP Client support (for requesting protected resources):
RestClientintegrationWebClientintegration (for Servlet Environments)
Default Runtime Behaviors of Spring Boot + Spring Security
mainWhen using Spring Boot with Spring Security, the following security behaviors are enabled by default:
- Authentication Requirement: All endpoints (including
/error) require an authenticated user. - Default User: A user with the username
useris registered with a randomly generated password logged to the console at startup. - Password Storage: Uses
BCryptfor password encoding. - Login/Logout Flows: Provides built-in form-based login and logout flows.
- Authentication Methods: Supports both form-based login and HTTP Basic authentication.
- Content Negotiation: Redirects web requests to a login page and returns
401 Unauthorizedfor service requests. - Security Headers: Automatically writes several security headers:
Strict-Transport-Security(HSTS)X-Content-Type-Options(to mitigate sniffing)Cache Control(to protect authenticated resources)X-Frame-Options(to mitigate Clickjacking)
- Attack Mitigation: Provides default protection against CSRF and Session Fixation attacks.
- Integration: Integrates with
HttpServletRequestauthentication methods and publishes authentication success/failure events.
- Authentication Requirement: All endpoints (including
Protect endpoints with OAuth 2.0 Bearer Tokens
mainSpring Security allows you to protect your servlet-based endpoints using two types of OAuth 2.0 Bearer Tokens:
- JWT (JSON Web Token): A self-contained token format.
- Opaque Tokens: Tokens that require the resource server to consult an authorization server (like Okta or Ping Identity) to validate them.
When an unauthenticated client attempts to access a protected resource, Spring Security's
BearerTokenAuthenticationEntryPointsends aWWW-Authenticate: Bearerheader to signal that the client should retry the request with a bearer token.Understand AuthorizationFilter architecture and dispatch types
mainThe
AuthorizationFilteris responsible for request-level authorization. It retrieves theAuthenticationfrom theSecurityContextHolderand passes it, along with theHttpServletRequest, to anAuthorizationManager.Key behaviors:
- Filter Order:
AuthorizationFilteris last in the filter chain by default. This ensures authentication filters and exploit protections run before authorization. - All Dispatches are Authorized: The filter runs on every dispatch type, including
REQUEST,FORWARD,ERROR, andINCLUDE. For example, Spring MVCFORWARDs to a view resolver, and Spring Boot dispatches to anERRORdispatch when exceptions occur. You may need to permitFORWARDorERRORdispatches specifically to allow these processes to complete.
- Filter Order:
How HTTP Basic Authentication works in Spring Security
mainHTTP Basic Authentication follows this lifecycle within the Spring Security filter chain:
- Unauthorized Request: An unauthenticated user requests a protected resource. The
AuthorizationFilterthrows anAccessDeniedException. - Triggering Authentication: The
ExceptionTranslationFiltercatches the exception and invokes the configuredAuthenticationEntryPoint(typicallyBasicAuthenticationEntryPoint), which sends aWWW-Authenticateheader to the client. - Credential Submission: The client retries the request with a
Authorizationheader containing credentials. TheBasicAuthenticationFilterextracts the username and password to create aUsernamePasswordAuthenticationToken. - Authentication Process: The token is passed to the
AuthenticationManager.- On Failure: The
SecurityContextHolderis cleared,RememberMeServices.loginFailis called (if configured), and theAuthenticationEntryPointis invoked again to re-send theWWW-Authenticateheader. - On Success: The
Authenticationobject is stored in theSecurityContextHolder,RememberMeServices.loginSuccessis called (if configured), and the filter chain continues.
- On Failure: The
- Unauthorized Request: An unauthenticated user requests a protected resource. The
Default Security HTTP Response Headers in Spring Security
mainBy default, Spring Security includes a set of security-related HTTP response headers to provide secure defaults. These headers protect against common vulnerabilities like clickjacking, XSS, and content sniffing.
Default Headers:
Cache-Control: no-cache, no-store, max-age=0, must-revalidatePragma: no-cacheExpires: 0X-Content-Type-Options: nosniffStrict-Transport-Security: max-age=31536000 ; includeSubDomains(Note: Added only on HTTPS requests)X-Frame-Options: DENYX-XSS-Protection: 0
You can remove, modify, or add headers to these defaults in your specific application configuration.