Spring Security Documentation

repository·main·Indexed 27 days ago

https://github.com/spring-projects/spring-security

A 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.

Tokens
180.5K
Snippets
468
Records
723
Agent score
94%

What's inside Spring Security

  1. Overview of OAuth 2.1 Authorization Server features

    main
    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.
  2. Overview of Spring Security features

    main

    Spring 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.

  3. Understand DaoAuthenticationProvider authentication flow

    main

    The DaoAuthenticationProvider is an implementation of AuthenticationProvider used to authenticate users via a username and password. It relies on two key components:

    1. UserDetailsService: Used to look up the UserDetails associated with a given username.
    2. PasswordEncoder: Used to validate the provided password against the stored password found in the UserDetails.

    Authentication Workflow:

    1. An authentication Filter passes a UsernamePasswordAuthenticationToken to the AuthenticationManager (typically a ProviderManager).
    2. The ProviderManager delegates to the DaoAuthenticationProvider.
    3. DaoAuthenticationProvider retrieves UserDetails from the configured UserDetailsService.
    4. DaoAuthenticationProvider validates the password using the configured PasswordEncoder.
    5. Upon success, a UsernamePasswordAuthenticationToken is returned. This token contains the UserDetails as the principal and includes at least the ROLE_USER authority (note: the source text mentions FACTOR_PASSWORD, but in standard Spring Security context this refers to the granted authorities).
    6. The authentication Filter sets this token in the SecurityContextHolder.
  4. Explore Spring Security Authentication Mechanisms

    main

    Spring 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.
  5. OAuth 2.0 and OpenID Connect Modules

    main

    Spring 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.
  6. Understand CSRF Attacks

    main
    A 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 (like JSESSIONID) with requests to the associated domain, the target server cannot distinguish between a legitimate user action and a forged request from an evil site.
  7. OAuth 2.0 Client Supported Features

    main

    Spring 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):

    • RestClient integration
    • WebClient integration (for Servlet Environments)
  8. Default Runtime Behaviors of Spring Boot + Spring Security

    main

    When 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 user is registered with a randomly generated password logged to the console at startup.
    • Password Storage: Uses BCrypt for 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 Unauthorized for 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 HttpServletRequest authentication methods and publishes authentication success/failure events.
  9. Protect endpoints with OAuth 2.0 Bearer Tokens

    main

    Spring Security allows you to protect your servlet-based endpoints using two types of OAuth 2.0 Bearer Tokens:

    1. JWT (JSON Web Token): A self-contained token format.
    2. 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 BearerTokenAuthenticationEntryPoint sends a WWW-Authenticate: Bearer header to signal that the client should retry the request with a bearer token.

  10. Understand AuthorizationFilter architecture and dispatch types

    main

    The AuthorizationFilter is responsible for request-level authorization. It retrieves the Authentication from the SecurityContextHolder and passes it, along with the HttpServletRequest, to an AuthorizationManager.

    Key behaviors:

    • Filter Order: AuthorizationFilter is 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, and INCLUDE. For example, Spring MVC FORWARDs to a view resolver, and Spring Boot dispatches to an ERROR dispatch when exceptions occur. You may need to permit FORWARD or ERROR dispatches specifically to allow these processes to complete.
  11. How HTTP Basic Authentication works in Spring Security

    main

    HTTP Basic Authentication follows this lifecycle within the Spring Security filter chain:

    1. Unauthorized Request: An unauthenticated user requests a protected resource. The AuthorizationFilter throws an AccessDeniedException.
    2. Triggering Authentication: The ExceptionTranslationFilter catches the exception and invokes the configured AuthenticationEntryPoint (typically BasicAuthenticationEntryPoint), which sends a WWW-Authenticate header to the client.
    3. Credential Submission: The client retries the request with a Authorization header containing credentials. The BasicAuthenticationFilter extracts the username and password to create a UsernamePasswordAuthenticationToken.
    4. Authentication Process: The token is passed to the AuthenticationManager.
      • On Failure: The SecurityContextHolder is cleared, RememberMeServices.loginFail is called (if configured), and the AuthenticationEntryPoint is invoked again to re-send the WWW-Authenticate header.
      • On Success: The Authentication object is stored in the SecurityContextHolder, RememberMeServices.loginSuccess is called (if configured), and the filter chain continues.
  12. Default Security HTTP Response Headers in Spring Security

    main

    By 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-revalidate
    • Pragma: no-cache
    • Expires: 0
    • X-Content-Type-Options: nosniff
    • Strict-Transport-Security: max-age=31536000 ; includeSubDomains (Note: Added only on HTTPS requests)
    • X-Frame-Options: DENY
    • X-XSS-Protection: 0

    You can remove, modify, or add headers to these defaults in your specific application configuration.