Use standard lambda syntax in documentation

Fixes: gh-7774
This commit is contained in:
Eleftheria Stein 2020-01-10 13:10:36 +01:00
parent a35ce77451
commit 1e33627d87
22 changed files with 423 additions and 599 deletions

View File

@ -23,12 +23,10 @@ You can easily do this with the following Java Configuration:
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers .frameOptions(frameOptions -> frameOptions
.frameOptions(frameOptions -> .mode(Mode.SAMEORIGIN)
frameOptions )
.mode(Mode.SAMEORIGIN)
)
); );
return http.build(); return http.build();
} }
@ -46,10 +44,7 @@ An example for both Java configuration is provided below:
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers.disable());
headers
.disable()
);
return http.build(); return http.build();
} }
---- ----
@ -76,9 +71,8 @@ If necessary, you can also disable Spring Security's cache control HTTP response
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers .cache(cache -> cache.disable())
.cache(cache -> cache.disable())
); );
return http.build(); return http.build();
} }
@ -99,9 +93,8 @@ However, you can disable it in Java Configuration with:
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers .contentTypeOptions(contentTypeOptions -> contentTypeOptions.disable())
.contentTypeOptions(contentTypeOptions -> contentTypeOptions.disable())
); );
return http.build(); return http.build();
} }
@ -122,14 +115,12 @@ For example, the following is an example of explicitly providing HSTS with Java
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers .hsts(hsts -> hsts
.hsts(hsts -> .includeSubdomains(true)
hsts .preload(true)
.includeSubdomains(true) .maxAge(Duration.ofDays(365))
.preload(true) )
.maxAge(Duration.ofDays(365))
)
); );
return http.build(); return http.build();
} }
@ -150,12 +141,10 @@ You can customize frame options to use the same origin within Java Configuration
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers .frameOptions(frameOptions -> frameOptions
.frameOptions(frameOptions -> .mode(SAMEORIGIN)
frameOptions )
.mode(SAMEORIGIN)
)
); );
return http.build(); return http.build();
} }
@ -175,9 +164,8 @@ You can disable `X-XSS-Protection` with the following Java Configuration:
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers .xssProtection(xssProtection -> xssProtection.disable())
.xssProtection(xssProtection -> xssProtection.disable())
); );
return http.build(); return http.build();
} }
@ -209,12 +197,10 @@ You can enable the CSP header using Java configuration as shown below:
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers .contentSecurityPolicy(policy -> policy
.contentSecurityPolicy(contentSecurityPolicy -> .policyDirectives("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/")
contentSecurityPolicy )
.policyDirectives("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/")
)
); );
return http.build(); return http.build();
} }
@ -231,13 +217,11 @@ To enable the CSP `report-only` header, provide the following Java configuration
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers .contentSecurityPolicy(policy -> policy
.contentSecurityPolicy(contentSecurityPolicy -> .policyDirectives("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/")
contentSecurityPolicy .reportOnly()
.policyDirectives("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/") )
.reportOnly()
)
); );
return http.build(); return http.build();
} }
@ -258,12 +242,10 @@ You can enable the Referrer Policy header using Java configuration as shown belo
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers .referrerPolicy(referrer -> referrer
.referrerPolicy(referrerPolicy -> .policy(ReferrerPolicy.SAME_ORIGIN)
referrerPolicy )
.policy(ReferrerPolicy.SAME_ORIGIN)
)
); );
return http.build(); return http.build();
} }
@ -295,9 +277,8 @@ can enable the Feature Policy header using Java configuration as shown below:
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers .featurePolicy("geolocation 'self'")
.featurePolicy("geolocation 'self'")
); );
return http.build(); return http.build();
} }

View File

@ -38,9 +38,8 @@ For example, if the production environment adds a header named `X-Forwarded-Prot
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http http
// ... // ...
.redirectToHttps(redirectToHttps -> .redirectToHttps(redirect -> redirect
redirectToHttps .httpsRedirectWhen(e -> e.getRequest().getHeaders().containsKey("X-Forwarded-Proto"))
.httpsRedirectWhen(e -> e.getRequest().getHeaders().containsKey("X-Forwarded-Proto"))
); );
return http.build(); return http.build();
} }

View File

@ -88,9 +88,8 @@ public class SecurityConfig {
return http return http
// Demonstrate that method security works // Demonstrate that method security works
// Best practice to use both for defense in depth // Best practice to use both for defense in depth
.authorizeExchange(exchanges -> .authorizeExchange(exchanges -> exchanges
exchanges .anyExchange().permitAll()
.anyExchange().permitAll()
) )
.httpBasic(withDefaults()) .httpBasic(withDefaults())
.build(); .build();

View File

@ -151,12 +151,11 @@ Additional configuration options can be seen below:
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http http
// ... // ...
.oauth2Login(oauth2Login -> .oauth2Login(oauth2 -> oauth2
oauth2Login .authenticationConverter(converter)
.authenticationConverter(converter) .authenticationManager(manager)
.authenticationManager(manager) .authorizedClientRepository(authorizedClients)
.authorizedClientRepository(authorizedClients) .clientRegistrationRepository(clientRegistrations)
.clientRegistrationRepository(clientRegistrations)
); );
return http.build(); return http.build();
} }

View File

@ -129,9 +129,8 @@ The first is a `SecurityWebFilterChain` that configures the app as a resource se
@Bean @Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http http
.authorizeExchange(exchanges -> .authorizeExchange(exchanges -> exchanges
exchanges .anyExchange().authenticated()
.anyExchange().authenticated()
) )
.oauth2ResourceServer(OAuth2ResourceServerSpec::jwt) .oauth2ResourceServer(OAuth2ResourceServerSpec::jwt)
return http.build(); return http.build();
@ -147,14 +146,12 @@ Replacing this is as simple as exposing the bean within the application:
@Bean @Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http http
.authorizeExchange(exchanges -> .authorizeExchange(exchanges -> exchanges
exchanges .pathMatchers("/message/**").hasAuthority("SCOPE_message:read")
.pathMatchers("/message/**").hasAuthority("SCOPE_message:read") .anyExchange().authenticated()
.anyExchange().authenticated()
) )
.oauth2ResourceServer(oauth2ResourceServer -> .oauth2ResourceServer(oauth2 -> oauth2
oauth2ResourceServer .jwt(withDefaults())
.jwt(withDefaults())
); );
return http.build(); return http.build();
} }
@ -190,16 +187,13 @@ An authorization server's JWK Set Uri can be configured <<webflux-oauth2resource
@Bean @Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http http
.authorizeExchange(exchanges -> .authorizeExchange(exchanges -> exchanges
exchanges .anyExchange().authenticated()
.anyExchange().authenticated()
) )
.oauth2ResourceServer(oauth2ResourceServer -> .oauth2ResourceServer(oauth2 -> oauth2
oauth2ResourceServer .jwt(jwt -> jwt
.jwt(jwt -> .jwkSetUri("https://idp.example.com/.well-known/jwks.json")
jwt )
.jwkSetUri("https://idp.example.com/.well-known/jwks.json")
)
); );
return http.build(); return http.build();
} }
@ -217,16 +211,13 @@ More powerful than `jwkSetUri()` is `decoder()`, which will completely replace a
@Bean @Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http http
.authorizeExchange(exchanges -> .authorizeExchange(exchanges -> exchanges
exchanges .anyExchange().authenticated()
.anyExchange().authenticated()
) )
.oauth2ResourceServer(oauth2ResourceServer -> .oauth2ResourceServer(oauth2 -> oauth2
oauth2ResourceServer .jwt(jwt -> jwt
.jwt(jwt -> .decoder(myCustomDecoder())
jwt )
.decoder(myCustomDecoder())
)
); );
return http.build(); return http.build();
} }
@ -398,7 +389,7 @@ This means that to protect an endpoint or method with a scope derived from a JWT
@Bean @Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http http
.authorizeExchange(exchanges ->exchanges .authorizeExchange(exchanges -> exchanges
.mvcMatchers("/contacts/**").hasAuthority("SCOPE_contacts") .mvcMatchers("/contacts/**").hasAuthority("SCOPE_contacts")
.mvcMatchers("/messages/**").hasAuthority("SCOPE_messages") .mvcMatchers("/messages/**").hasAuthority("SCOPE_messages")
.anyExchange().authenticated() .anyExchange().authenticated()
@ -430,16 +421,13 @@ To this end, the DSL exposes `jwtAuthenticationConverter()`:
@Bean @Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http http
.authorizeExchange(exchanges -> .authorizeExchange(exchanges -> exchanges
exchanges .anyExchange().authenticated()
.anyExchange().authenticated()
) )
.oauth2ResourceServer(oauth2ResourceServer -> .oauth2ResourceServer(oauth2 -> oauth2
oauth2ResourceServer .jwt(jwt -> jwt
.jwt(jwt -> .jwtAuthenticationConverter(grantedAuthoritiesExtractor())
jwt )
.jwtAuthenticationConverter(grantedAuthoritiesExtractor())
)
); );
return http.build(); return http.build();
} }
@ -678,9 +666,8 @@ When use Opaque Token, this `SecurityWebFilterChain` looks like:
@Bean @Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http http
.authorizeExchange(exchanges -> .authorizeExchange(exchanges -> exchanges
exchanges .anyExchange().authenticated()
.anyExchange().authenticated()
) )
.oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::opaqueToken) .oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::opaqueToken)
return http.build(); return http.build();
@ -698,17 +685,14 @@ public class MyCustomSecurityConfiguration {
@Bean @Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http http
.authorizeExchange(exchanges -> .authorizeExchange(exchanges -> exchanges
exchanges .pathMatchers("/messages/**").hasAuthority("SCOPE_message:read")
.pathMatchers("/messages/**").hasAuthority("SCOPE_message:read") .anyExchange().authenticated()
.anyExchange().authenticated()
) )
.oauth2ResourceServer(oauth2ResourceServer -> .oauth2ResourceServer(oauth2 -> oauth2
oauth2ResourceServer .opaqueToken(opaqueToken -> opaqueToken
.opaqueToken(opaqueToken -> .introspector(myIntrospector())
opaqueToken )
.introspector(myIntrospector())
)
); );
return http.build(); return http.build();
} }
@ -745,17 +729,14 @@ public class DirectlyConfiguredIntrospectionUri {
@Bean @Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http http
.authorizeExchange(exchanges -> .authorizeExchange(exchanges -> exchanges
exchanges .anyExchange().authenticated()
.anyExchange().authenticated()
) )
.oauth2ResourceServer(oauth2ResourceServer -> .oauth2ResourceServer(oauth2 -> oauth2
oauth2ResourceServer .opaqueToken(opaqueToken -> opaqueToken
.opaqueToken(opaqueToken -> .introspectionUri("https://idp.example.com/introspect")
opaqueToken .introspectionClientCredentials("client", "secret")
.introspectionUri("https://idp.example.com/introspect") )
.introspectionClientCredentials("client", "secret")
)
); );
return http.build(); return http.build();
} }
@ -776,16 +757,13 @@ public class DirectlyConfiguredIntrospector {
@Bean @Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http http
.authorizeExchange(exchanges -> .authorizeExchange(exchanges -> exchanges
exchanges .anyExchange().authenticated()
.anyExchange().authenticated()
) )
.oauth2ResourceServer(oauth2ResourceServer -> .oauth2ResourceServer(oauth2 -> oauth2
oauth2ResourceServer .opaqueToken(opaqueToken -> opaqueToken
.opaqueToken(opaqueToken -> .introspector(myCustomIntrospector())
opaqueToken )
.introspector(myCustomIntrospector())
)
); );
return http.build(); return http.build();
} }

View File

@ -56,9 +56,8 @@ public class HelloWebfluxSecurityConfig {
@Bean @Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http http
.authorizeExchange(exchanges -> .authorizeExchange(exchanges -> exchanges
exchanges .anyExchange().authenticated()
.anyExchange().authenticated()
) )
.httpBasic(withDefaults()) .httpBasic(withDefaults())
.formLogin(withDefaults()); .formLogin(withDefaults());

View File

@ -10,9 +10,8 @@ Below is an example of a reactive x509 security configuration:
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
http http
.x509(withDefaults()) .x509(withDefaults())
.authorizeExchange(exchanges -> .authorizeExchange(exchanges -> exchanges
exchanges .anyExchange().permitAll()
.anyExchange().permitAll()
); );
return http.build(); return http.build();
} }
@ -37,14 +36,12 @@ public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
}; };
http http
.x509(x509 -> .x509(x509 -> x509
x509 .principalExtractor(principalExtractor)
.principalExtractor(principalExtractor) .authenticationManager(authenticationManager)
.authenticationManager(authenticationManager)
) )
.authorizeExchange(exchanges -> .authorizeExchange(exchanges -> exchanges
exchanges .anyExchange().authenticated()
.anyExchange().authenticated()
); );
return http.build(); return http.build();
} }

View File

@ -17,17 +17,16 @@ Similar to configuring login capabilities, however, you also have various option
[source,java] [source,java]
---- ----
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.logout(logout -> // <1> .logout(logout -> logout // <1>
logout .logoutUrl("/my/logout") // <2>
.logoutUrl("/my/logout") // <2> .logoutSuccessUrl("/my/index") // <3>
.logoutSuccessUrl("/my/index") // <3> .logoutSuccessHandler(logoutSuccessHandler) // <4>
.logoutSuccessHandler(logoutSuccessHandler) // <4> .invalidateHttpSession(true) // <5>
.invalidateHttpSession(true) // <5> .addLogoutHandler(logoutHandler) // <6>
.addLogoutHandler(logoutHandler) // <6> .deleteCookies(cookieNamesToClear) // <7>
.deleteCookies(cookieNamesToClear) // <7> )
) ...
...
} }
---- ----

View File

@ -9,12 +9,11 @@ For example:
---- ----
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.authorizeRequests(authorizeRequests -> // <1> .authorizeRequests(authorize -> authorize // <1>
authorizeRequests .antMatchers("/resources/**", "/signup", "/about").permitAll() // <2>
.antMatchers("/resources/**", "/signup", "/about").permitAll() // <2> .antMatchers("/admin/**").hasRole("ADMIN") // <3>
.antMatchers("/admin/**").hasRole("ADMIN") // <3> .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')") // <4>
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')") // <4> .anyRequest().authenticated() // <5>
.anyRequest().authenticated() // <5>
) )
.formLogin(withDefaults()); .formLogin(withDefaults());
} }

View File

@ -140,10 +140,9 @@ or in Java configuration
[source,java] [source,java]
---- ----
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .antMatchers("/user/**").access("@webSecurity.check(authentication,request)")
.antMatchers("/user/**").access("@webSecurity.check(authentication,request)") ...
...
) )
---- ----
@ -181,10 +180,9 @@ or in Java configuration
[source,java] [source,java]
---- ----
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .antMatchers("/user/{userId}/**").access("@webSecurity.checkUserId(authentication,#userId)")
.antMatchers("/user/{userId}/**").access("@webSecurity.checkUserId(authentication,#userId)") ...
...
); );
---- ----

View File

@ -70,9 +70,8 @@ public class WebSecurityConfig extends
@Override @Override
protected void configure(HttpSecurity http) { protected void configure(HttpSecurity http) {
http http
.csrf(csrf -> .csrf(csrf -> csrf
csrf .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
); );
} }
} }
@ -119,9 +118,7 @@ public class WebSecurityConfig extends
@Override @Override
protected void configure(HttpSecurity http) { protected void configure(HttpSecurity http) {
http http
.csrf(csrf -> .csrf(csrf -> csrf.disable());
csrf.disable()
);
} }
} }
---- ----
@ -303,9 +300,8 @@ public class WebSecurityConfig extends
@Override @Override
protected void configure(HttpSecurity http) { protected void configure(HttpSecurity http) {
http http
.logout(logout -> .logout(logout -> logout
logout .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
); );
} }
} }

View File

@ -27,11 +27,10 @@ public class WebSecurityConfig extends
protected void configure(HttpSecurity http) { protected void configure(HttpSecurity http) {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers .frameOptions(frameOptions -> frameOptions
.frameOptions(frameOptions -> .sameOrigin()
frameOptions.sameOrigin() )
)
); );
} }
} }
@ -69,11 +68,10 @@ WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers // do not use any default headers unless explicitly listed
// do not use any default headers unless explicitly listed .defaultsDisabled()
.defaultsDisabled() .cacheControl(withDefaults())
.cacheControl(withDefaults())
); );
} }
} }
@ -105,9 +103,7 @@ WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers.disable());
headers.disable()
);
} }
} }
---- ----
@ -149,10 +145,8 @@ WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) { protected void configure(HttpSecurity http) {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers.cacheControl(cache -> .cacheControl(cache -> cache.disable())
cache.disabled()
)
); );
} }
} }
@ -194,10 +188,8 @@ public class WebSecurityConfig extends
protected void configure(HttpSecurity http) { protected void configure(HttpSecurity http) {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers.contentTypeOptions(contentType -> .contentTypeOptions(contentTypeOptions -> contentTypeOptions.disable())
contentType.disabled()
)
); );
} }
} }
@ -239,14 +231,12 @@ WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers .httpStrictTransportSecurity(hsts -> hsts
.httpStrictTransportSecurity(hsts -> .includeSubDomains(true)
hsts .preload(true)
.includeSubDomains(true) .maxAgeInSeconds(31536000)
.preload(true) )
.maxAgeInSeconds(31536000)
)
); );
} }
} }
@ -291,14 +281,12 @@ WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers .httpPublicKeyPinning(hpkp -> hpkp
.httpPublicKeyPinning(hpkp -> .includeSubDomains(true)
hpkp .reportUri("https://example.net/pkp-report")
.includeSubDomains(true) .addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=", "E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=")
.reportUri("https://example.net/pkp-report") )
.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=", "E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=")
)
); );
} }
} }
@ -348,12 +336,10 @@ WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers .frameOptions(frameOptions -> frameOptions
.frameOptions(frameOptions -> .sameOrigin()
frameOptions )
.sameOrigin()
)
); );
} }
} }
@ -397,12 +383,10 @@ WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers .xssProtection(xss -> xss
.xssProtection(xssProtection -> .block(false)
xssProtection )
.block(false)
)
); );
} }
} }
@ -456,12 +440,10 @@ WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) { protected void configure(HttpSecurity http) {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers .contentSecurityPolicy(csp -> csp
.contentSecurityPolicy(csp -> .policyDirectives("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/")
csp )
.policyDirectives("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/")
)
); );
} }
} }
@ -499,13 +481,11 @@ public class WebSecurityConfig extends
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers .contentSecurityPolicy(csp -> csp
.contentSecurityPolicy(csp -> .policyDirectives("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/")
csp .reportOnly()
.policyDirectives("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/") )
.reportOnly()
)
); );
} }
} }
@ -548,12 +528,10 @@ WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) { protected void configure(HttpSecurity http) {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers .referrerPolicy(referrer -> referrer
.referrerPolicy(referrerPolicy -> .policy(ReferrerPolicy.SAME_ORIGIN)
referrerPolicy )
.policy(ReferrerPolicy.SAME_ORIGIN)
)
); );
} }
} }
@ -605,9 +583,8 @@ WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers .featurePolicy("geolocation 'self'")
.featurePolicy("geolocation 'self'")
); );
} }
} }
@ -694,9 +671,8 @@ WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers .addHeaderWriter(new StaticHeadersWriter("X-Custom-Security-Header","header-value"))
.addHeaderWriter(new StaticHeadersWriter("X-Custom-Security-Header","header-value"))
); );
} }
} }
@ -739,9 +715,8 @@ WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers .addHeaderWriter(new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN))
.addHeaderWriter(new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN))
); );
} }
} }
@ -794,12 +769,9 @@ WebSecurityConfigurerAdapter {
new DelegatingRequestMatcherHeaderWriter(matcher,new XFrameOptionsHeaderWriter()); new DelegatingRequestMatcherHeaderWriter(matcher,new XFrameOptionsHeaderWriter());
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers .frameOptions(frameOptions -> frameOptions.disable())
.frameOptions(frameOptions -> .addHeaderWriter(headerWriter)
frameOptions.disable()
)
.addHeaderWriter(headerWriter)
); );
} }
} }

View File

@ -25,9 +25,8 @@ public class WebSecurityConfig extends
protected void configure(HttpSecurity http) { protected void configure(HttpSecurity http) {
http http
// ... // ...
.requiresChannel(channel -> .requiresChannel(channel -> channel
channel .anyRequest().requiresSecure()
.anyRequest().requiresSecure()
); );
} }
} }

View File

@ -102,9 +102,8 @@ If we wanted to restrict access to this controller method to admin users, a deve
---- ----
protected configure(HttpSecurity http) throws Exception { protected configure(HttpSecurity http) throws Exception {
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .antMatchers("/admin").hasRole("ADMIN")
.antMatchers("/admin").hasRole("ADMIN")
); );
} }
---- ----
@ -133,9 +132,8 @@ The following configuration will protect the same URLs that Spring MVC will matc
---- ----
protected configure(HttpSecurity http) throws Exception { protected configure(HttpSecurity http) throws Exception {
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .mvcMatchers("/admin").hasRole("ADMIN")
.mvcMatchers("/admin").hasRole("ADMIN")
); );
} }
---- ----

View File

@ -319,18 +319,16 @@ Similarly, you can customize frame options to use the same origin within Java Co
public class WebSecurityConfig extends public class WebSecurityConfig extends
WebSecurityConfigurerAdapter { WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
// ... // ...
.headers(headers -> .headers(headers -> headers
headers .frameOptions(frameOptions -> frameOptions
.frameOptions(frameOptions -> .sameOrigin()
frameOptions )
.sameOrigin() );
) }
);
}
} }
---- ----
@ -361,20 +359,17 @@ public class WebSecurityConfig
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.csrf(csrf -> .csrf(csrf -> csrf
csrf // ignore our stomp endpoints since they are protected using Stomp headers
// ignore our stomp endpoints since they are protected using Stomp headers .ignoringAntMatchers("/chat/**")
.ignoringAntMatchers("/chat/**")
) )
.headers(headers -> .headers(headers -> headers
headers // allow same origin to frame our site to support iframe SockJS
// allow same origin to frame our site to support iframe SockJS .frameOptions(frameOptions -> frameOptions
.frameOptions(frameOptions -> .sameOrigin()
frameOptions )
.sameOrigin()
)
) )
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
... ...
) )
... ...

View File

@ -140,9 +140,8 @@ It has a method called `configure` with the following default implementation:
---- ----
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .anyRequest().authenticated()
.anyRequest().authenticated()
) )
.formLogin(withDefaults()) .formLogin(withDefaults())
.httpBasic(withDefaults()); .httpBasic(withDefaults());
@ -192,9 +191,8 @@ public class MultiHttpSecurityConfig {
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.antMatcher("/api/**") <3> .antMatcher("/api/**") <3>
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .anyRequest().hasRole("ADMIN")
.anyRequest().hasRole("ADMIN")
) )
.httpBasic(withDefaults()); .httpBasic(withDefaults());
} }
@ -206,9 +204,8 @@ public class MultiHttpSecurityConfig {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .anyRequest().authenticated()
.anyRequest().authenticated()
) )
.formLogin(withDefaults()); .formLogin(withDefaults());
} }
@ -326,16 +323,15 @@ For example, if you wanted to configure the `filterSecurityPublishAuthorizationS
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .anyRequest().authenticated()
.anyRequest().authenticated() .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() { public <O extends FilterSecurityInterceptor> O postProcess(
public <O extends FilterSecurityInterceptor> O postProcess( O fsi) {
O fsi) { fsi.setPublishAuthorizationSuccess(true);
fsi.setPublishAuthorizationSuccess(true); return fsi;
return fsi; }
} })
})
); );
} }
---- ----

View File

@ -27,17 +27,15 @@ public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.oauth2Client(oauth2Client -> .oauth2Client(oauth2 -> oauth2
oauth2Client .clientRegistrationRepository(this.clientRegistrationRepository())
.clientRegistrationRepository(this.clientRegistrationRepository()) .authorizedClientRepository(this.authorizedClientRepository())
.authorizedClientRepository(this.authorizedClientRepository()) .authorizedClientService(this.authorizedClientService())
.authorizedClientService(this.authorizedClientService()) .authorizationCodeGrant(codeGrant -> codeGrant
.authorizationCodeGrant(authorizationCodeGrant -> .authorizationRequestRepository(this.authorizationRequestRepository())
authorizationCodeGrant .authorizationRequestResolver(this.authorizationRequestResolver())
.authorizationRequestRepository(this.authorizationRequestRepository()) .accessTokenResponseClient(this.accessTokenResponseClient())
.authorizationRequestResolver(this.authorizationRequestResolver()) )
.accessTokenResponseClient(this.accessTokenResponseClient())
)
); );
} }
} }
@ -465,18 +463,16 @@ public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .anyRequest().authenticated()
.anyRequest().authenticated()
) )
.oauth2Login(oauth2Login -> .oauth2Login(oauth2 -> oauth2
oauth2Login .authorizationEndpoint(authorization -> authorization
.authorizationEndpoint(authorizationEndpoint -> .authorizationRequestResolver(
authorizationEndpoint new CustomAuthorizationRequestResolver(
.authorizationRequestResolver( this.clientRegistrationRepository) <1>
new CustomAuthorizationRequestResolver(
this.clientRegistrationRepository)) <1>
) )
)
); );
} }
} }
@ -595,13 +591,11 @@ public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.oauth2Client(oauth2Client -> .oauth2Client(oauth2 -> oauth2
oauth2Client .authorizationCodeGrant(codeGrant -> codeGrant
.authorizationCodeGrant(authorizationCodeGrant -> .authorizationRequestRepository(this.authorizationRequestRepository())
authorizationCodeGrant ...
.authorizationRequestRepository(this.authorizationRequestRepository()) )
...
)
); );
} }
} }
@ -659,13 +653,11 @@ public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.oauth2Client(oauth2Client -> .oauth2Client(oauth2 -> oauth2
oauth2Client .authorizationCodeGrant(codeGrant -> codeGrant
.authorizationCodeGrant(authorizationCodeGrant -> .accessTokenResponseClient(this.accessTokenResponseClient())
authorizationCodeGrant ...
.accessTokenResponseClient(this.accessTokenResponseClient()) )
...
)
); );
} }
} }

View File

@ -291,9 +291,8 @@ public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .anyRequest().authenticated()
.anyRequest().authenticated()
) )
.oauth2Login(withDefaults()); .oauth2Login(withDefaults());
} }
@ -317,9 +316,8 @@ public class OAuth2LoginConfig {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .anyRequest().authenticated()
.anyRequest().authenticated()
) )
.oauth2Login(withDefaults()); .oauth2Login(withDefaults());
} }
@ -366,9 +364,8 @@ public class OAuth2LoginConfig {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .anyRequest().authenticated()
.anyRequest().authenticated()
) )
.oauth2Login(withDefaults()); .oauth2Login(withDefaults());
} }
@ -418,24 +415,19 @@ public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.oauth2Login(oauth2Login -> .oauth2Login(oauth2 -> oauth2
oauth2Login .authorizationEndpoint(authorization -> authorization
.authorizationEndpoint(authorizationEndpoint -> ...
authorizationEndpoint )
... .redirectionEndpoint(redirection -> redirection
) ...
.redirectionEndpoint(redirectionEndpoint -> )
redirectionEndpoint .tokenEndpoint(token -> token
... ...
) )
.tokenEndpoint(tokenEndpoint -> .userInfoEndpoint(userInfo -> userInfo
tokenEndpoint ...
... )
)
.userInfoEndpoint(userInfoEndpoint ->
userInfoEndpoint
...
)
); );
} }
} }
@ -470,33 +462,28 @@ public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.oauth2Login(oauth2Login -> .oauth2Login(oauth2 -> oauth2
oauth2Login .clientRegistrationRepository(this.clientRegistrationRepository())
.clientRegistrationRepository(this.clientRegistrationRepository()) .authorizedClientRepository(this.authorizedClientRepository())
.authorizedClientRepository(this.authorizedClientRepository()) .authorizedClientService(this.authorizedClientService())
.authorizedClientService(this.authorizedClientService()) .loginPage("/login")
.loginPage("/login") .authorizationEndpoint(authorization -> authorization
.authorizationEndpoint(authorizationEndpoint -> .baseUri(this.authorizationRequestBaseUri())
authorizationEndpoint .authorizationRequestRepository(this.authorizationRequestRepository())
.baseUri(this.authorizationRequestBaseUri()) .authorizationRequestResolver(this.authorizationRequestResolver())
.authorizationRequestRepository(this.authorizationRequestRepository()) )
.authorizationRequestResolver(this.authorizationRequestResolver()) .redirectionEndpoint(redirection -> redirection
) .baseUri(this.authorizationResponseBaseUri())
.redirectionEndpoint(redirectionEndpoint -> )
redirectionEndpoint .tokenEndpoint(token -> token
.baseUri(this.authorizationResponseBaseUri()) .accessTokenResponseClient(this.accessTokenResponseClient())
) )
.tokenEndpoint(tokenEndpoint -> .userInfoEndpoint(userInfo -> userInfo
tokenEndpoint .userAuthoritiesMapper(this.userAuthoritiesMapper())
.accessTokenResponseClient(this.accessTokenResponseClient()) .userService(this.oauth2UserService())
) .oidcUserService(this.oidcUserService())
.userInfoEndpoint(userInfoEndpoint -> .customUserType(GitHubOAuth2User.class, "github")
userInfoEndpoint )
.userAuthoritiesMapper(this.userAuthoritiesMapper())
.userService(this.oauth2UserService())
.oidcUserService(this.oidcUserService())
.customUserType(GitHubOAuth2User.class, "github")
)
); );
} }
} }
@ -542,15 +529,13 @@ public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.oauth2Login(oauth2Login -> .oauth2Login(oauth2 -> oauth2
oauth2Login .loginPage("/login/oauth2")
.loginPage("/login/oauth2") ...
.authorizationEndpoint(authorization -> authorization
.baseUri("/login/oauth2/authorization")
... ...
.authorizationEndpoint(authorizationEndpoint -> )
authorizationEndpoint
.baseUri("/login/oauth2/authorization")
...
)
); );
} }
} }
@ -594,13 +579,11 @@ public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.oauth2Login(oauth2Login -> .oauth2Login(oauth2 -> oauth2
oauth2Login .redirectionEndpoint(redirection -> redirection
.redirectionEndpoint(redirectionEndpoint -> .baseUri("/login/oauth2/callback/*")
redirectionEndpoint ...
.baseUri("/login/oauth2/callback/*") )
...
)
); );
} }
} }
@ -661,13 +644,11 @@ public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.oauth2Login(oauth2Login -> .oauth2Login(oauth2 -> oauth2
oauth2Login .userInfoEndpoint(userInfo -> userInfo
.userInfoEndpoint(userInfoEndpoint -> .userAuthoritiesMapper(this.userAuthoritiesMapper())
userInfoEndpoint ...
.userAuthoritiesMapper(this.userAuthoritiesMapper()) )
...
)
); );
} }
@ -740,13 +721,11 @@ public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.oauth2Login(oauth2Login -> .oauth2Login(oauth2 -> oauth2
oauth2Login .userInfoEndpoint(userInfo -> userInfo
.userInfoEndpoint(userInfoEndpoint -> .oidcUserService(this.oidcUserService())
userInfoEndpoint ...
.oidcUserService(this.oidcUserService()) )
...
)
); );
} }
@ -791,13 +770,11 @@ public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.oauth2Login(oauth2Login -> .oauth2Login(oauth2 -> oauth2
oauth2Login .userInfoEndpoint(userInfo -> userInfo
.userInfoEndpoint(userInfoEndpoint -> .customUserType(GitHubOAuth2User.class, "github")
userInfoEndpoint ...
.customUserType(GitHubOAuth2User.class, "github") )
...
)
); );
} }
} }
@ -909,13 +886,11 @@ public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.oauth2Login(oauth2Login -> .oauth2Login(oauth2 -> oauth2
oauth2Login .userInfoEndpoint(userInfo -> userInfo
.userInfoEndpoint(userInfoEndpoint -> .userService(this.oauth2UserService())
userInfoEndpoint ...
.userService(this.oauth2UserService()) )
...
)
); );
} }
@ -945,13 +920,11 @@ public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.oauth2Login(oauth2Login -> .oauth2Login(oauth2 -> oauth2
oauth2Login .userInfoEndpoint(userInfo -> userInfo
.userInfoEndpoint(userInfoEndpoint -> .oidcUserService(this.oidcUserService())
userInfoEndpoint ...
.oidcUserService(this.oidcUserService()) )
...
)
); );
} }
@ -1031,14 +1004,12 @@ public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .anyRequest().authenticated()
.anyRequest().authenticated()
) )
.oauth2Login(withDefaults()) .oauth2Login(withDefaults())
.logout(logout -> .logout(logout -> logout
logout .logoutSuccessHandler(oidcLogoutSuccessHandler())
.logoutSuccessHandler(oidcLogoutSuccessHandler())
); );
} }

View File

@ -128,9 +128,8 @@ The first is a `WebSecurityConfigurerAdapter` that configures the app as a resou
---- ----
protected void configure(HttpSecurity http) { protected void configure(HttpSecurity http) {
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .anyRequest().authenticated()
.anyRequest().authenticated()
) )
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt); .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
} }
@ -146,17 +145,14 @@ Replacing this is as simple as exposing the bean within the application:
public class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter { public class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) { protected void configure(HttpSecurity http) {
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .mvcMatchers("/messages/**").hasAuthority("SCOPE_message:read")
.mvcMatchers("/messages/**").hasAuthority("SCOPE_message:read") .anyRequest().authenticated()
.anyRequest().authenticated()
) )
.oauth2ResourceServer(oauth2ResourceServer -> .oauth2ResourceServer(oauth2 -> oauth2
oauth2ResourceServer .jwt(jwt -> jwt
.jwt(jwt -> .jwtAuthenticationConverter(myConverter())
jwt )
.jwtAuthenticationConverter(myConverter())
)
); );
} }
} }
@ -194,16 +190,13 @@ An authorization server's JWK Set Uri can be configured <<oauth2resourceserver-j
public class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter { public class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) { protected void configure(HttpSecurity http) {
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .anyRequest().authenticated()
.anyRequest().authenticated()
) )
.oauth2ResourceServer(oauth2ResourceServer -> .oauth2ResourceServer(oauth2 -> oauth2
oauth2ResourceServer .jwt(jwt -> jwt
.jwt(jwt -> .jwkSetUri("https://idp.example.com/.well-known/jwks.json")
jwt )
.jwkSetUri("https://idp.example.com/.well-known/jwks.json")
)
); );
} }
} }
@ -222,16 +215,13 @@ More powerful than `jwkSetUri()` is `decoder()`, which will completely replace a
public class DirectlyConfiguredJwtDecoder extends WebSecurityConfigurerAdapter { public class DirectlyConfiguredJwtDecoder extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) { protected void configure(HttpSecurity http) {
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .anyRequest().authenticated()
.anyRequest().authenticated()
) )
.oauth2ResourceServer(oauth2ResourceServer -> .oauth2ResourceServer(oauth2 -> oauth2
oauth2ResourceServer .jwt(jwt -> jwt
.jwt(jwt -> .decoder(myCustomDecoder())
jwt )
.decoder(myCustomDecoder())
)
); );
} }
} }
@ -427,7 +417,7 @@ This means that to protect an endpoint or method with a scope derived from a JWT
public class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter { public class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) { protected void configure(HttpSecurity http) {
http http
.authorizeRequests(authorizeRequests -> authorizeRequests .authorizeRequests(authorize -> authorize
.mvcMatchers("/contacts/**").hasAuthority("SCOPE_contacts") .mvcMatchers("/contacts/**").hasAuthority("SCOPE_contacts")
.mvcMatchers("/messages/**").hasAuthority("SCOPE_messages") .mvcMatchers("/messages/**").hasAuthority("SCOPE_messages")
.anyRequest().authenticated() .anyRequest().authenticated()
@ -460,16 +450,13 @@ To this end, the DSL exposes `jwtAuthenticationConverter()`:
public class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter { public class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) { protected void configure(HttpSecurity http) {
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .anyRequest().authenticated()
.anyRequest().authenticated()
) )
.oauth2ResourceServer(oauth2ResourceServer -> .oauth2ResourceServer(oauth2 -> oauth2
oauth2ResourceServer .jwt(jwt -> jwt
.jwt(jwt -> .jwtAuthenticationConverter(grantedAuthoritiesExtractor())
jwt )
.jwtAuthenticationConverter(grantedAuthoritiesExtractor())
)
); );
} }
} }
@ -828,9 +815,8 @@ When use Opaque Token, this `WebSecurityConfigurerAdapter` looks like:
---- ----
protected void configure(HttpSecurity http) { protected void configure(HttpSecurity http) {
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .anyRequest().authenticated()
.anyRequest().authenticated()
) )
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::opaqueToken); .oauth2ResourceServer(OAuth2ResourceServerConfigurer::opaqueToken);
} }
@ -846,17 +832,14 @@ Replacing this is as simple as exposing the bean within the application:
public class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter { public class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) { protected void configure(HttpSecurity http) {
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .mvcMatchers("/messages/**").hasAuthority("SCOPE_message:read")
.mvcMatchers("/messages/**").hasAuthority("SCOPE_message:read") .anyRequest().authenticated()
.anyRequest().authenticated()
) )
.oauth2ResourceServer(oauth2ResourceServer -> .oauth2ResourceServer(oauth2 -> oauth2
oauth2ResourceServer .opaqueToken(opaqueToken -> opaqueToken
.opaqueToken(opaqueToken -> .introspector(myIntrospector())
opaqueToken )
.introspector(myIntrospector())
)
); );
} }
} }
@ -891,17 +874,14 @@ An authorization server's Introspection Uri can be configured <<oauth2resourcese
public class DirectlyConfiguredIntrospectionUri extends WebSecurityConfigurerAdapter { public class DirectlyConfiguredIntrospectionUri extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) { protected void configure(HttpSecurity http) {
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .anyRequest().authenticated()
.anyRequest().authenticated()
) )
.oauth2ResourceServer(oauth2ResourceServer -> .oauth2ResourceServer(oauth2 -> oauth2
oauth2ResourceServer .opaqueToken(opaqueToken -> opaqueToken
.opaqueToken(opaqueToken -> .introspectionUri("https://idp.example.com/introspect")
opaqueToken .introspectionClientCredentials("client", "secret")
.introspectionUri("https://idp.example.com/introspect") )
.introspectionClientCredentials("client", "secret")
)
); );
} }
} }
@ -920,16 +900,13 @@ More powerful than `introspectionUri()` is `introspector()`, which will complete
public class DirectlyConfiguredIntrospector extends WebSecurityConfigurerAdapter { public class DirectlyConfiguredIntrospector extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) { protected void configure(HttpSecurity http) {
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .anyRequest().authenticated()
.anyRequest().authenticated()
) )
.oauth2ResourceServer(oauth2ResourceServer -> .oauth2ResourceServer(oauth2 -> oauth2
oauth2ResourceServer .opaqueToken(opaqueToken -> opaqueToken
.opaqueToken(opaqueToken -> .introspector(myCustomIntrospector())
opaqueToken )
.introspector(myCustomIntrospector())
)
); );
} }
} }
@ -1220,13 +1197,11 @@ And then specify this `AuthenticationManagerResolver` in the DSL:
[source,java] [source,java]
---- ----
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .anyRequest().authenticated()
.anyRequest().authenticated()
) )
.oauth2ResourceServer(oauth2ResourceServer -> .oauth2ResourceServer(oauth2 -> oauth2
oauth2ResourceServer .authenticationManagerResolver(this.tokenAuthenticationManagerResolver)
.authenticationManagerResolver(this.tokenAuthenticationManagerResolver)
); );
---- ----
@ -1253,13 +1228,11 @@ JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = new JwtIs
("https://idp.example.org/issuerOne", "https://idp.example.org/issuerTwo"); ("https://idp.example.org/issuerOne", "https://idp.example.org/issuerTwo");
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .anyRequest().authenticated()
.anyRequest().authenticated()
) )
.oauth2ResourceServer(oauth2ResourceServer -> .oauth2ResourceServer(oauth2 -> oauth2
oauth2ResourceServer .authenticationManagerResolver(authenticationManagerResolver)
.authenticationManagerResolver(authenticationManagerResolver)
); );
---- ----
@ -1286,13 +1259,11 @@ JwtIssuerAuthenticationManagerResolver authenticationManagerResolver =
new JwtIssuerAuthenticationManagerResolver(authenticationManagers::get); new JwtIssuerAuthenticationManagerResolver(authenticationManagers::get);
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .anyRequest().authenticated()
.anyRequest().authenticated()
) )
.oauth2ResourceServer(oauth2ResourceServer -> .oauth2ResourceServer(oauth2 -> oauth2
oauth2ResourceServer .authenticationManagerResolver(authenticationManagerResolver)
.authenticationManagerResolver(authenticationManagerResolver)
); );
---- ----
@ -1443,9 +1414,8 @@ To achieve this, you can wire a `HeaderBearerTokenResolver` instance into the DS
[source,java] [source,java]
---- ----
http http
.oauth2ResourceServer(oauth2ResourceServer -> .oauth2ResourceServer(oauth2 -> oauth2
oauth2ResourceServer .bearerTokenResolver(new HeaderBearerTokenResolver("x-goog-iap-jwt-assertion"))
.bearerTokenResolver(new HeaderBearerTokenResolver("x-goog-iap-jwt-assertion"))
); );
---- ----
@ -1458,9 +1428,8 @@ Or, you may wish to read the token from a form parameter, which you can do by co
DefaultBearerTokenResolver resolver = new DefaultBearerTokenResolver(); DefaultBearerTokenResolver resolver = new DefaultBearerTokenResolver();
resolver.setAllowFormEncodedBodyParameter(true); resolver.setAllowFormEncodedBodyParameter(true);
http http
.oauth2ResourceServer(oauth2ResourceServer -> .oauth2ResourceServer(oauth2 -> oauth2
oauth2ResourceServer .bearerTokenResolver(resolver)
.bearerTokenResolver(resolver)
); );
---- ----

View File

@ -85,9 +85,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .anyRequest().authenticated()
.anyRequest().authenticated()
) )
.saml2Login(withDefaults()) .saml2Login(withDefaults())
; ;
@ -105,13 +104,11 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .anyRequest().authenticated()
.anyRequest().authenticated()
) )
.saml2Login(saml2Login -> .saml2Login(saml2 -> saml2
saml2Login .relyingPartyRegistrationRepository(...)
.relyingPartyRegistrationRepository(...)
) )
; ;
} }
@ -262,13 +259,11 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
}; };
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .anyRequest().authenticated()
.anyRequest().authenticated()
) )
.saml2Login(saml2Login -> .saml2Login(saml2 -> saml2
saml2Login .addObjectPostProcessor(processor)
.addObjectPostProcessor(processor)
) )
; ;
} }
@ -291,13 +286,11 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
authProvider.setAuthoritiesMapper(AUTHORITIES_MAPPER); authProvider.setAuthoritiesMapper(AUTHORITIES_MAPPER);
authProvider.setAuthoritiesExtractor(AUTHORITIES_EXTRACTOR); authProvider.setAuthoritiesExtractor(AUTHORITIES_EXTRACTOR);
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .anyRequest().authenticated()
.anyRequest().authenticated()
) )
.saml2Login(saml2Login -> .saml2Login(saml2 -> saml2
saml2Login .authenticationManager(new ProviderManager(asList(authProvider)))
.authenticationManager(new ProviderManager(asList(authProvider)))
) )
; ;
} }
@ -319,13 +312,11 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
AuthenticationManager authenticationManager = new MySaml2AuthenticationManager(...); AuthenticationManager authenticationManager = new MySaml2AuthenticationManager(...);
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .anyRequest().authenticated()
.anyRequest().authenticated()
) )
.saml2Login(saml2Login -> .saml2Login(saml2 -> saml2
saml2Login .authenticationManager(authenticationManager)
.authenticationManager(authenticationManager)
) )
; ;
} }

View File

@ -40,9 +40,8 @@ public class SecurityConfig {
return http return http
// Demonstrate that method security works // Demonstrate that method security works
// Best practice to use both for defense in depth // Best practice to use both for defense in depth
.authorizeExchange(exchanges -> .authorizeExchange(exchanges -> exchanges
exchanges .anyExchange().permitAll()
.anyExchange().permitAll()
) )
.httpBasic(withDefaults()) .httpBasic(withDefaults())
.build(); .build();

View File

@ -34,15 +34,13 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.authorizeRequests(authorizeRequests -> .authorizeRequests(authorize -> authorize
authorizeRequests .antMatchers("/css/**", "/index").permitAll()
.antMatchers("/css/**", "/index").permitAll() .antMatchers("/user/**").hasRole("USER")
.antMatchers("/user/**").hasRole("USER")
) )
.formLogin(formLogin -> .formLogin(formLogin -> formLogin
formLogin .loginPage("/login")
.loginPage("/login") .failureUrl("/login-error")
.failureUrl("/login-error")
); );
} }
// @formatter:on // @formatter:on