### Reactive Authorized Client Manager Setup (Kotlin) Source: https://docs.spring.io/spring-security/reference/6.5/reactive/oauth2/client/index.html Kotlin example for setting up a `ReactiveOAuth2AuthorizedClientManager` bean. This includes configuring the `ReactiveOAuth2AuthorizedClientProvider` to support multiple authorization grant types. ```kotlin @Bean fun authorizedClientManager( clientRegistrationRepository: ReactiveClientRegistrationRepository, authorizedClientRepository: ServerOAuth2AuthorizedClientRepository): ReactiveOAuth2AuthorizedClientManager { val authorizedClientProvider: ReactiveOAuth2AuthorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder() .authorizationCode() .refreshToken() .clientCredentials() .password() .build() val authorizedClientManager = DefaultReactiveOAuth2AuthorizedClientManager( clientRegistrationRepository, authorizedClientRepository) authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) return authorizedClientManager } ``` -------------------------------- ### Example Output Source: https://docs.spring.io/spring-security/reference/6.5/servlet/test/method.html Example output string from the getMessage method, showing the authenticated user details. ```text Hello org.springframework.security.authentication.UsernamePasswordAuthenticationToken@ca25360: Principal: org.springframework.security.core.userdetails.User@36ebcb: Username: user; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_USER ``` -------------------------------- ### Example Response for Verification Options Source: https://docs.spring.io/spring-security/reference/6.5/servlet/authentication/passkeys.html Example response containing the necessary options for client-side passkey verification. ```json { "challenge": "cQfdGrj9zDg3zNBkOH3WPL954FTOShVy0-CoNgSewNM", "timeout": 300000, "rpId": "example.localhost", "allowCredentials": [], "userVerification": "preferred", "extensions": {} } ``` -------------------------------- ### Lambda-based Security Configuration Example Source: https://docs.spring.io/spring-security/reference/6.5/api/java/deprecated-list.html Example demonstrating the use of lambda-based configuration for security matchers and authorization, replacing older methods. ```java @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .securityMatchers((matchers) -> matchers .requestMatchers("/api/**") ) .authorizeHttpRequests((authorize) -> authorize .anyRequest().hasRole("USER") ) .httpBasic(Customizer.withDefaults()); return http.build(); } } ``` -------------------------------- ### Example: Using OidcBackChannelServerLogoutHandler Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/config/web/server/ServerHttpSecurity.OidcLogoutSpec.BackChannelLogoutConfigurer.html Example of configuring Back-Channel Logout with a custom OidcBackChannelServerLogoutHandler. This approach does not require special CSRF configuration. ```java http .oidcLogout((oidc) -> oidc .backChannel((backChannel) -> backChannel .logoutHandler(new OidcBackChannelServerLogoutHandler()) ) ); ``` -------------------------------- ### Reactive Authorized Client Manager Setup (Java) Source: https://docs.spring.io/spring-security/reference/6.5/reactive/oauth2/client/index.html Example of registering a `ReactiveOAuth2AuthorizedClientManager` bean in Java. It configures a composite provider supporting authorization code, refresh token, client credentials, and password grant types. ```java @Bean public ReactiveOAuth2AuthorizedClientManager authorizedClientManager( ReactiveClientRegistrationRepository clientRegistrationRepository, ServerOAuth2AuthorizedClientRepository authorizedClientRepository) { ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder() .authorizationCode() .refreshToken() .clientCredentials() .password() .build(); DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager = new DefaultReactiveOAuth2AuthorizedClientManager( clientRegistrationRepository, authorizedClientRepository); authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); return authorizedClientManager; } ``` -------------------------------- ### Kotlin Setup for MockMvc with Spring Security Source: https://docs.spring.io/spring-security/reference/6.5/servlet/test/mockmvc/setup.html This Kotlin example demonstrates applying Spring Security's configuration to MockMvc for testing purposes. It ensures that Spring Security's features are active within the test environment. ```kotlin @ExtendWith(SpringExtension::class) @ContextConfiguration(classes = [SecurityConfig::class]) @WebAppConfiguration class CsrfShowcaseTests { @Autowired private lateinit var context: WebApplicationContext private lateinit var mvc: MockMvc @BeforeEach fun setup() { mvc = MockMvcBuilders .webAppContextSetup(context) .apply(springSecurity()) __**(1)** .build() } // ... ``` -------------------------------- ### Send Username and Password in RSocket Setup Metadata (Java) Source: https://docs.spring.io/spring-security/reference/6.5/reactive/integrations/rsocket.html Connects to an RSocket server, sending username and password credentials in the setup metadata. Requires SimpleAuthenticationEncoder to be configured. ```java MimeType authenticationMimeType = MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString()); UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("user", "password"); Mono requester = RSocketRequester.builder() .setupMetadata(credentials, authenticationMimeType) .rsocketStrategies(strategies.build()) .connectTcp(host, port); ``` -------------------------------- ### Customizing SecurityFilterChain Endpoints in Kotlin Source: https://docs.spring.io/spring-security/reference/6.5/servlet/configuration/kotlin.html This example configures a SecurityFilterChain to secure requests starting with '/secured/**', denies all other requests, and customizes the login and logout page URLs. It requires custom endpoints for GET requests to login and logout. ```kotlin import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.invoke import org.springframework.security.config.annotation.web.invoke.http import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.security.web.SecurityFilterChain import org.springframework.core.annotation.Order @Configuration @EnableWebSecurity class SecuredSecurityConfig { @Bean open fun userDetailsService(): UserDetailsService { // ... } @Bean @Order(1) open fun securedFilterChain(http: HttpSecurity): SecurityFilterChain { http { securityMatcher("/secured/**") authorizeHttpRequests { authorize(anyRequest, authenticated) } formLogin { loginPage = "/secured/login" loginProcessingUrl = "/secured/login" permitAll = true } logout { logoutUrl = "/secured/logout" logoutSuccessUrl = "/secured/login?logout" permitAll = true } } return http.build() } @Bean open fun defaultFilterChain(http: HttpSecurity): SecurityFilterChain { http { authorizeHttpRequests { authorize(anyRequest, denyAll) } } return http.build() } } ``` -------------------------------- ### setupModule Method Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/web/server/jackson2/WebServerJackson2Module.html Configures the provided `SetupContext` with the module's serializers and deserializers. ```APIDOC ## setupModule(SetupContext context) ### Description Configures the `SetupContext` for this module. This method is called by Jackson during module registration to add necessary serializers, deserializers, and other configurations. ### Method `void setupModule(com.fasterxml.jackson.databind.Module.SetupContext context)` ### Overrides `setupModule` in class `com.fasterxml.jackson.databind.module.SimpleModule` ``` -------------------------------- ### Configure SecurityFilterChain with Custom Endpoints Source: https://docs.spring.io/spring-security/reference/6.5/servlet/configuration/java.html This configuration secures requests starting with /secured/**, requires authentication for these requests, and customizes the login and logout URLs. It also denies all other requests. You must provide custom endpoints for GET /secured/login and GET /secured/logout. ```java @Configuration @EnableWebSecurity public class SecuredSecurityConfig { @Bean public UserDetailsService userDetailsService() throws Exception { // ... } @Bean @Order(1) public SecurityFilterChain securedFilterChain(HttpSecurity http) throws Exception { http .securityMatcher("/secured/**") .authorizeHttpRequests(authorize -> authorize .anyRequest().authenticated() ) .formLogin(formLogin -> formLogin .loginPage("/secured/login") .loginProcessingUrl("/secured/login") .permitAll() ) .logout(logout -> logout .logoutUrl("/secured/logout") .logoutSuccessUrl("/secured/login?logout") .permitAll() ) .formLogin(Customizer.withDefaults()); return http.build(); } @Bean public SecurityFilterChain defaultFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(authorize -> authorize .anyRequest().denyAll() ); return http.build(); } } ``` -------------------------------- ### Example: Adding Custom Container Support with TargetVisitor Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/authorization/method/AuthorizationAdvisorProxyFactory.html Shows how to extend the default `TargetVisitor` to add support for custom container types like `Function`. ```java TargetVisitor functions = (factory, target) -> { if (target instanceof Function function) { return (input) -> factory.proxy(function.apply(input)); } return null; }; AuthorizationAdvisorProxyFactory proxyFactory = new AuthorizationAdvisorProxyFactory(); proxyFactory.setTargetVisitor(TargetVisitor.of(functions, TargetVisitor.defaultsSkipValueTypes())); ``` -------------------------------- ### Send Username and Password in RSocket Setup Metadata (Kotlin) Source: https://docs.spring.io/spring-security/reference/6.5/reactive/integrations/rsocket.html Connects to an RSocket server, sending username and password credentials in the setup metadata in Kotlin. Requires SimpleAuthenticationEncoder to be configured. ```kotlin val authenticationMimeType: MimeType = MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.string) val credentials = UsernamePasswordMetadata("user", "password") val requester: Mono = RSocketRequester.builder() .setupMetadata(credentials, authenticationMimeType) .rsocketStrategies(strategies.build()) .connectTcp(host, port) ``` -------------------------------- ### WebJackson2Module setupModule Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/web/jackson2/WebJackson2Module.html Sets up the Jackson module by registering necessary mixins and configurations with the provided SetupContext. ```APIDOC ## setupModule(SetupContext context) ### Description Configures the Jackson ObjectMapper by registering serializers, deserializers, and mixin annotations required for Spring Security web objects. This method is called by Jackson during module registration. ### Method `void setupModule(com.fasterxml.jackson.databind.Module.SetupContext context)` ### Overrides `setupModule` in class `com.fasterxml.jackson.databind.module.SimpleModule` ``` -------------------------------- ### Configure SecurityFilterChain with securityMatcher Source: https://docs.spring.io/spring-security/reference/6.5/servlet/configuration/kotlin.html This example shows how to configure a SecurityFilterChain that only protects requests starting with '/secured/**'. Requests not matching this pattern are not protected by Spring Security. ```kotlin import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.invoke import org.springframework.security.config.annotation.web.invoke.authorizeHttpRequests import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.security.web.SecurityFilterChain @Configuration @EnableWebSecurity class PartialSecurityConfig { @Bean open fun userDetailsService(): UserDetailsService { // ... } @Bean open fun securedFilterChain(http: HttpSecurity): SecurityFilterChain { http { securityMatcher("/secured/**") __**(1)** authorizeHttpRequests { authorize("/secured/user", hasRole("USER")) __**(2)** authorize("/secured/admin", hasRole("ADMIN")) __**(3)** authorize(anyRequest, authenticated) __**(4)** } httpBasic { } formLogin { } } return http.build() } } ``` -------------------------------- ### Create User with Default Password Encoding Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/core/userdetails/User.html Use this method for demos and getting started. It automatically encodes the password using `PasswordEncoderFactories.createDelegatingPasswordEncoder()`. Not recommended for production. ```java UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); // outputs {bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG System.out.println(user.getPassword()); ``` -------------------------------- ### init Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/config/annotation/web/configurers/AbstractAuthenticationFilterConfigurer.html Initializes the security configuration. ```APIDOC ### init public void init(B http) throws Exception Description copied from interface: `SecurityConfigurer` ``` -------------------------------- ### Password Storage Format Example Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/crypto/password/DelegatingPasswordEncoder.html Illustrates the common format for storing encoded passwords, where a prefix identifies the encoding algorithm used. The prefix must start with '{' and end with '}'. ```plaintext {id}encodedPassword ``` ```plaintext {bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG {noop}password {pbkdf2}5d923b44a6d129f3ddf3e3c8d29412723dcbde72445e8ef6bf3b508fbf17fa4ed4d6b99ca763d8dc {scrypt}$e0801$8bWJaSu2IKSn9Z9kM+TPXfOc/9bdYSrN1oD9qfVThWEwdRTnO7re7Ei+fUZRJ68k9lTyuTeUp4of4g24hHnazw==$OAOec05+bXxvuu/1qZ6NUR+xQYvYv7BeL1QxwRpY5Pc= {sha256}97cde38028ad898ebc02e690819fa220e88c62e0699403e94fff291cfffaf8410849f27605abcbc0 ``` -------------------------------- ### X509Configurer Constructor Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/config/annotation/web/configurers/X509Configurer.html Creates a new instance of X509Configurer. ```APIDOC ## X509Configurer Constructor ### Description Creates a new instance of the `X509Configurer` class. ### Method `public X509Configurer()` ### Returns A new instance of `X509Configurer`. ``` -------------------------------- ### XML Configuration with {noop} Password Encoding Source: https://docs.spring.io/spring-security/reference/6.5/servlet/authentication/passwords/in-memory.html Configure an InMemoryUserDetailsManager using XML with `{noop}` prefix for passwords. This indicates no encoding should be used and is suitable for demos or getting started. ```xml ``` -------------------------------- ### Spring Boot OAuth2 Custom Provider Configuration for Okta Source: https://docs.spring.io/spring-security/reference/6.5/reactive/oauth2/login/core.html Example of configuring custom protocol endpoint URIs for an Okta OAuth2 provider, essential for multi-tenant setups. ```yaml spring: security: oauth2: client: registration: okta: client-id: okta-client-id client-secret: okta-client-secret provider: okta: authorization-uri: https://your-subdomain.oktapreview.com/oauth2/v1/authorize token-uri: https://your-subdomain.oktapreview.com/oauth2/v1/token user-info-uri: https://your-subdomain.oktapreview.com/oauth2/v1/userinfo user-name-attribute: sub jwk-set-uri: https://your-subdomain.oktapreview.com/oauth2/v1/keys ``` -------------------------------- ### void commence(HttpServletRequest, HttpServletResponse, AuthenticationException) Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/web/authentication/www/BasicAuthenticationEntryPoint.html Commences the BASIC authentication scheme by modifying response headers to prompt the user for credentials. ```APIDOC ## void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) ### Description Commences an authentication scheme. This method is called by the ExceptionTranslationFilter to indicate to the browser that credentials are required, typically resulting in a 401 Unauthorized status. ### Parameters #### Path Parameters - **request** (HttpServletRequest) - Required - The request that resulted in an AuthenticationException. - **response** (HttpServletResponse) - Required - The response used to initiate the authentication process. - **authException** (AuthenticationException) - Required - The exception that caused the invocation. ### Response - **Status** (401) - Sends a WWW-Authenticate header to the client to trigger the browser login prompt. ``` -------------------------------- ### Configure SecurityFilterChain with securityMatcher Source: https://docs.spring.io/spring-security/reference/6.5/servlet/configuration/java.html Use `securityMatcher` to specify which requests a `SecurityFilterChain` should protect. Requests not matching this pattern will not be processed by this filter chain. This example protects only requests starting with `/secured/`. ```java @Configuration @EnableWebSecurity public class PartialSecurityConfig { @Bean public UserDetailsService userDetailsService() throws Exception { // ... } @Bean public SecurityFilterChain securedFilterChain(HttpSecurity http) throws Exception { http .securityMatcher("/secured/**") .authorizeHttpRequests(authorize -> authorize .requestMatchers("/secured/user").hasRole("USER") .requestMatchers("/secured/admin").hasRole("ADMIN") .anyRequest().authenticated() ) .httpBasic(Customizer.withDefaults()) .formLogin(Customizer.withDefaults()); return http.build(); } } ``` -------------------------------- ### Response for Registration Options Source: https://docs.spring.io/spring-security/reference/6.5/servlet/authentication/passkeys.html Example response containing the necessary options for client-side passkey registration. ```json { "rp": { "name": "SimpleWebAuthn Example", "id": "example.localhost" }, "user": { "name": "user@example.localhost", "id": "oWJtkJ6vJ_m5b84LB4_K7QKTCTEwLIjCh4tFMCGHO4w", "displayName": "user@example.localhost" }, "challenge": "q7lCdd3SVQxdC-v8pnRAGEn1B2M-t7ZECWPwCAmhWvc", "pubKeyCredParams": [ { "type": "public-key", "alg": -8 }, { "type": "public-key", "alg": -7 }, { "type": "public-key", "alg": -257 } ], "timeout": 300000, "excludeCredentials": [], "authenticatorSelection": { "residentKey": "required", "userVerification": "preferred" }, "attestation": "none", "extensions": { "credProps": true } } ``` -------------------------------- ### Making Downstream Request with Propagated Token (Java) Source: https://docs.spring.io/spring-security/reference/6.5/reactive/oauth2/resource-server/bearer-tokens.html Example of making a GET request using a WebClient configured for bearer token propagation. The token will be automatically added to the Authorization header. ```java this.rest.get() .uri("https://other-service.example.com/endpoint") .retrieve() .bodyToMono(String.class) ``` -------------------------------- ### Making Downstream Request with Propagated Token (Kotlin) Source: https://docs.spring.io/spring-security/reference/6.5/reactive/oauth2/resource-server/bearer-tokens.html Example of making a GET request using a WebClient configured for bearer token propagation in Kotlin. The token will be automatically added to the Authorization header. ```kotlin this.rest.get() .uri("https://other-service.example.com/endpoint") .retrieve() .bodyToMono() ``` -------------------------------- ### Manually Construct AuthorizationProxyFactory (Kotlin) Source: https://docs.spring.io/spring-security/reference/6.5/servlet/authorization/method-security.html This Kotlin example demonstrates manual construction of an AuthorizationProxyFactory, including customization with TargetVisitor.defaultsSkipValueTypes(), and then proxies a User object. ```kotlin import org.springframework.security.authorization.method.AuthorizationAdvisorProxyFactory.TargetVisitor; import org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor.preAuthorize // ... val proxyFactory: AuthorizationProxyFactory = AuthorizationProxyFactory(preAuthorize()) // and if needing to skip value types proxyFactory.setTargetVisitor(TargetVisitor.defaultsSkipValueTypes()) ``` ```kotlin @Test fun getEmailWhenProxiedThenAuthorizes() { val proxyFactory: AuthorizationProxyFactory = AuthorizationAdvisorProxyFactory.withDefaults() val user: User = User("name", "email") assertThat(user.getEmail()).isNotNull() val securedUser: User = proxyFactory.proxy(user) assertThatExceptionOfType(AccessDeniedException::class.java).isThrownBy(securedUser::getEmail) } ``` -------------------------------- ### Java Code to Generate DPoP Proof JWT Source: https://docs.spring.io/spring-security/reference/6.5/servlet/oauth2/resource-server/dpop-tokens.html Example Java code demonstrating how to generate a DPoP Proof JWT using Nimbus JOSE+JWT library. Requires RSAKey and JWKSource setup. ```Java RSAKey rsaKey = ... JWKSource jwkSource = (jwkSelector, securityContext) -> jwkSelector .select(new JWKSet(rsaKey)); NimbusJwtEncoder jwtEncoder = new NimbusJwtEncoder(jwkSource); JwsHeader jwsHeader = JwsHeader.with(SignatureAlgorithm.RS256) .type("dpop+jwt") .jwk(rsaKey.toPublicJWK().toJSONObject()) .build(); JwtClaimsSet claims = JwtClaimsSet.builder() .issuedAt(Instant.now()) .claim("htm", "POST") .claim("htu", "https://server.example.com/oauth2/token") .id(UUID.randomUUID().toString()) .build(); Jwt dPoPProof = jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, claims)); ``` -------------------------------- ### with(C configurer, Customizer customizer) Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/config/annotation/AbstractConfiguredSecurityBuilder.html Applies a `SecurityConfigurerAdapter` to this `SecurityBuilder` and invokes `SecurityConfigurerAdapter.setBuilder(SecurityBuilder)`, followed by applying the provided customizer. ```APIDOC ## Method: with ### Description Applies a `SecurityConfigurerAdapter` to this `SecurityBuilder` and invokes `SecurityConfigurerAdapter.setBuilder(SecurityBuilder)`. ### Parameters * `configurer` (C extends SecurityConfigurerAdapter) - * `customizer` (Customizer) - ### Returns (B) - the `SecurityBuilder` for further customizations ### Throws * `Exception` ### Since 6.2 ``` -------------------------------- ### Migrating Request Matchers with Lambda Configuration Source: https://docs.spring.io/spring-security/reference/6.5/api/java/deprecated-list.html Use lambda-based configuration for defining request matchers instead of the deprecated `and()` method. This example shows how to match requests starting with '/api/**' and authorize them for users with the 'USER' role. ```java @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .securityMatchers((matchers) -> matchers .requestMatchers("/api/**") ) .authorizeHttpRequests((authorize) -> authorize .anyRequest().hasRole("USER") ) .httpBasic(Customizer.withDefaults()); return http.build(); } } ``` -------------------------------- ### HTTP Basic Authentication Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/config/annotation/web/builders/HttpSecurity.html This example demonstrates how to configure HTTP Basic authentication using the recommended `httpBasic(Customizer)` method. This allows for more flexible customization of the HTTP Basic authentication process. ```APIDOC ## HTTP Basic Authentication ### Description Configures HTTP Basic authentication for an application using a `Customizer` for more options. ### Method `httpBasic(Customizer> httpBasicCustomizer)` ### Endpoint N/A (Applies globally) ### Parameters - **httpBasicCustomizer** (Customizer>) - Required - The `Customizer` to provide more options for the `HttpBasicConfigurer`. ### Request Body N/A ### Request Example ```java @Configuration @EnableWebSecurity public class HttpBasicSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/**").hasRole("USER") ) .httpBasic(withDefaults()); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } } ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Initialize OpenSAML with Defaults Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/saml2/core/OpenSamlInitializationService.html Use this method to prepare OpenSAML for use with reasonable defaults. It is idempotent and safe to call multiple times, though initialization only occurs once. ```java static { OpenSamlInitializationService.requireInitialize((registry) -> { registry.setParserPool(...); registry.getBuilderFactory().registerBuilder(...); }); } ``` -------------------------------- ### SCryptPasswordEncoder Example (Java) Source: https://docs.spring.io/spring-security/reference/6.5/features/authentication/password-storage.html Demonstrates creating a default SCryptPasswordEncoder and using it to encode and match a password. ```java // Create an encoder with all the defaults SCryptPasswordEncoder encoder = SCryptPasswordEncoder.defaultsForSpringSecurity_v5_8(); String result = encoder.encode("myPassword"); assertTrue(encoder.matches("myPassword", result)); ``` -------------------------------- ### Custom SAML 2.0 Login Configuration (Kotlin) Source: https://docs.spring.io/spring-security/reference/6.5/servlet/saml2/login/overview.html Custom SecurityFilterChain configuration to override Spring Boot's default. This example restricts access to URLs starting with /messages/** to users with ROLE_USER, while all other requests require authentication. ```kotlin @Configuration @EnableWebSecurity class MyCustomSecurityConfiguration { @Bean open fun filterChain(http: HttpSecurity): SecurityFilterChain { http { authorizeRequests { authorize("/messages/**", hasAuthority("ROLE_USER")) authorize(anyRequest, authenticated) } saml2Login { } } return http.build() } } ``` -------------------------------- ### Custom SAML 2.0 Login Configuration (Java) Source: https://docs.spring.io/spring-security/reference/6.5/servlet/saml2/login/overview.html Custom SecurityFilterChain configuration to override Spring Boot's default. This example restricts access to URLs starting with /messages/** to users with ROLE_USER, while all other requests require authentication. ```java @Configuration @EnableWebSecurity public class MyCustomSecurityConfiguration { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(authorize -> authorize .requestMatchers("/messages/**").hasAuthority("ROLE_USER") .anyRequest().authenticated() ) .saml2Login(withDefaults()); return http.build(); } } ``` -------------------------------- ### Spring Security Setup Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurers.html Sets up Spring Security's `WebTestClient` test support. ```APIDOC ## springSecurity ### Description Sets up Spring Security's `WebTestClient` test support. ### Method `static org.springframework.test.web.reactive.server.MockServerConfigurer springSecurity()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Kotlin Configuration for Custom Authentication Converter Source: https://docs.spring.io/spring-security/reference/6.5/servlet/saml2/login/authentication.html Configure a custom SAML2 authentication converter in Kotlin. This example shows how to integrate a custom converter for SAML assertion to Authentication object transformation in a Kotlin Spring Security setup. ```kotlin @Configuration @EnableWebSecurity open class SecurityConfig { @Autowired var authenticationConverter: Converter? = null @Bean open fun filterChain(http: HttpSecurity): SecurityFilterChain { val authenticationProvider = OpenSaml5AuthenticationProvider() authenticationProvider.setResponseAuthenticationConverter(this.authenticationConverter) http { authorizeRequests { authorize(anyRequest, authenticated) } saml2Login { authenticationManager = ProviderManager(authenticationProvider) } } return http.build() } } ``` -------------------------------- ### Pbkdf2PasswordEncoder Example (Java) Source: https://docs.spring.io/spring-security/reference/6.5/features/authentication/password-storage.html Demonstrates creating a default Pbkdf2PasswordEncoder and using it to encode and match a password. ```java // Create an encoder with all the defaults Pbkdf2PasswordEncoder encoder = Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8(); String result = encoder.encode("myPassword"); assertTrue(encoder.matches("myPassword", result)); ``` -------------------------------- ### RSocket Authorization DSL Configuration (Java) Source: https://docs.spring.io/spring-security/reference/6.5/reactive/integrations/rsocket.html Configure RSocket payload authorization rules using the Java DSL. This example demonstrates setting up authorization for setup connections, specific routes, custom matchers, routes with variables, and default rules for authenticated andpermitAll requests. ```java rsocket .authorizePayload(authz -> authz .setup().hasRole("SETUP") __**(1)** .route("fetch.profile.me").authenticated() __**(2)** .matcher(payloadExchange -> isMatch(payloadExchange)) __**(3)** .hasRole("CUSTOM") .route("fetch.profile.{username}") __**(4)** .access((authentication, context) -> checkFriends(authentication, context)) .anyRequest().authenticated() __**(5)** .anyExchange().permitAll() __**(6)** ); ``` -------------------------------- ### SCryptPasswordEncoder Example (Kotlin) Source: https://docs.spring.io/spring-security/reference/6.5/features/authentication/password-storage.html Demonstrates creating a default SCryptPasswordEncoder and using it to encode and match a password in Kotlin. ```kotlin // Create an encoder with all the defaults val encoder = SCryptPasswordEncoder.defaultsForSpringSecurity_v5_8() val result: String = encoder.encode("myPassword") assertTrue(encoder.matches("myPassword", result)) ``` -------------------------------- ### RSocket Authorization DSL Configuration (Kotlin) Source: https://docs.spring.io/spring-security/reference/6.5/reactive/integrations/rsocket.html Configure RSocket payload authorization rules using the Kotlin DSL. This example mirrors the Java configuration, showing how to set up authorization for setup connections, specific routes, custom matchers, routes with variables, and default rules for authenticated and permitAll requests. ```kotlin rsocket .authorizePayload { authz -> authz .setup().hasRole("SETUP") __**(1)** .route("fetch.profile.me").authenticated() __**(2)** .matcher { payloadExchange -> isMatch(payloadExchange) } __**(3)** .hasRole("CUSTOM") .route("fetch.profile.{username}") __**(4)** .access { authentication, context -> checkFriends(authentication, context) } .anyRequest().authenticated() __**(5)** .anyExchange().permitAll() } __**(6)** ``` -------------------------------- ### start Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/ldap/server/ApacheDSContainer.html Starts the embedded LDAP server. This method is deprecated. ```APIDOC ## start ### Description Starts the embedded LDAP server. This method is part of the `Lifecycle` interface and is deprecated. ### Signature `public void start()` ### Implements `org.springframework.context.Lifecycle.start` ``` -------------------------------- ### Method: commence Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/oauth2/server/resource/web/server/BearerTokenServerAuthenticationEntryPoint.html Initiates the authentication flow for a protected resource request. ```APIDOC ## commence ### Description Initiates the authentication flow for a protected resource request, setting the appropriate HTTP status code and WWW-Authenticate header. ### Parameters #### Request Body - **exchange** (ServerWebExchange) - Required - The current server web exchange. - **authException** (AuthenticationException) - Required - The authentication exception that triggered the entry point. ### Response #### Success Response (200) - **Mono** - Returns a Mono indicating when the authentication request is complete. ``` -------------------------------- ### JWT Scope Example Source: https://docs.spring.io/spring-security/reference/6.5/reactive/oauth2/resource-server/jwt.html Example of a JWT containing 'scope' attribute. ```json { ..., "scope" : "messages contacts" } ``` -------------------------------- ### Constructor Details Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/util/SimpleMethodInvocation.html Detailed explanations for the constructors of SimpleMethodInvocation. ```APIDOC ## Constructor Details ### SimpleMethodInvocation public SimpleMethodInvocation(Object targetObject, Method method, Object... arguments) ### SimpleMethodInvocation public SimpleMethodInvocation() ``` -------------------------------- ### Example Usage Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/oauth2/client/web/method/annotation/OAuth2AuthorizedClientArgumentResolver.html Example of how to use the OAuth2AuthorizedClientArgumentResolver in a Spring MVC controller. ```APIDOC ```java @Controller public class MyController { @GetMapping("/authorized-client") public String authorizedClient(@RegisteredOAuth2AuthorizedClient("login-client") OAuth2AuthorizedClient authorizedClient) { // do something with authorizedClient return "authorizedClientInfo"; } } ``` ``` -------------------------------- ### Java Configuration for Username/Password Authentication Source: https://docs.spring.io/spring-security/reference/6.5/servlet/authentication/passwords/index.html Configure basic authentication with form login and HTTP Basic using Java. This example sets up an in-memory UserDetailsService. ```java @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests((authorize) -> authorize .anyRequest().authenticated() ) .httpBasic(Customizer.withDefaults()) .formLogin(Customizer.withDefaults()); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails userDetails = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(userDetails); } } ``` -------------------------------- ### Example Clear-Site-Data Header Source: https://docs.spring.io/spring-security/reference/6.5/reactive/exploits/headers.html An example of a Clear-Site-Data header, specifying that 'cache' and 'cookies' should be cleared. ```plaintext Clear-Site-Data: "cache", "cookies" ``` -------------------------------- ### with Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/config/annotation/AbstractConfiguredSecurityBuilder.html Applies a SecurityConfigurerAdapter and invokes SecurityConfigurerAdapter.setBuilder. ```APIDOC ## `with` ### Description Applies a `SecurityConfigurerAdapter` to this `SecurityBuilder` and invokes `SecurityConfigurerAdapter.setBuilder(SecurityBuilder)`. ### Method `with` ### Type Parameters `>` ### Parameters * `configurer` (C) - The `SecurityConfigurerAdapter` to apply. * `customizer` (Customizer) - A `Customizer` to configure the `SecurityConfigurerAdapter`. ``` -------------------------------- ### Constructor: LoginUrlAuthenticationEntryPoint Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPoint.html Initializes the entry point with a specific login form URL. ```APIDOC ## Constructor LoginUrlAuthenticationEntryPoint ### Description Initializes the LoginUrlAuthenticationEntryPoint with the specified login form URL. ### Parameters #### Request Body - **loginFormUrl** (String) - Required - URL where the login page can be found. Should be relative to the web-app context path or an absolute URL. ``` -------------------------------- ### Getting the UserDetailsService Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/config/annotation/authentication/configurers/provisioning/JdbcUserDetailsManagerConfigurer.html Gets the UserDetailsService that is used with the DaoAuthenticationProvider. Overrides the getUserDetailsService method from AbstractDaoAuthenticationConfigurer. ```java public JdbcUserDetailsManager getUserDetailsService() ``` -------------------------------- ### Configure One-Time Token Login Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/config/annotation/web/builders/HttpSecurity.html Example configuration for enabling One-Time Token Login support. This requires a custom `OneTimeTokenGenerationSuccessHandler` implementation. ```java @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests((authorize) -> authorize .anyRequest().authenticated() ) .oneTimeTokenLogin(Customizer.withDefaults()); return http.build(); } @Bean public OneTimeTokenGenerationSuccessHandler oneTimeTokenGenerationSuccessHandler() { return new MyMagicLinkOneTimeTokenGenerationSuccessHandler(); } } ``` -------------------------------- ### Get MethodSecurityExpressionHandler Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfiguration.html Gets the MethodSecurityExpressionHandler or creates it using expressionHandler. Returns a non-null MethodSecurityExpressionHandler. ```java protected final MethodSecurityExpressionHandler getExpressionHandler() Deprecated. Gets the `MethodSecurityExpressionHandler` or creates it using `expressionHandler`. Returns: a non `null` `MethodSecurityExpressionHandler` ``` -------------------------------- ### init Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/config/annotation/web/configurers/JeeConfigurer.html Populates a PreAuthenticatedAuthenticationProvider into HttpSecurity.authenticationProvider and a Http403ForbiddenEntryPoint into HttpSecurityBuilder.setSharedObject. ```APIDOC ## init ### Description Populates a `PreAuthenticatedAuthenticationProvider` into `HttpSecurity.authenticationProvider(org.springframework.security.authentication.AuthenticationProvider)` and a `Http403ForbiddenEntryPoint` into `HttpSecurityBuilder.setSharedObject(Class, Object)`. ### Method public void init(H http) ### Overrides `init` in class `SecurityConfigurerAdapter>` ### See Also * `SecurityConfigurerAdapter.init(org.springframework.security.config.annotation.SecurityBuilder)` ``` -------------------------------- ### Custom Security Header Example Source: https://docs.spring.io/spring-security/reference/6.5/servlet/exploits/headers.html Example of a custom security header. This can be used for non-standard security headers. ```text X-Custom-Security-Header: header-value ``` -------------------------------- ### beforeInit Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/config/annotation/AbstractConfiguredSecurityBuilder.html Invoked prior to invoking each SecurityConfigurer.init(SecurityBuilder) method. ```APIDOC ## `beforeInit` ### Description Invoked prior to invoking each `SecurityConfigurer.init(SecurityBuilder)` method. This method can be overridden by subclasses to perform actions before initialization. ### Method `protected void beforeInit()` ``` -------------------------------- ### beforeInit Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/config/annotation/AbstractConfiguredSecurityBuilder.html Invoked prior to invoking each SecurityConfigurer.init(SecurityBuilder) method. ```APIDOC ## beforeInit ### Description Invoked prior to invoking each `SecurityConfigurer.init(SecurityBuilder)` method. Subclasses may override this method to hook into the lifecycle without using a `SecurityConfigurer`. ### Throws - **Exception** ``` -------------------------------- ### Configure SwitchUserWebFilter Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/web/server/authentication/SwitchUserWebFilter.html Example of how to configure the SwitchUserWebFilter and add it to the security filter chain. Ensure it is placed after AUTHORIZATION. ```java SwitchUserWebFilter filter = new SwitchUserWebFilter(userDetailsService, loginSuccessHandler, failureHandler); http.addFilterAfter(filter, SecurityWebFiltersOrder.AUTHORIZATION); ``` -------------------------------- ### HTTP Request Example Source: https://docs.spring.io/spring-security/reference/6.5/reactive/integrations/observability.html Example of an HTTP request made to the Spring Boot application with basic authentication. ```shell ?> http -a user:password :8080 ``` -------------------------------- ### WebAuthn Registration Request Example Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/web/webauthn/registration/WebAuthnRegistrationFilter.html An example of a PublicKeyCredential request body that the WebAuthnRegistrationFilter can parse and authenticate. ```json { "publicKey": { "credential": { "id": "dYF7EGnRFFIXkpXi9XU2wg", "rawId": "dYF7EGnRFFIXkpXi9XU2wg", "response": { "attestationObject": "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YViUy9GqwTRaMpzVDbXq1dyEAXVOxrou08k22ggRC45MKNhdAAAAALraVWanqkAfvZZFYZpVEg0AEHWBexBp0RRSF5KV4vV1NsKlAQIDJiABIVggQjmrekPGzyqtoKK9HPUH-8Z2FLpoqkklFpFPQVICQ3IiWCD6I9Jvmor685fOZOyGXqUd87tXfvJk8rxj9OhuZvUALA", "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmdlIjoiSl9RTi10SFJYRWVKYjlNcUNrWmFPLUdOVmlibXpGVGVWMk43Z0ptQUdrQSIsIm9yaWdpbiI6Imh0dHBzOi8vZXhhbXBsZS5sb2NhbGhvc3Q6ODQ0MyIsImNyb3NzT3JpZ2luIjpmYWxzZX0", "transports": [ "internal", "hybrid" ] }, "type": "public-key", "clientExtensionResults": {}, "authenticatorAttachment": "platform" }, "label": "1password" } } ``` -------------------------------- ### Pbkdf2PasswordEncoder Example (Kotlin) Source: https://docs.spring.io/spring-security/reference/6.5/features/authentication/password-storage.html Demonstrates creating a default Pbkdf2PasswordEncoder and using it to encode and match a password in Kotlin. ```kotlin // Create an encoder with all the defaults val encoder = Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8() val result: String = encoder.encode("myPassword") assertTrue(encoder.matches("myPassword", result)) ``` -------------------------------- ### HPKP Header Example with Pins Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/web/header/writers/HpkpHeaderWriter.html Example of a Public-Key-Pins header with a short max-age and two SHA256 pins. ```http Public-Key-Pins: max-age=3000; pin-sha256="d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM="; pin-sha256="E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=" ``` -------------------------------- ### XML Configuration for Username/Password Authentication Source: https://docs.spring.io/spring-security/reference/6.5/servlet/authentication/passwords/index.html Configure basic authentication with form login and HTTP Basic using XML. This example sets up an in-memory user. ```xml ``` -------------------------------- ### Example Transfer Form HTML Source: https://docs.spring.io/spring-security/reference/6.5/features/exploits/csrf.html An example HTML form used for transferring money on a bank's website. ```html
``` -------------------------------- ### AbstractSecurityWebApplicationInitializer Constructors Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/web/context/AbstractSecurityWebApplicationInitializer.html Provides details on how to instantiate AbstractSecurityWebApplicationInitializer. ```APIDOC ## Constructors ### `protected AbstractSecurityWebApplicationInitializer()` Creates a new instance that assumes the Spring Security configuration is loaded by some other means than this class. ### `protected AbstractSecurityWebApplicationInitializer(Class... configurationClasses)` Creates a new instance that will instantiate the `ContextLoaderListener` with the specified classes. ``` -------------------------------- ### Allow Only GET and POST HTTP Methods (Kotlin) Source: https://docs.spring.io/spring-security/reference/6.5/reactive/exploits/firewall.html Configures the StrictServerWebExchangeFirewall to only permit GET and POST HTTP methods, enhancing security by preventing methods like PUT, DELETE, etc. Use this when your application only needs to handle GET and POST requests. ```kotlin @Bean fun httpFirewall(): StrictServerWebExchangeFirewall { val firewall = StrictServerWebExchangeFirewall() firewall.setAllowedHttpMethods(listOf("GET", "POST")) return firewall } ``` -------------------------------- ### Kotlin Configuration for Username/Password Authentication Source: https://docs.spring.io/spring-security/reference/6.5/servlet/authentication/passwords/index.html Configure basic authentication with form login and HTTP Basic using Kotlin. This example sets up an in-memory UserDetailsService. ```kotlin import org.springframework.security.config.annotation.web.invoke @Configuration @EnableWebSecurity class SecurityConfig { @Bean fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { http { authorizeHttpRequests { authorize(anyRequest, authenticated) } formLogin { } httpBasic { } } return http.build() } @Bean fun userDetailsService(): UserDetailsService { val user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build() return InMemoryUserDetailsManager(user) } } ``` -------------------------------- ### Allow Only GET and POST HTTP Methods (Java) Source: https://docs.spring.io/spring-security/reference/6.5/reactive/exploits/firewall.html Configures the StrictServerWebExchangeFirewall to only permit GET and POST HTTP methods, enhancing security by preventing methods like PUT, DELETE, etc. Use this when your application only needs to handle GET and POST requests. ```java @Bean public StrictServerWebExchangeFirewall httpFirewall() { StrictServerWebExchangeFirewall firewall = new StrictServerWebExchangeFirewall(); firewall.setAllowedHttpMethods(Arrays.asList("GET", "POST")); return firewall; } ``` -------------------------------- ### Constructor Source: https://docs.spring.io/spring-security/reference/6.5/api/java/org/springframework/security/ldap/userdetails/LdapUserDetailsManager.html Initializes a new instance of the LdapUserDetailsManager class. ```APIDOC ## Constructor LdapUserDetailsManager ### Description Initializes a new instance of the LdapUserDetailsManager class with the provided ContextSource. ### Parameters * **contextSource** (org.springframework.ldap.core.ContextSource) - The LDAP context source to use for operations. ``` -------------------------------- ### Kotlin Method Security Example Source: https://docs.spring.io/spring-security/reference/6.5/servlet/authorization/method-security.html Example of a Kotlin service class with @PreAuthorize and @PostAuthorize annotations to control method access. ```kotlin @Service open class MyCustomerService { @PreAuthorize("hasAuthority('permission:read')") @PostAuthorize("returnObject.owner == authentication.name") fun readCustomer(id: String): Customer { ... } } ```