Use http security nested builder in docs

Issue: gh-5557
This commit is contained in:
Eleftheria Stein 2019-07-12 13:58:17 -04:00
parent 7961b819aa
commit b004f9f677
10 changed files with 507 additions and 335 deletions

View File

@ -104,8 +104,10 @@ 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 ->
.antMatchers("/admin").hasRole("ADMIN"); authorizeRequests
.antMatchers("/admin").hasRole("ADMIN")
);
} }
---- ----
@ -133,8 +135,10 @@ 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 ->
.mvcMatchers("/admin").hasRole("ADMIN"); authorizeRequests
.mvcMatchers("/admin").hasRole("ADMIN")
);
} }
---- ----

View File

@ -16,15 +16,25 @@ 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 ->
.authorizationEndpoint() oauth2Login
... .authorizationEndpoint(authorizationEndpoint ->
.redirectionEndpoint() authorizationEndpoint
... ...
.tokenEndpoint() )
... .redirectionEndpoint(redirectionEndpoint ->
.userInfoEndpoint() redirectionEndpoint
... ...
)
.tokenEndpoint(tokenEndpoint ->
tokenEndpoint
...
)
.userInfoEndpoint(userInfoEndpoint ->
userInfoEndpoint
...
)
);
} }
} }
---- ----
@ -58,27 +68,34 @@ 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 ->
.clientRegistrationRepository(this.clientRegistrationRepository()) oauth2Login
.authorizedClientRepository(this.authorizedClientRepository()) .clientRegistrationRepository(this.clientRegistrationRepository())
.authorizedClientService(this.authorizedClientService()) .authorizedClientRepository(this.authorizedClientRepository())
.loginPage("/login") .authorizedClientService(this.authorizedClientService())
.authorizationEndpoint() .loginPage("/login")
.baseUri(this.authorizationRequestBaseUri()) .authorizationEndpoint(authorizationEndpoint ->
.authorizationRequestRepository(this.authorizationRequestRepository()) authorizationEndpoint
.authorizationRequestResolver(this.authorizationRequestResolver()) .baseUri(this.authorizationRequestBaseUri())
.and() .authorizationRequestRepository(this.authorizationRequestRepository())
.redirectionEndpoint() .authorizationRequestResolver(this.authorizationRequestResolver())
.baseUri(this.authorizationResponseBaseUri()) )
.and() .redirectionEndpoint(redirectionEndpoint ->
.tokenEndpoint() redirectionEndpoint
.accessTokenResponseClient(this.accessTokenResponseClient()) .baseUri(this.authorizationResponseBaseUri())
.and() )
.userInfoEndpoint() .tokenEndpoint(tokenEndpoint ->
.userAuthoritiesMapper(this.userAuthoritiesMapper()) tokenEndpoint
.userService(this.oauth2UserService()) .accessTokenResponseClient(this.accessTokenResponseClient())
.oidcUserService(this.oidcUserService()) )
.customUserType(GitHubOAuth2User.class, "github"); .userInfoEndpoint(userInfoEndpoint ->
userInfoEndpoint
.userAuthoritiesMapper(this.userAuthoritiesMapper())
.userService(this.oauth2UserService())
.oidcUserService(this.oidcUserService())
.customUserType(GitHubOAuth2User.class, "github")
)
);
} }
} }
---- ----
@ -123,12 +140,16 @@ 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 ->
.loginPage("/login/oauth2") oauth2Login
... .loginPage("/login/oauth2")
.authorizationEndpoint() ...
.baseUri("/login/oauth2/authorization") .authorizationEndpoint(authorizationEndpoint ->
.... authorizationEndpoint
.baseUri("/login/oauth2/authorization")
...
)
);
} }
} }
---- ----
@ -171,10 +192,14 @@ 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 ->
.redirectionEndpoint() oauth2Login
.baseUri("/login/oauth2/callback/*") .redirectionEndpoint(redirectionEndpoint ->
.... redirectionEndpoint
.baseUri("/login/oauth2/callback/*")
...
)
);
} }
} }
---- ----
@ -234,10 +259,14 @@ 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 ->
.userInfoEndpoint() oauth2Login
.userAuthoritiesMapper(this.userAuthoritiesMapper()) .userInfoEndpoint(userInfoEndpoint ->
... userInfoEndpoint
.userAuthoritiesMapper(this.userAuthoritiesMapper())
...
)
);
} }
private GrantedAuthoritiesMapper userAuthoritiesMapper() { private GrantedAuthoritiesMapper userAuthoritiesMapper() {
@ -280,7 +309,8 @@ public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http.oauth2Login(); http
.oauth2Login(withDefaults());
} }
@Bean @Bean
@ -308,10 +338,14 @@ 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 ->
.userInfoEndpoint() oauth2Login
.oidcUserService(this.oidcUserService()) .userInfoEndpoint(userInfoEndpoint ->
... userInfoEndpoint
.oidcUserService(this.oidcUserService())
...
)
);
} }
private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() { private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() {
@ -355,10 +389,14 @@ 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 ->
.userInfoEndpoint() oauth2Login
.customUserType(GitHubOAuth2User.class, "github") .userInfoEndpoint(userInfoEndpoint ->
... userInfoEndpoint
.customUserType(GitHubOAuth2User.class, "github")
...
)
);
} }
} }
---- ----
@ -469,10 +507,14 @@ 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 ->
.userInfoEndpoint() oauth2Login
.userService(this.oauth2UserService()) .userInfoEndpoint(userInfoEndpoint ->
... userInfoEndpoint
.userService(this.oauth2UserService())
...
)
);
} }
private OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService() { private OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService() {
@ -501,10 +543,14 @@ 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 ->
.userInfoEndpoint() oauth2Login
.oidcUserService(this.oidcUserService()) .userInfoEndpoint(userInfoEndpoint ->
... userInfoEndpoint
.oidcUserService(this.oidcUserService())
...
)
);
} }
private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() { private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() {

View File

@ -169,9 +169,11 @@ or in Java configuration
[source,java] [source,java]
---- ----
http http
.authorizeRequests() .authorizeRequests(authorizeRequests ->
.antMatchers("/user/{userId}/**").access("@webSecurity.checkUserId(authentication,#userId)") authorizeRequests
... .antMatchers("/user/{userId}/**").access("@webSecurity.checkUserId(authentication,#userId)")
...
);
---- ----
In both configurations URLs that match would pass in the path variable (and convert it) into checkUserId method. In both configurations URLs that match would pass in the path variable (and convert it) into checkUserId method.

View File

@ -137,12 +137,12 @@ How does Spring Security know that we want to require all users to be authentica
---- ----
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.authorizeRequests() .authorizeRequests(authorizeRequests ->
.anyRequest().authenticated() authorizeRequests
.and() .anyRequest().authenticated()
.formLogin() )
.and() .formLogin(withDefaults())
.httpBasic(); .httpBasic(withDefaults());
} }
---- ----
@ -163,10 +163,6 @@ You will notice that this configuration is quite similar the XML Namespace confi
</http> </http>
---- ----
The Java Configuration equivalent of closing an XML tag is expressed using the `and()` method which allows us to continue configuring the parent.
If you read the code it also makes sense.
I want to configure authorized requests __and__ configure form login __and__ configure HTTP Basic authentication.
[[jc-form]] [[jc-form]]
== Java Configuration and Form Login == Java Configuration and Form Login
You might be wondering where the login form came from when you were prompted to log in, since we made no mention of any HTML files or JSPs. You might be wondering where the login form came from when you were prompted to log in, since we made no mention of any HTML files or JSPs.
@ -180,12 +176,15 @@ To do so we can update our configuration as seen below:
---- ----
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.authorizeRequests() .authorizeRequests(authorizeRequests ->
.anyRequest().authenticated() authorizeRequests
.and() .anyRequest().authenticated()
.formLogin() )
.loginPage("/login") // <1> .formLogin(formLogin ->
.permitAll(); // <2> formLogin
.loginPage("/login") // <1>
.permitAll() // <2>
);
} }
---- ----
@ -245,14 +244,14 @@ For example:
---- ----
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.authorizeRequests() <1> .authorizeRequests(authorizeRequests -> // <1>
.antMatchers("/resources/**", "/signup", "/about").permitAll() <2> authorizeRequests
.antMatchers("/admin/**").hasRole("ADMIN") <3> .antMatchers("/resources/**", "/signup", "/about").permitAll() // <2>
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')") <4> .antMatchers("/admin/**").hasRole("ADMIN") // <3>
.anyRequest().authenticated() <5> .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')") // <4>
.and() .anyRequest().authenticated() // <5>
// ... )
.formLogin(); .formLogin(withDefaults());
} }
---- ----
@ -282,14 +281,15 @@ Similar to configuring login capabilities, however, you also have various option
---- ----
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.logout() <1> .logout(logout -> // <1>
.logoutUrl("/my/logout") <2> logout
.logoutSuccessUrl("/my/index") <3> .logoutUrl("/my/logout") // <2>
.logoutSuccessHandler(logoutSuccessHandler) <4> .logoutSuccessUrl("/my/index") // <3>
.invalidateHttpSession(true) <5> .logoutSuccessHandler(logoutSuccessHandler) // <4>
.addLogoutHandler(logoutHandler) <6> .invalidateHttpSession(true) // <5>
.deleteCookies(cookieNamesToClear) <7> .addLogoutHandler(logoutHandler) // <6>
.and() .deleteCookies(cookieNamesToClear) // <7>
)
... ...
} }
---- ----
@ -510,11 +510,14 @@ The first is a `WebSecurityConfigurerAdapter` that configures the app as a resou
```java ```java
protected void configure(HttpSecurity http) { protected void configure(HttpSecurity http) {
http http
.authorizeRequests() .authorizeRequests(authorizeRequests ->
.anyRequest().authenticated() authorizeRequests
.and() .anyRequest().authenticated()
.oauth2ResourceServer() )
.jwt(); .oauth2ResourceServer(oauth2ResourceServer ->
oauth2ResourceServer
.jwt(withDefaults())
);
} }
``` ```
@ -527,13 +530,18 @@ 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 ->
.mvcMatchers("/messages/**").hasAuthority("SCOPE_message:read") authorizeRequests
.anyRequest().authenticated() .mvcMatchers("/messages/**").hasAuthority("SCOPE_message:read")
.and() .anyRequest().authenticated()
.oauth2ResourceServer() )
.jwt() .oauth2ResourceServer(oauth2ResourceServer ->
.jwtAuthenticationConverter(myConverter()); oauth2ResourceServer
.jwt(jwt ->
jwt
.jwtAuthenticationConverter(myConverter())
)
);
} }
} }
``` ```
@ -565,12 +573,17 @@ 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 ->
.anyRequest().authenticated() authorizeRequests
.and() .anyRequest().authenticated()
.oauth2ResourceServer() )
.jwt() .oauth2ResourceServer(oauth2ResourceServer ->
.jwkSetUri("https://idp.example.com/.well-known/jwks.json"); oauth2ResourceServer
.jwt(jwt ->
jwt
.jwkSetUri("https://idp.example.com/.well-known/jwks.json")
)
);
} }
} }
``` ```
@ -587,12 +600,17 @@ More powerful than `jwkSetUri()` is `decoder()`, which will completely replace a
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 ->
.anyRequest().authenticated() authorizeRequests
.and() .anyRequest().authenticated()
.oauth2ResourceServer() )
.jwt() .oauth2ResourceServer(oauth2ResourceServer ->
.decoder(myCustomDecoder()); oauth2ResourceServer
.jwt(jwt ->
jwt
.decoder(myCustomDecoder())
)
);
} }
} }
``` ```
@ -627,13 +645,16 @@ 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 ->
.mvcMatchers("/contacts/**").hasAuthority("SCOPE_contacts") authorizeRequests
.mvcMatchers("/messages/**").hasAuthority("SCOPE_messages") .mvcMatchers("/contacts/**").hasAuthority("SCOPE_contacts")
.anyRequest().authenticated() .mvcMatchers("/messages/**").hasAuthority("SCOPE_messages")
.and() .anyRequest().authenticated()
.oauth2ResourceServer() )
.jwt(); .oauth2ResourceServer(oauth2ResourceServer ->
oauth2ResourceServer
.jwt(withDefaults())
);
} }
} }
``` ```
@ -659,12 +680,17 @@ 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 ->
.anyRequest().authenticated() authorizeRequests
.and() .anyRequest().authenticated()
.oauth2ResourceServer() )
.jwt() .oauth2ResourceServer(oauth2ResourceServer ->
.jwtAuthenticationConverter(grantedAuthoritiesExtractor()); oauth2ResourceServer
.jwt(jwt ->
jwt
.jwtAuthenticationConverter(grantedAuthoritiesExtractor())
)
);
} }
} }
@ -1078,10 +1104,11 @@ 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 ->
.anyRequest().hasRole("ADMIN") authorizeRequests
.and() .anyRequest().hasRole("ADMIN")
.httpBasic(); )
.httpBasic(withDefaults());
} }
} }
@ -1091,10 +1118,11 @@ public class MultiHttpSecurityConfig {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.authorizeRequests() .authorizeRequests(authorizeRequests ->
.anyRequest().authenticated() authorizeRequests
.and() .anyRequest().authenticated()
.formLogin(); )
.formLogin(withDefaults());
} }
} }
} }
@ -1221,15 +1249,17 @@ 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 ->
.anyRequest().authenticated() authorizeRequests
.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() { .anyRequest().authenticated()
public <O extends FilterSecurityInterceptor> O postProcess( .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
O fsi) { public <O extends FilterSecurityInterceptor> O postProcess(
fsi.setPublishAuthorizationSuccess(true); O fsi) {
return fsi; fsi.setPublishAuthorizationSuccess(true);
} return fsi;
}); }
})
);
} }
---- ----

View File

@ -20,14 +20,18 @@ 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 ->
.clientRegistrationRepository(this.clientRegistrationRepository()) oauth2Client
.authorizedClientRepository(this.authorizedClientRepository()) .clientRegistrationRepository(this.clientRegistrationRepository())
.authorizedClientService(this.authorizedClientService()) .authorizedClientRepository(this.authorizedClientRepository())
.authorizationCodeGrant() .authorizedClientService(this.authorizedClientService())
.authorizationRequestRepository(this.authorizationRequestRepository()) .authorizationCodeGrant(authorizationCodeGrant ->
.authorizationRequestResolver(this.authorizationRequestResolver()) authorizationCodeGrant
.accessTokenResponseClient(this.accessTokenResponseClient()); .authorizationRequestRepository(this.authorizationRequestRepository())
.authorizationRequestResolver(this.authorizationRequestResolver())
.accessTokenResponseClient(this.accessTokenResponseClient())
)
);
} }
} }
---- ----
@ -245,10 +249,14 @@ 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 ->
.authorizationCodeGrant() oauth2Client
.authorizationRequestRepository(this.cookieAuthorizationRequestRepository()) .authorizationCodeGrant(authorizationCodeGrant ->
... authorizationCodeGrant
.authorizationRequestRepository(this.cookieAuthorizationRequestRepository())
...
)
);
} }
private AuthorizationRequestRepository<OAuth2AuthorizationRequest> cookieAuthorizationRequestRepository() { private AuthorizationRequestRepository<OAuth2AuthorizationRequest> cookieAuthorizationRequestRepository() {
@ -285,14 +293,19 @@ 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 ->
.anyRequest().authenticated() authorizeRequests
.and() .anyRequest().authenticated()
.oauth2Login() )
.authorizationEndpoint() .oauth2Login(oauth2Login ->
.authorizationRequestResolver( oauth2Login
new CustomAuthorizationRequestResolver( .authorizationEndpoint(authorizationEndpoint ->
this.clientRegistrationRepository)); <1> authorizationEndpoint
.authorizationRequestResolver(
new CustomAuthorizationRequestResolver(
this.clientRegistrationRepository)) <1>
)
);
} }
} }
@ -422,10 +435,14 @@ 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 ->
.authorizationCodeGrant() oauth2Client
.accessTokenResponseClient(this.customAccessTokenResponseClient()) .authorizationCodeGrant(authorizationCodeGrant ->
... authorizationCodeGrant
.accessTokenResponseClient(this.customAccessTokenResponseClient())
...
)
);
} }
private OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> customAccessTokenResponseClient() { private OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> customAccessTokenResponseClient() {

View File

@ -285,10 +285,11 @@ 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 ->
.anyRequest().authenticated() authorizeRequests
.and() .anyRequest().authenticated()
.oauth2Login(); )
.oauth2Login(withDefaults());
} }
} }
---- ----
@ -310,10 +311,11 @@ public class OAuth2LoginConfig {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.authorizeRequests() .authorizeRequests(authorizeRequests ->
.anyRequest().authenticated() authorizeRequests
.and() .anyRequest().authenticated()
.oauth2Login(); )
.oauth2Login(withDefaults());
} }
} }
@ -358,10 +360,11 @@ public class OAuth2LoginConfig {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.authorizeRequests() .authorizeRequests(authorizeRequests ->
.anyRequest().authenticated() authorizeRequests
.and() .anyRequest().authenticated()
.oauth2Login(); )
.oauth2Login(withDefaults());
} }
} }

View File

@ -18,7 +18,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
// by default uses a Bean by the name of corsConfigurationSource // by default uses a Bean by the name of corsConfigurationSource
.cors().and() .cors(withDefaults())
... ...
} }
@ -59,7 +59,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
http http
// if Spring MVC is on classpath and no CorsConfigurationSource is provided, // if Spring MVC is on classpath and no CorsConfigurationSource is provided,
// Spring Security will use CORS configuration provided to Spring MVC // Spring Security will use CORS configuration provided to Spring MVC
.cors().and() .cors(withDefaults())
... ...
} }
} }

View File

@ -187,7 +187,9 @@ WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.csrf().disable(); .csrf(csrf ->
csrf.disable()
);
} }
} }
---- ----
@ -314,8 +316,10 @@ public class WebSecurityConfig extends
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.csrf() .csrf(csrf ->
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); csrf
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
);
} }
} }
---- ----
@ -391,8 +395,10 @@ WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.logout() .logout(logout ->
.logoutRequestMatcher(new AntPathRequestMatcher("/logout")); logout
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
);
} }
} }
---- ----

View File

@ -60,9 +60,15 @@ public class WebSecurityConfig extends
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
// ... // ...
.headers() .headers(headers ->
.frameOptions().sameOrigin() headers
.httpStrictTransportSecurity().disable(); .frameOptions(frameOptions ->
frameOptions.sameOrigin()
)
.httpStrictTransportSecurity(hsts ->
hsts.disable()
)
);
} }
} }
---- ----
@ -92,15 +98,17 @@ If you are using Spring Security's Java Configuration the following will only ad
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 ->
// do not use any default headers unless explicitly listed headers
.defaultsDisabled() // do not use any default headers unless explicitly listed
.cacheControl(); .defaultsDisabled()
} .cacheControl(withDefaults())
);
}
} }
---- ----
@ -126,12 +134,14 @@ If necessary, you can disable all of the HTTP Security response headers with the
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().disable(); .headers(headers ->
} headers.disable()
);
}
} }
---- ----
@ -182,14 +192,16 @@ Similarly, you can enable only cache control within Java Configuration with the
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 ->
.defaultsDisabled() headers
.cacheControl(); .defaultsDisabled()
} .cacheControl(withDefaults())
);
}
} }
---- ----
@ -263,14 +275,16 @@ If you want more control over the headers, you can explicitly specify the conten
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 ->
.defaultsDisabled() headers
.contentTypeOptions(); .defaultsDisabled()
} .contentTypeOptions(withDefaults())
);
}
} }
---- ----
@ -327,16 +341,20 @@ Similarly, you can enable only HSTS headers with Java Configuration:
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 ->
.httpStrictTransportSecurity() headers
.includeSubdomains(true) .httpStrictTransportSecurity(hsts ->
.preload(true) hsts
.maxAgeSeconds(31536000); .includeSubDomains(true)
} .preload(true)
.maxAgeInSeconds(31536000)
)
);
}
} }
---- ----
@ -399,16 +417,20 @@ Similarly, you can enable HPKP headers with Java Configuration:
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 ->
.httpPublicKeyPinning() headers
.includeSubdomains(true) .httpPublicKeyPinning(hpkp ->
.reportUri("https://example.net/pkp-report") hpkp
.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=", "E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g="; .includeSubDomains(true)
} .reportUri("https://example.net/pkp-report")
.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=", "E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=")
)
);
}
} }
---- ----
@ -461,14 +483,18 @@ 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 ->
.frameOptions() headers
.sameOrigin(); .frameOptions(frameOptions ->
} frameOptions
.sameOrigin()
)
);
}
} }
---- ----
@ -511,14 +537,18 @@ Similarly, you can customize XSS protection within Java Configuration with the f
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 ->
.xssProtection() headers
.block(false); .xssProtection(xssProtection ->
} xssProtection
.block(false)
)
);
}
} }
---- ----
@ -625,13 +655,18 @@ Similarly, you can enable the CSP header using Java configuration as shown below
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 ->
.contentSecurityPolicy("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/"); headers
} .contentSecurityPolicy(csp ->
csp
.policyDirectives("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/")
)
);
}
} }
---- ----
@ -643,14 +678,19 @@ To enable the CSP _'report-only'_ header, provide the following Java configurati
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 ->
.contentSecurityPolicy("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/") headers
.reportOnly(); .contentSecurityPolicy(csp ->
} csp
.policyDirectives("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/")
.reportOnly()
)
);
}
} }
---- ----
@ -707,13 +747,18 @@ Similarly, you can enable the Referrer Policy header using Java configuration as
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 ->
.referrerPolicy(ReferrerPolicy.SAME_ORIGIN); headers
} .referrerPolicy(referrerPolicy ->
referrerPolicy
.policy(ReferrerPolicy.SAME_ORIGIN)
)
);
}
} }
---- ----
@ -757,13 +802,15 @@ Similarly, you can enable the Feature Policy header using Java configuration as
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 ->
.featurePolicy("geolocation 'self'"); headers
} .featurePolicy("geolocation 'self'")
);
}
} }
---- ----
@ -804,13 +851,15 @@ Similarly, the headers could be added to the response using Java Configuration a
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 ->
.addHeaderWriter(new StaticHeadersWriter("X-Custom-Security-Header","header-value")); headers
} .addHeaderWriter(new StaticHeadersWriter("X-Custom-Security-Header","header-value"))
);
}
} }
---- ----
@ -849,13 +898,15 @@ We could also restrict framing of content to the same origin with Java configura
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 ->
.addHeaderWriter(new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN)); headers
} .addHeaderWriter(new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN))
);
}
} }
---- ----
@ -903,17 +954,21 @@ We could also prevent framing of content to the log in page using java configura
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 {
RequestMatcher matcher = new AntPathRequestMatcher("/login"); RequestMatcher matcher = new AntPathRequestMatcher("/login");
DelegatingRequestMatcherHeaderWriter headerWriter = DelegatingRequestMatcherHeaderWriter headerWriter =
new DelegatingRequestMatcherHeaderWriter(matcher,new XFrameOptionsHeaderWriter()); new DelegatingRequestMatcherHeaderWriter(matcher,new XFrameOptionsHeaderWriter());
http http
// ... // ...
.headers() .headers(headers ->
.frameOptions().disabled() headers
.addHeaderWriter(headerWriter); .frameOptions(frameOptions ->
} frameOptions.disable()
)
.addHeaderWriter(headerWriter)
);
}
} }
---- ----

View File

@ -323,9 +323,13 @@ public class WebSecurityConfig extends
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
// ... // ...
.headers() .headers(headers ->
.frameOptions() headers
.sameOrigin(); .frameOptions(frameOptions ->
frameOptions
.sameOrigin()
)
);
} }
} }
---- ----
@ -356,18 +360,23 @@ public class WebSecurityConfig
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
.csrf() .csrf(csrf ->
// ignore our stomp endpoints since they are protected using Stomp headers csrf
.ignoringAntMatchers("/chat/**") // ignore our stomp endpoints since they are protected using Stomp headers
.and() .ignoringAntMatchers("/chat/**")
.headers() )
// allow same origin to frame our site to support iframe SockJS .headers(headers ->
.frameOptions().sameOrigin() headers
.and() // allow same origin to frame our site to support iframe SockJS
.authorizeRequests() .frameOptions(frameOptions ->
frameOptions
.sameOrigin()
)
)
.authorizeRequests(authorizeRequests ->
...
)
... ...
---- ----