### Custom Opaque Token Configuration Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/oauth2/resource-server/opaque-token.adoc Example of starting a custom configuration class for Opaque Token authentication. ```java import static org.springframework.security.oauth2.core.authorization.OAuth2AuthorizationManagers.hasScope; @Configuration ``` -------------------------------- ### Build and Install Artifacts Source: https://github.com/spring-projects/spring-security/blob/main/README.adoc Commands for building the project, running tests, and installing artifacts to the local Maven repository. ```bash ./gradlew publishToMavenLocal ``` ```bash ./gradlew build ``` -------------------------------- ### JSON Serialization Examples Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authorization/method-security.adoc Demonstrates JSON serialization differences based on user authorization. Includes examples for unauthorized and authorized users. ```json { "name" : "name", "email" : null } ``` ```json { "name" : "name", "email" : "email" } ``` -------------------------------- ### Define Kerberos configuration file Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authentication/kerberos/appendix.adoc Example krb5.ini configuration file for mapping realms and keytabs. ```text $ cat krb5.ini [libdefaults] default_realm = EXAMPLE.ORG default_keytab_name = /tmp/tomcat.keytab forwardable=true [realms] EXAMPLE.ORG = { kdc = WIN-EKBO0EQ7TS7.example.org:88 } [domain_realm] example.org=EXAMPLE.ORG .example.org=EXAMPLE.ORG ``` -------------------------------- ### Connect RSocket with Username/Password Setup Metadata Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/reactive/integrations/rsocket.adoc Establishes an RSocket connection using `RSocketRequester.builder()`, providing username and password credentials in the setup metadata. This is useful for authenticating the connection itself. ```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); ``` ```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) ``` -------------------------------- ### Kerberos Login with Keytab File Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authentication/kerberos/samples.adoc Example of performing a Kerberos login using a keytab file. ```text $ kinit -kt user2.keytab user1 $ klist Ticket cache: FILE:/tmp/krb5cc_1000 Default principal: user2@EXAMPLE.ORG Valid starting Expires Service principal 10/03/15 17:25:03 11/03/15 03:25:03 krbtgt/EXAMPLE.ORG@EXAMPLE.ORG renew until 11/03/15 17:25:03 ``` -------------------------------- ### Configure OAuth 2.0 Client Registration Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/reactive/oauth2/login/advanced.adoc Example of building an OAuth 2.0 client registration configuration. ```java .clientSecret("google-client-secret") .redirectUri("{baseUrl}/login/oauth2/callback/{registrationId}") .build() ``` -------------------------------- ### Configure KerberosRestTemplate Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authentication/kerberos/ssk.adoc Provides configuration examples for KerberosRestTemplate, supporting both cached tickets and keytab files for authentication. ```java include::example$kerberos/KerberosRestTemplateConfig.java[tags=snippetA] ``` ```java include::example$kerberos/KerberosRestTemplateConfig.java[tags=snippetB] ``` -------------------------------- ### Initializing DelegatingSecurityContextExecutor Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/features/integrations/concurrency.adoc Example of creating a context for use with the executor. ```java SecurityContext context = SecurityContextHolder.createEmptyContext(); Authentication authentication = ``` -------------------------------- ### Copy Release Notes to Clipboard Source: https://github.com/spring-projects/spring-security/blob/main/RELEASE.adoc This command pipes the generated release notes to the clipboard for easy pasting. Ensure `xclip` is installed. ```bash cat build/changelog/release-notes.md | xclip -selection clipboard ``` -------------------------------- ### Configure Digest Authentication Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authentication/passwords/digest.adoc Examples for setting up DigestAuthenticationFilter and DigestAuthenticationEntryPoint using Java and XML configurations. ```java @Autowired UserDetailsService userDetailsService; DigestAuthenticationEntryPoint authenticationEntryPoint() { DigestAuthenticationEntryPoint result = new DigestAuthenticationEntryPoint(); result.setRealmName("My App Realm"); result.setKey("3028472b-da34-4501-bfd8-a355c42bdf92"); return result; } DigestAuthenticationFilter digestAuthenticationFilter() { DigestAuthenticationFilter result = new DigestAuthenticationFilter(); result.setUserDetailsService(userDetailsService); result.setAuthenticationEntryPoint(authenticationEntryPoint()); return result; } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http // ... .exceptionHandling((e) -> e.authenticationEntryPoint(authenticationEntryPoint())) .addFilter(digestAuthenticationFilter()); return http.build(); } ``` ```xml ``` -------------------------------- ### Configure FilterSecurityInterceptor Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authentication/anonymous.adoc Example of setting up the FilterSecurityInterceptor to apply security across URI patterns. ```xml ``` -------------------------------- ### OAuth2 Login Link Example Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/oauth2/login/advanced.adoc This HTML snippet demonstrates how a link to initiate an OAuth 2.0 login for Google might look. ```html Google ``` -------------------------------- ### Manual Kerberos Login with User Principal Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authentication/kerberos/samples.adoc Example of performing a manual Kerberos login using a user principal and password. ```text $ kinit user1 Password for user1@EXAMPLE.ORG: $ klist Ticket cache: FILE:/tmp/krb5cc_1000 Default principal: user1@EXAMPLE.ORG Valid starting Expires Service principal 10/03/15 17:18:45 11/03/15 03:18:45 krbtgt/EXAMPLE.ORG@EXAMPLE.ORG renew until 11/03/15 17:18:40 ``` -------------------------------- ### Build Documentation Source: https://github.com/spring-projects/spring-security/blob/main/README.adoc Generates the reference documentation site locally. ```bash ./gradlew :spring-security-docs:antora ``` -------------------------------- ### Test Maximum Sessions with MockMvc Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authentication/session-management.adoc Example test setup for verifying session termination on second login using Spring Boot. ```java @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @AutoConfigureMockMvc public class MaximumSessionsTests { @Autowired private MockMvc mvc; @Test void loginOnSecondLoginThenFirstSessionTerminated() throws Exception { MvcResult mvcResult = this.mvc.perform(formLogin()) .andExpect(authenticated()) .andReturn(); MockHttpSession firstLoginSession = (MockHttpSession) mvcResult.getRequest().getSession(); ``` -------------------------------- ### Setup MIT Kerberos Realm and Database Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authentication/kerberos/appendix.adoc Initial commands to set up a new Kerberos realm and database using MIT Kerberos. This is a foundational step for development environments. ```text kdcadmin_password = "password" admin_keytab = "/etc/krb5kdc/kadm5.keytab" # Create a new realm kdb5_util create -s -P $kdcadmin_password # Start the KDC server krb5kdc # Start the KDC admin server kadmin_server ``` -------------------------------- ### Generate DPoP Proof JWT in Java Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/oauth2/authorization-server/protocol-endpoints.adoc Example of generating 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)); ``` -------------------------------- ### BCryptPasswordEncoder Example Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/features/authentication/password-storage.adoc Demonstrates the usage of BCryptPasswordEncoder, which uses the bcrypt algorithm. The default strength is 10, but it's recommended to tune it for your system. ```java BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder(10); bcryptPasswordEncoder.encode("password"); ``` -------------------------------- ### Define JAAS Login Configuration File Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authentication/jaas.adoc Example content for a standard JAAS login configuration file used by JaasAuthenticationProvider. ```txt JAASTest { sample.SampleLoginModule required; }; ``` -------------------------------- ### Annotate User Class Properties for Security in Kotlin Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authorization/method-security.adoc Use `@get:PreAuthorize` on properties in a Kotlin class to secure their getter methods. This example secures the `email` property. ```kotlin class User (val name:String, @get:PreAuthorize("hasAuthority('user:read')") val email:String) ``` -------------------------------- ### Initialize Kerberos Database Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authentication/kerberos/appendix.adoc Use kdb5_util to create a new Kerberos database. You will be prompted to set a master password, which must not be forgotten. ```text kdb5_util create -s -r EXAMPLE.ORG Loading random data Initializing database '/var/lib/krb5kdc/principal' for realm 'EXAMPLE.ORG', master key name 'K/M@EXAMPLE.ORG' You will be prompted for the database Master Password. It is important that you NOT FORGET this password. Enter KDC database master key: Re-enter KDC database master key to verify: ``` -------------------------------- ### Make Request with Propagated Bearer Token Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/reactive/oauth2/resource-server/bearer-tokens.adoc Example of making a GET request using a WebClient configured with ServerBearerExchangeFilterFunction. The bearer token will be automatically included in the Authorization header. ```java this.rest.get() .uri("https://other-service.example.com/endpoint") .retrieve() .bodyToMono(String.class) ``` ```kotlin this.rest.get() .uri("https://other-service.example.com/endpoint") .retrieve() .bodyToMono() ``` -------------------------------- ### Access Protected Resources using WebClient (Java) Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/reactive/oauth2/index.adoc Example of using a configured `WebClient` to make a GET request to a protected resource endpoint, automatically including the OAuth2 access token. ```java @RestController public class MessagesController { private final WebClient webClient; public MessagesController(WebClient webClient) { this.webClient = webClient; } fun messages(): Mono>> { return webClient.get() .uri("http://localhost:8090/messages") .attributes(clientRegistrationId("my-oauth2-client")), .retrieve() .toEntityList() } data class Message(val message: String) } ``` -------------------------------- ### Example RestClient Usage in Kotlin Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/oauth2/index.adoc This Kotlin controller demonstrates how to use RestClient to make a GET request to a protected resource. It retrieves messages from 'http://localhost:8090/messages' using an OAuth2 client registration. ```kotlin import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController import org.springframework.web.client.RestClient @RestController class MessagesController(private val restClient: RestClient) { @GetMapping("/messages") fun messages(): ResponseEntity> { val messages = restClient.get() .uri("http://localhost:8090/messages") .attributes(clientRegistrationId("my-oauth2-client")) .retrieve() .body>()!! .toList() return ResponseEntity.ok(messages) } data class Message(val message: String) } ``` -------------------------------- ### Run Security Server Side Auth Sample Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authentication/kerberos/samples.adoc Command to run the Security Server Side Auth sample application. ```text $ java -jar sec-server-client-auth-{spring-security-version}.jar ``` -------------------------------- ### Run Security Server Windows Auth Sample Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authentication/kerberos/samples.adoc Command to run the Security Server Windows Auth sample application. ```text $ java -jar sec-server-win-auth-{spring-security-version}.jar ``` -------------------------------- ### Implement Custom Token Delivery Handler Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/reactive/authentication/onetimetoken.adoc Provide a custom `ServerOneTimeTokenGenerationSuccessHandler` to manage how the generated one-time token is delivered to the user. This example shows a basic setup for sending an email via a magic link. ```java import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; @Component <1> public class MagicLinkOneTimeTokenGenerationSuccessHandler implements ServerOneTimeTokenGenerationSuccessHandler { private final MailSender mailSender; private final ServerOneTimeTokenGenerationSuccessHandler redirectHandler = new ServerRedirectOneTimeTokenGenerationSuccessHandler("/ott/sent"); // constructor omitted @Override public Mono handle(ServerWebExchange exchange, OneTimeToken oneTimeToken) { ``` -------------------------------- ### Observability Trace Output Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/integrations/observability.adoc Example output demonstrating the traces generated by Spring Security for an HTTP request. It shows the start and stop events for various components like the HTTP server requests, security filter chains, and authentication. ```bash START - name='http.server.requests', contextualName='null', error='null', lowCardinalityKeyValues=[], highCardinalityKeyValues=[], map=[class io.micrometer.core.instrument.Timer$Sample='io.micrometer.core.instrument.Timer$Sample@687e16d1', class io.micrometer.core.instrument.LongTaskTimer$Sample='SampleImpl{duration(seconds)=0.001779024, duration(nanos)=1779024.0, startTimeNanos=91695917264958}'] START - name='spring.security.http.chains', contextualName='spring.security.http.chains.before', error='null', lowCardinalityKeyValues=[chain.position='0', chain.size='17', filter.section='before'], highCardinalityKeyValues=[request.line='GET /'], map=[class io.micrometer.core.instrument.Timer$Sample='io.micrometer.core.instrument.Timer$Sample@79f554a5', class io.micrometer.core.instrument.LongTaskTimer$Sample='SampleImpl{duration(seconds)=7.42147E-4, duration(nanos)=742147.0, startTimeNanos=91695947182029}'] ... skipped for brevity ... STOP - name='spring.security.http.chains', contextualName='spring.security.http.chains.before', error='null', lowCardinalityKeyValues=[chain.position='0', chain.size='17', filter.section='before'], highCardinalityKeyValues=[request.line='GET /'], map=[class io.micrometer.core.instrument.Timer$Sample='io.micrometer.core.instrument.Timer$Sample@79f554a5', class io.micrometer.core.instrument.LongTaskTimer$Sample='SampleImpl{duration(seconds)=0.014771848, duration(nanos)=1.4771848E7, startTimeNanos=91695947182029}'] START - name='spring.security.authentications', contextualName='null', error='null', lowCardinalityKeyValues=[authentication.failure.type='Optional', authentication.method='ProviderManager', authentication.request.type='UsernamePasswordAuthenticationToken'], highCardinalityKeyValues=[], map=[class io.micrometer.core.instrument.Timer$Sample='io.micrometer.core.instrument.Timer$Sample@4d4b2b56', class io.micrometer.core.instrument.LongTaskTimer$Sample='SampleImpl{duration(seconds)=7.09759E-4, duration(nanos)=709759.0, startTimeNanos=91696094477504}'] ... skipped for brevity ... STOP - name='spring.security.authentications', contextualName='null', error='null', lowCardinalityKeyValues=[authentication.failure.type='Optional', authentication.method='ProviderManager', authentication.request.type='UsernamePasswordAuthenticationToken', authentication.result.type='UsernamePasswordAuthenticationToken'], highCardinalityKeyValues=[], map=[class io.micrometer.core.instrument.Timer$Sample='io.micrometer.core.instrument.Timer$Sample@4d4b2b56', class io.micrometer.core.instrument.LongTaskTimer$Sample='SampleImpl{duration(seconds)=0.895141386, duration(nanos)=8.95141386E8, startTimeNanos=91696094477504}'] ``` -------------------------------- ### Initialize Kerberos credentials Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authentication/kerberos/appendix.adoc Uses a specific configuration file and keytab to obtain initial Kerberos tickets. ```text $ env KRB5_CONFIG=/path/to/krb5.ini kinit -kt tomcat.keytab HTTP/neo.example.org@EXAMPLE.ORG $ klist Ticket cache: FILE:/tmp/krb5cc_1000 Default principal: HTTP/neo.example.org@EXAMPLE.ORG Valid starting Expires Service principal 26/03/15 09:04:37 26/03/15 19:04:37 krbtgt/EXAMPLE.ORG@EXAMPLE.ORG renew until 27/03/15 09:04:37 ``` -------------------------------- ### Send RSocket Authentication Token at Setup Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/reactive/integrations/rsocket.adoc Configures an RSocketRequester to include a Bearer token during the initial connection setup. ```java MimeType authenticationMimeType = MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString()); BearerTokenMetadata token = ...; Mono requester = RSocketRequester.builder() .setupMetadata(token, authenticationMimeType) .connectTcp(host, port); ``` ```kotlin val authenticationMimeType: MimeType = MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.string) val token: BearerTokenMetadata = ... val requester = RSocketRequester.builder() .setupMetadata(token, authenticationMimeType) .connectTcp(host, port) ``` -------------------------------- ### MockMvc GET Request with JWT Authentication Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/test/mockmvc/oauth2.adoc Perform a GET request using MockMvc with a pre-configured JWT authentication token. ```kotlin mvc.get("/endpoint") { with( authentication(token) ) } ``` -------------------------------- ### Create User and Export Keytab with kadmin Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authentication/kerberos/appendix.adoc Create a user and then generate a keytab file containing the principal's keys. This is useful for services that need to authenticate without user interaction. ```text kadmin: addprinc user2 WARNING: no policy specified for user2@EXAMPLE.ORG; defaulting to no policy Enter password for principal "user2@EXAMPLE.ORG": Re-enter password for principal "user2@EXAMPLE.ORG": Principal "user2@EXAMPLE.ORG" created. kadmin: ktadd -k /tmp/user2.keytab user2@EXAMPLE.ORG Entry for principal user2@EXAMPLE.ORG with kvno 2, encryption type aes256-cts-hmac-sha1-96 added to keytab WRFILE:/tmp/user2.keytab. Entry for principal user2@EXAMPLE.ORG with kvno 2, encryption type arcfour-hmac added to keytab WRFILE:/tmp/user2.keytab. Entry for principal user2@EXAMPLE.ORG with kvno 2, encryption type des3-cbc-sha1 added to keytab WRFILE:/tmp/user2.keytab. Entry for principal user2@EXAMPLE.ORG with kvno 2, encryption type des-cbc-crc added to keytab WRFILE:/tmp/user2.keytab. ``` -------------------------------- ### Run Security Server Spnego and Form Auth Sample Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authentication/kerberos/samples.adoc Command to run the Security Server Spnego and Form Auth sample application. ```text $ java -jar sec-server-spnego-form-auth-{spring-security-version}.jar ``` -------------------------------- ### DelegatingPasswordEncoder Encoded Passwords Example Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/features/authentication/password-storage.adoc Examples of passwords encoded with different IDs, demonstrating how DelegatingPasswordEncoder can handle various encoding formats. ```text {bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG {noop}password {pbkdf2}5d923b44a6d129f3ddf3e3c8d29412723dcbde72445e8ef6bf3b508fbf17fa4ed4d6b99ca763d8dc {scrypt}$e0801$8bWJaSu2IKSn9Z9kM+TPXfOc/9bdYSrN1oD9qfVThWEwdRTnO7re7Ei+fUZRJ68k9lTyuTeUp4of4g24hHnazw==$OAOec05+bXxvuu/1qZ6NUR+xQYvYv7BeL1QxwRpY5Pc= {sha256}97cde38028ad898ebc02e690819fa220e88c62e0699403e94fff291cfffaf8410849f27605abcbc0 ``` -------------------------------- ### JWT Scope Example Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/reactive/oauth2/resource-server/jwt.adoc Example of a JWT containing a 'scope' attribute. Resource Server will prefix these scopes with 'SCOPE_' when converting them to granted authorities. ```json { ..., "scope" : "messages contacts" } ``` -------------------------------- ### Dummy UserDetailsService for Kerberos Samples Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authentication/kerberos/appendix.adoc A sample UserDetailsService implementation used in Kerberos authentication examples. It's a placeholder for a real user source. ```java package com.example.security.kerberos; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; public class DummyUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // Dummy implementation: always returns a user with username and password 'password' // In a real application, this would fetch user details from a database or other user store. if (username.equals("user")) { return org.springframework.security.core.userdetails.User.withUsername("user") .password("password") .roles("USER") .build(); } throw new UsernameNotFoundException("User not found: " + username); } } ``` -------------------------------- ### Login Page Path Configuration Example Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authentication/passwords/form.adoc Demonstrates how to correctly specify the login page URI when the dispatcher servlet is mapped under a base path. Ensure the prefix is included in the URI passed to the DSL. ```java http.formLogin(form -> form.loginPage("/api/login")) ``` -------------------------------- ### Spring Security Debug Logging Example Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/architecture.adoc Example log output demonstrating Spring Security's detailed logging for security-related events, useful for debugging. ```text 2023-06-14T09:44:25.797-03:00 DEBUG 76975 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Securing POST /hello 2023-06-14T09:44:25.797-03:00 TRACE 76975 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking DisableEncodeUrlFilter (1/15) 2023-06-14T09:44:25.798-03:00 TRACE 76975 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking WebAsyncManagerIntegrationFilter (2/15) 2023-06-14T09:44:25.800-03:00 TRACE 76975 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking SecurityContextHolderFilter (3/15) 2023-06-14T09:44:25.801-03:00 TRACE 76975 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking HeaderWriterFilter (4/15) 2023-06-14T09:44:25.802-03:00 TRACE 76975 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking CsrfFilter (5/15) ``` -------------------------------- ### Synchronizer Token HTTP Request Example Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/features/exploits/csrf.adoc An example of an HTTP POST request demonstrating the Synchronizer Token Pattern. The CSRF token is included as a form parameter. ```http POST /transfer HTTP/1.1 Host: bank.example.com Cookie: JSESSIONID=randomid Content-Type: application/x-www-form-urlencoded amount=100.00&routingNumber=1234&account=9876&_csrf=4bfd1575-3ad1-4d21-96c7-4ef2d9f86721 ``` -------------------------------- ### Configure ClientRegistration using Issuer Location Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/reactive/oauth2/client/core.adoc Demonstrates how to build a ClientRegistration by discovering provider details from an issuer URI. This is a convenient way to initialize client configurations. ```java ClientRegistration clientRegistration = ClientRegistrations.fromIssuerLocation("https://idp.example.com/issuer").build(); ``` -------------------------------- ### Implement Banking Security Configuration Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/configuration/java.adoc Demonstrates a multi-filter chain setup for banking applications with specific role-based access control for different path patterns. ```java @Configuration @EnableWebSecurity public class BankingSecurityConfig { @Bean <1> public UserDetailsService userDetailsService() { UserBuilder users = User.withDefaultPasswordEncoder(); InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); manager.createUser(users.username("user1").password("password").roles("USER", "VIEW_BALANCE").build()); manager.createUser(users.username("user2").password("password").roles("USER").build()); manager.createUser(users.username("admin").password("password").roles("ADMIN").build()); return manager; } @Bean @Order(1) <2> public SecurityFilterChain approvalsSecurityFilterChain(HttpSecurity http) throws Exception { String[] approvalsPaths = { "/accounts/approvals/**", "/loans/approvals/**", "/credit-cards/approvals/**" }; http .securityMatcher(approvalsPaths) .authorizeHttpRequests((authorize) -> authorize .anyRequest().hasRole("ADMIN") ) .httpBasic(Customizer.withDefaults()); return http.build(); } @Bean @Order(2) <3> public SecurityFilterChain bankingSecurityFilterChain(HttpSecurity http) throws Exception { String[] bankingPaths = { "/accounts/**", "/loans/**", "/credit-cards/**", "/balances/**" }; String[] viewBalancePaths = { "/balances/**" }; http .securityMatcher(bankingPaths) .authorizeHttpRequests((authorize) -> authorize .requestMatchers(viewBalancePaths).hasRole("VIEW_BALANCE") .anyRequest().hasRole("USER") ); return http.build(); } @Bean <4> ``` -------------------------------- ### Allow Only GET & POST HTTP Methods in Kotlin Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/reactive/exploits/firewall.adoc Configure StrictServerWebExchangeFirewall to only allow GET and POST HTTP methods. This enhances security by restricting the accepted HTTP verbs. ```kotlin @Bean fun httpFirewall(): StrictServerWebExchangeFirewall { val firewall = StrictServerWebExchangeFirewall() firewall.setAllowedHttpMethods(listOf("GET", "POST")) return firewall } ``` -------------------------------- ### Execute Kerberos Client with Keytab Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authentication/kerberos/samples.adoc Run the client application using a keytab file for authentication. ```text $ java -jar sec-client-rest-template-{spring-security-version}.jar ``` -------------------------------- ### Allow Only GET & POST HTTP Methods in Java Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/reactive/exploits/firewall.adoc Configure StrictServerWebExchangeFirewall to only allow GET and POST HTTP methods. This enhances security by restricting the accepted HTTP verbs. ```java @Bean public StrictServerWebExchangeFirewall httpFirewall() { StrictServerWebExchangeFirewall firewall = new StrictServerWebExchangeFirewall(); firewall.setAllowedHttpMethods(Arrays.asList("GET", "POST")); return firewall; } ``` -------------------------------- ### DPoP Access Token Request Example Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/oauth2/resource-server/dpop-tokens.adoc An example of an authorization code access token request including a DPoP proof in the 'DPoP' header. This format is applicable for all access token grant types. ```shell POST /oauth2/token HTTP/1.1 Host: server.example.com Content-Type: application/x-www-form-urlencoded DPoP: eyJraWQiOiJyc2EtandrLWtpZCIsInR5cCI6ImRwb3Arand0IiwiYWxnIjoiUlMyNTYiLCJqd2siOnsia3R5IjoiUlNBIiwiZSI6IkFRQUIiLCJraWQiOiJyc2EtandrLWtpZCIsIm4iOiIzRmxxSnI1VFJza0lRSWdkRTNEZDdEOWxib1dkY1RVVDhhLWZKUjdNQXZRbTdYWE5vWWttM3Y3TVFMMU5ZdER2TDJsOENBbmMwV2RTVElOVTZJUnZjNUtxbzJRNGNzTlg5U0hPbUVmem9ST2pRcWFoRWN2ZTFqQlhsdW9DWGRZdVlweDRfMXRmUmdHNmlpNFVoeGg2aUk4cU5NSlFYLWZMZnFoYmZZZnhCUVZSUHl3QmtBYklQNHgxRUFzYkM2RlNObWtoQ3hpTU5xRWd4YUlwWThDMmtKZEpfWklWLVdXNG5vRGR6cEtxSGN3bUI4RnNydW1sVllfRE5WdlVTRElpcGlxOVBiUDRIOTlUWE4xbzc0Nm9SYU5hMDdycTFob0NnTVNTeS04NVNhZ0NveGxteUUtRC1vZjlTc01ZOE9sOXQwcmR6cG9iQnVoeUpfbzVkZnZqS3cifX0.eyJodG0iOiJQT1NUIiwiaHR1IjoiaHR0cHM6Ly9zZXJ2ZXIuZXhhbXBsZS5jb20vb2F1dGgyL3Rva2VuIiwiaWF0IjoxNzQ2ODA2MzA1LCJqdGkiOiI0YjIzNDBkMi1hOTFmLTQ0Y5-YmFhOS1kZDRlNWRlYWM4NjcifQ.wq8gJ_G6vpiEinfaY3WhereqCCLoeJOG8tnWBBAzRWx9F1KU5yAAWq-ZVCk_k07-h6DIqz2wgv6y9dVbNpRYwNwDUeik9qLRsC60M8YW7EFVyI3n_NpujLwzZeub_nDYMVnyn4ii0NaZrYHtoGXOlswQfS_-ET-jpC0XWm5nBZsCdUEXjOYtwaACC6Js-pyNwKmSLp5SKIk11jZUR5xIIopaQy521y9qJHhGRwzj8DQGsP7wMZ98UFL0E--1c-hh4rTy8PMeWCqRHdwjj_ry_eTe0DJFcxxYQdeL7-0_0CIO4Ayx5WHEpcUOIzBRoN32RsNpDZc-5slDNj9ku004DA grant_type=authorization_code &client_id=s6BhdRkqt &code=SplxlOBeZQQYbYS6WxSbIA &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb &code_verifier=bEaL42izcC-o-xBk0K2vuJ6U-y1p9r_wW2dFWIWgjz- ``` -------------------------------- ### Configure SAML 2.0 Relying Party Registration Repository (Kotlin) Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/saml2/logout.adoc Sets up a RelyingPartyRegistrationRepository with SAML 2.0 metadata, registration ID, single logout service location, and signing credentials in Kotlin. Ensure the private key and certificate are properly configured. ```kotlin @Configuration class SecurityConfig(@Value("${private.key}") val key: RSAPrivateKey, @Value("${public.certificate}") val certificate: X509Certificate) { @Bean fun registrations(): RelyingPartyRegistrationRepository { val credential = Saml2X509Credential.signing(key, certificate) val registration = RelyingPartyRegistrations .fromMetadataLocation("https://ap.example.org/metadata") <1> .registrationId("metadata") .singleLogoutServiceLocation("{baseUrl}/logout/saml2/slo") <2> .signingX509Credentials({ signing: List -> signing.add(credential) }) <3> .build() return InMemoryRelyingPartyRegistrationRepository(registration) } ``` -------------------------------- ### OAuth2TokenGenerator Configuration Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/oauth2/authorization-server/core-model-components.adoc Example of how to register a custom OAuth2TokenGenerator bean. ```APIDOC ## Registering OAuth2TokenGenerator ### Description This example demonstrates how to configure a DelegatingOAuth2TokenGenerator with custom generators for JWT and opaque tokens. ### Request Example @Bean public OAuth2TokenGenerator tokenGenerator() { JwtEncoder jwtEncoder = ... JwtGenerator jwtGenerator = new JwtGenerator(jwtEncoder); OAuth2AccessTokenGenerator accessTokenGenerator = new OAuth2AccessTokenGenerator(); OAuth2RefreshTokenGenerator refreshTokenGenerator = new OAuth2RefreshTokenGenerator(); return new DelegatingOAuth2TokenGenerator( jwtGenerator, accessTokenGenerator, refreshTokenGenerator); } ``` -------------------------------- ### Configure X.509 Authentication Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authentication/x509.adoc Basic configuration for X.509 authentication using the HttpSecurity DSL. ```java include-code::./DefaultX509Configuration[tag=springSecurity,indent=0] ``` -------------------------------- ### Configure TestExecutionEvent for @WithMockUser Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/test/method.adoc Changes the SecurityContext setup event to beforeTestExecution. ```java @WithMockUser(setupBefore = TestExecutionEvent.TEST_EXECUTION) ``` -------------------------------- ### Retrieving BearerTokenAuthentication in Controller Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/reactive/test/web/oauth2.adoc Example controller method signature for receiving BearerTokenAuthentication. ```java @GetMapping("/endpoint") public Mono foo(BearerTokenAuthentication authentication) { return Mono.just((String) authentication.getTokenAttributes().get("sub")); } ``` ```kotlin @GetMapping("/endpoint") fun foo(authentication: BearerTokenAuthentication): Mono { return Mono.just(authentication.tokenAttributes["sub"] as String?) } ``` -------------------------------- ### Inspect Security Filter Chain Logs Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/architecture.adoc Example of the DEBUG level console output showing the configured security filter chain during application startup. ```text 2023-06-14T08:55:22.321-03:00 DEBUG 76975 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure any request with [ DisableEncodeUrlFilter, WebAsyncManagerIntegrationFilter, SecurityContextHolderFilter, HeaderWriterFilter, CsrfFilter, LogoutFilter, UsernamePasswordAuthenticationFilter, DefaultLoginPageGeneratingFilter, DefaultLogoutPageGeneratingFilter, BasicAuthenticationFilter, RequestCacheAwareFilter, SecurityContextHolderAwareRequestFilter, AnonymousAuthenticationFilter, ExceptionTranslationFilter, AuthorizationFilter] ``` -------------------------------- ### Run as a user with custom roles and password Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/test/mockmvc/authentication.adoc Configures a user with specific credentials and multiple roles. ```java mvc .perform(get("/admin").with(user("admin").password("pass").roles("USER","ADMIN"))) ``` ```kotlin mvc.get("/admin") { with(user("admin").password("pass").roles("USER","ADMIN")) } ``` -------------------------------- ### Define Content Security Policy Header Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/reactive/exploits/headers.adoc Example of a CSP header string. ```http Content-Security-Policy: script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/ ``` -------------------------------- ### Configure SAML 2.0 Relying Party Registration Repository Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/saml2/logout.adoc Sets up a RelyingPartyRegistrationRepository with SAML 2.0 metadata, registration ID, single logout service location, and signing credentials. Ensure the private key and certificate are properly configured. ```java RelyingPartyRegistrationRepository registrations() { Saml2X509Credential credential = Saml2X509Credential.signing(key, certificate); RelyingPartyRegistration registration = RelyingPartyRegistrations .fromMetadataLocation("https://ap.example.org/metadata") <1> .registrationId("metadata") .singleLogoutServiceLocation("{baseUrl}/logout/saml2/slo") <2> .signingX509Credentials((signing) -> signing.add(credential)) <3> .build(); return new InMemoryRelyingPartyRegistrationRepository(registration); } ``` -------------------------------- ### Observability Output Log Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/reactive/integrations/observability.adoc Example of the console output generated by the ObservationTextPublisher during a request. ```bash START - name='http.server.requests', contextualName='null', error='null', lowCardinalityKeyValues=[], highCardinalityKeyValues=[], map=[class io.micrometer.tracing.handler.TracingObservationHandler$TracingContext='io.micrometer.tracing.handler.TracingObservationHandler$TracingContext@5dfdb78', class io.micrometer.core.instrument.LongTaskTimer$Sample='SampleImpl{duration(seconds)=0.00191856, duration(nanos)=1918560.0, startTimeNanos=101177265022745}', class io.micrometer.core.instrument.Timer$Sample='io.micrometer.core.instrument.Timer$Sample@121549e0'] START - name='spring.security.http.chains', contextualName='spring.security.http.chains.before', error='null', lowCardinalityKeyValues=[chain.size='14', filter.section='before'], highCardinalityKeyValues=[request.line='/'], map=[class io.micrometer.tracing.handler.TracingObservationHandler$TracingContext='io.micrometer.tracing.handler.TracingObservationHandler$TracingContext@3932a48c', class io.micrometer.core.instrument.LongTaskTimer$Sample='SampleImpl{duration(seconds)=4.65777E-4, duration(nanos)=465777.0, startTimeNanos=101177276300777}', class io.micrometer.core.instrument.Timer$Sample='io.micrometer.core.instrument.Timer$Sample@562db70f'] STOP - name='spring.security.http.chains', contextualName='spring.security.http.chains.before', error='null', lowCardinalityKeyValues=[chain.size='14', filter.section='before'], highCardinalityKeyValues=[request.line='/'], map=[class io.micrometer.tracing.handler.TracingObservationHandler$TracingContext='io.micrometer.tracing.handler.TracingObservationHandler$TracingContext@3932a48c', class io.micrometer.core.instrument.LongTaskTimer$Sample='SampleImpl{duration(seconds)=0.003733105, duration(nanos)=3733105.0, startTimeNanos=101177276300777}', class io.micrometer.core.instrument.Timer$Sample='io.micrometer.core.instrument.Timer$Sample@562db70f'] START - name='spring.security.authentications', contextualName='null', error='null', lowCardinalityKeyValues=[authentication.failure.type='Optional', authentication.method='UserDetailsRepositoryReactiveAuthenticationManager', authentication.request.type='UsernamePasswordAuthenticationToken'], highCardinalityKeyValues=[], map=[class io.micrometer.tracing.handler.TracingObservationHandler$TracingContext='io.micrometer.tracing.handler.TracingObservationHandler$TracingContext@574ba6cd', class io.micrometer.core.instrument.LongTaskTimer$Sample='SampleImpl{duration(seconds)=3.21015E-4, duration(nanos)=321015.0, startTimeNanos=101177336038417}', class io.micrometer.core.instrument.Timer$Sample='io.micrometer.core.instrument.Timer$Sample@49202cc7'] ``` -------------------------------- ### Configure ClientRegistration for Google Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/oauth2/login/core.adoc Manual definition of a Google ClientRegistration using the builder pattern. ```java return ClientRegistration.withRegistrationId("google") .clientId("google-client-id") .clientSecret("google-client-secret") .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") .scope("openid", "profile", "email", "address", "phone") .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") .tokenUri("https://www.googleapis.com/oauth2/v4/token") .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") .userNameAttributeName(IdTokenClaimNames.SUB) .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") .clientName("Google") .build(); } } ``` ```kotlin @Configuration class OAuth2LoginConfig { @Bean open fun filterChain(http: HttpSecurity): SecurityFilterChain { http { authorizeHttpRequests { authorize(anyRequest, authenticated) } oauth2Login { } } return http.build() } @Bean fun clientRegistrationRepository(): ClientRegistrationRepository { return InMemoryClientRegistrationRepository(googleClientRegistration()) } private fun googleClientRegistration(): ClientRegistration { return ClientRegistration.withRegistrationId("google") .clientId("google-client-id") .clientSecret("google-client-secret") .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") .scope("openid", "profile", "email", "address", "phone") .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") .tokenUri("https://www.googleapis.com/oauth2/v4/token") .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") .userNameAttributeName(IdTokenClaimNames.SUB) .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") .clientName("Google") .build() } } ``` -------------------------------- ### Configure TestExecutionEvent for @WithUserDetails Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/test/method.adoc Changes the SecurityContext setup event for UserDetails-based tests to beforeTestExecution. ```java @WithUserDetails(setupBefore = TestExecutionEvent.TEST_EXECUTION) ``` -------------------------------- ### Authorize Requests with Multiple Rules Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authorization/authorize-http-requests.adoc This example demonstrates authorizing requests using a combination of authorization rules, including `allOf`, `hasAuthority`, and `hasRole`. It requires the `Authentication` to have specific authorities and roles. ```java import static jakarta.servlet.DispatcherType.*; import static org.springframework.security.authorization.AuthorizationManagers.allOf; import static org.springframework.security.authorization.AuthorityAuthorizationManager.hasAuthority; import static org.springframework.security.authorization.AuthorityAuthorizationManager.hasRole; @Bean SecurityFilterChain web(HttpSecurity http) throws Exception { http // ... ``` -------------------------------- ### Configure TestExecutionEvent for @WithAnonymousUser Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/test/method.adoc Changes the SecurityContext setup event for anonymous users to beforeTestExecution. ```java @WithAnonymousUser(setupBefore = TestExecutionEvent.TEST_EXECUTION) ``` -------------------------------- ### Configure Saml2AuthenticationTokenConverter Bean Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/migration/servlet/saml2.adoc Defines a bean for Saml2AuthenticationTokenConverter with GET request processing disabled. ```kotlin @Bean fun authenticationConverter(val registrations: RelyingPartyRegistrationRepository): Saml2AuthenticationTokenConverter { val authenticationConverter = Saml2AuthenticationTokenConverter(registrations) authenticationConverter.setShouldConvertGetRequests(false) return authenticationConverter } ``` -------------------------------- ### Configure Authentication Provider with JavaConfig Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authentication/kerberos/ssk.adoc Sets up the Kerberos authentication provider using Java configuration. ```java include::example$kerberos/AuthProviderConfig.java[tags=snippetA] ``` -------------------------------- ### Perform filtered LDAP search Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authentication/kerberos/appendix.adoc Example of querying LDAP with specific user filters. ```text $ ldapsearch -H ldap://WIN-EKBO0EQ7TS7.example.org \ -b "dc=example,dc=org" \ "(| (userPrincipalName=user2@EXAMPLE.ORG) (sAMAccountName=user2@EXAMPLE.ORG))" \ dn ... ``` -------------------------------- ### Example Introspection Response Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/reactive/oauth2/resource-server/opaque-token.adoc The default structure expected from an introspection endpoint for scope parsing. ```json { "active" : true, "scope" : "message:read message:write" } ``` -------------------------------- ### Basic Security Test Setup Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/test/method.adoc Sets up the test environment for Spring Security testing. It uses JUnit 5 extension and context configuration to load the application context. ```java import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = SecurityConfig.class) public class MethodSecurityExpressionTests { @Autowired private HelloMessageService messageService; @Test public void expectsSecuredMessage() { messageService.getMessage(); } } ``` -------------------------------- ### Configure Content Security Policy (CSP) for Script Sources Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/features/exploits/headers.adoc This example demonstrates how to declare trusted sources for script resources using the Content-Security-Policy header. Attempts to load scripts from untrusted sources will be blocked. ```http Content-Security-Policy: script-src https://trustedscripts.example.com ``` -------------------------------- ### Attempt kadmin Connection Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authentication/kerberos/appendix.adoc This demonstrates an attempt to use the kadmin command before any admin users are created in the database, resulting in a 'Client not found' error. ```text kadmin Authenticating as principal root/admin@EXAMPLE.ORG with password. kadmin: Client not found in Kerberos database while initializing kadmin interface ``` -------------------------------- ### User Controller with AuthorizationProxyFactory Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/authorization/method-security.adoc Example of a user controller that uses AuthorizationProxyFactory to proxy user information. ```java @RestController class UserController { @Autowired var proxyFactory: AuthorizationProxyFactory? = null @GetMapping fun currentUser(@AuthenticationPrincipal user:User?): User { return proxyFactory.proxy(user) } } ``` -------------------------------- ### Registering InMemoryRegisteredClientRepository Bean Source: https://github.com/spring-projects/spring-security/blob/main/docs/modules/ROOT/pages/servlet/oauth2/authorization-server/core-model-components.adoc Example of how to register an InMemoryRegisteredClientRepository bean. This implementation is recommended only for development and testing. ```java @Bean public RegisteredClientRepository registeredClientRepository() { List registrations = ... return new InMemoryRegisteredClientRepository(registrations); } ```