public class ServerHttpSecurity
extends java.lang.Object
ServerHttpSecurity is similar to Spring Security's HttpSecurity but for WebFlux.
It allows configuring web based security for specific http requests. By default it will be applied
to all requests, but can be restricted using securityMatcher(ServerWebExchangeMatcher) or
other similar methods.
A minimal configuration can be found below:
@EnableWebFluxSecurity
public class MyMinimalSecurityConfiguration {
@Bean
public MapReactiveUserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
return new MapReactiveUserDetailsService(user);
}
}
Below is the same as our minimal configuration, but explicitly declaring the
ServerHttpSecurity.
@EnableWebFluxSecurity
public class MyExplicitSecurityConfiguration {
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange()
.anyExchange().authenticated()
.and()
.httpBasic().and()
.formLogin();
return http.build();
}
@Bean
public MapReactiveUserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
return new MapReactiveUserDetailsService(user);
}
}| Modifier and Type | Class and Description |
|---|---|
class |
ServerHttpSecurity.AuthorizeExchangeSpec
Configures authorization
|
class |
ServerHttpSecurity.CorsSpec
Configures CORS support within Spring Security.
|
class |
ServerHttpSecurity.CsrfSpec
Configures CSRF Protection
|
class |
ServerHttpSecurity.ExceptionHandlingSpec
Configures exception handling
|
class |
ServerHttpSecurity.FormLoginSpec
Configures Form Based authentication
|
class |
ServerHttpSecurity.HeaderSpec
Configures HTTP Response Headers.
|
class |
ServerHttpSecurity.HttpBasicSpec
Configures HTTP Basic Authentication
|
class |
ServerHttpSecurity.HttpsRedirectSpec
Configures HTTPS redirection rules
|
class |
ServerHttpSecurity.LogoutSpec
Configures log out
|
class |
ServerHttpSecurity.OAuth2ClientSpec |
class |
ServerHttpSecurity.OAuth2LoginSpec |
class |
ServerHttpSecurity.OAuth2ResourceServerSpec
Configures OAuth2 Resource Server Support
|
class |
ServerHttpSecurity.RequestCacheSpec
Configures the request cache which is used when a flow is interrupted (i.e.
|
| Modifier | Constructor and Description |
|---|---|
protected |
ServerHttpSecurity() |
| Modifier and Type | Method and Description |
|---|---|
ServerHttpSecurity |
addFilterAt(org.springframework.web.server.WebFilter webFilter,
SecurityWebFiltersOrder order)
Adds a
WebFilter at a specific position. |
ServerHttpSecurity |
authenticationManager(ReactiveAuthenticationManager manager)
Configure the default authentication manager.
|
ServerHttpSecurity.AuthorizeExchangeSpec |
authorizeExchange()
Configures authorization.
|
SecurityWebFilterChain |
build()
Builds the
SecurityWebFilterChain |
ServerHttpSecurity.CorsSpec |
cors()
Configures CORS headers.
|
ServerHttpSecurity.CsrfSpec |
csrf()
Configures CSRF Protection
which is enabled by default.
|
ServerHttpSecurity.ExceptionHandlingSpec |
exceptionHandling()
Configures exception handling (i.e.
|
ServerHttpSecurity.FormLoginSpec |
formLogin()
Configures form based authentication.
|
ServerHttpSecurity.HeaderSpec |
headers()
Configures HTTP Response Headers.
|
static ServerHttpSecurity |
http()
Creates a new instance.
|
ServerHttpSecurity.HttpBasicSpec |
httpBasic()
Configures HTTP Basic authentication.
|
ServerHttpSecurity.LogoutSpec |
logout()
Configures log out.
|
ServerHttpSecurity.OAuth2ClientSpec |
oauth2Client()
Configures the OAuth2 client.
|
ServerHttpSecurity.OAuth2LoginSpec |
oauth2Login() |
ServerHttpSecurity.OAuth2ResourceServerSpec |
oauth2ResourceServer() |
ServerHttpSecurity.HttpsRedirectSpec |
redirectToHttps()
Configures HTTPS redirection rules.
|
ServerHttpSecurity.RequestCacheSpec |
requestCache()
Configures the request cache which is used when a flow is interrupted (i.e.
|
ServerHttpSecurity |
securityContextRepository(ServerSecurityContextRepository securityContextRepository)
The strategy used with
ReactorContextWebFilter. |
ServerHttpSecurity |
securityMatcher(ServerWebExchangeMatcher matcher)
The ServerExchangeMatcher that determines which requests apply to this HttpSecurity instance.
|
protected void |
setApplicationContext(org.springframework.context.ApplicationContext applicationContext) |
public ServerHttpSecurity securityMatcher(ServerWebExchangeMatcher matcher)
matcher - the ServerExchangeMatcher that determines which requests apply to this HttpSecurity instance.
Default is all requests.ServerHttpSecurity to continue configuringpublic ServerHttpSecurity addFilterAt(org.springframework.web.server.WebFilter webFilter, SecurityWebFiltersOrder order)
WebFilter at a specific position.webFilter - the WebFilter to addorder - the place to insert the WebFilterServerHttpSecurity to continue configuringpublic ServerHttpSecurity securityContextRepository(ServerSecurityContextRepository securityContextRepository)
ReactorContextWebFilter. It does not impact how the SecurityContext is
saved which is configured on a per AuthenticationWebFilter basis.securityContextRepository - the repository to useServerHttpSecurity to continue configuringpublic ServerHttpSecurity.HttpsRedirectSpec redirectToHttps()
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
// ...
.redirectToHttps();
return http.build();
}
Then all non-HTTPS requests will be redirected to HTTPS.
Typically, all requests should be HTTPS; however, the focus for redirection can also be narrowed:
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
// ...
.redirectToHttps()
.httpsRedirectWhen(serverWebExchange ->
serverWebExchange.getRequest().getHeaders().containsKey("X-Requires-Https"))
return http.build();
}
ServerHttpSecurity.HttpsRedirectSpec to customizepublic ServerHttpSecurity.CsrfSpec csrf()
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
// ...
.csrf().disabled();
return http.build();
}
Additional configuration options can be seen below:
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
// ...
.csrf()
// Handle CSRF failures
.accessDeniedHandler(accessDeniedHandler)
// Custom persistence of CSRF Token
.csrfTokenRepository(csrfTokenRepository)
// custom matching when CSRF protection is enabled
.requireCsrfProtectionMatcher(matcher);
return http.build();
}
ServerHttpSecurity.CsrfSpec to customizepublic ServerHttpSecurity.CorsSpec cors()
CorsConfigurationSource Bean is found, it will be used
to create a CorsWebFilter. If ServerHttpSecurity.CorsSpec.configurationSource(CorsConfigurationSource) is invoked
it will be used instead. If neither has been configured, the Cors configuration will do nothing.ServerHttpSecurity.CorsSpec to customizepublic ServerHttpSecurity.HttpBasicSpec httpBasic()
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
// ...
.httpBasic()
// used for authenticating the credentials
.authenticationManager(authenticationManager)
// Custom persistence of the authentication
.securityContextRepository(securityContextRepository);
return http.build();
}
ServerHttpSecurity.HttpBasicSpec to customizepublic ServerHttpSecurity.FormLoginSpec formLogin()
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
// ...
.formLogin()
// used for authenticating the credentials
.authenticationManager(authenticationManager)
// Custom persistence of the authentication
.securityContextRepository(securityContextRepository)
// expect a log in page at "/authenticate"
// a POST "/authenticate" is where authentication occurs
// error page at "/authenticate?error"
.formLogin("/authenticate");
return http.build();
}
ServerHttpSecurity.FormLoginSpec to customizepublic ServerHttpSecurity.OAuth2LoginSpec oauth2Login()
public ServerHttpSecurity.OAuth2ClientSpec oauth2Client()
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
// ...
.oauth2Client()
.clientRegistrationRepository(clientRegistrationRepository)
.authorizedClientRepository(authorizedClientRepository);
return http.build();
}
ServerHttpSecurity.OAuth2ClientSpec to customizepublic ServerHttpSecurity.OAuth2ResourceServerSpec oauth2ResourceServer()
public ServerHttpSecurity.HeaderSpec headers()
Cache-Control: no-cache, no-store, max-age=0, must-revalidate Pragma: no-cache Expires: 0 X-Content-Type-Options: nosniff Strict-Transport-Security: max-age=31536000 ; includeSubDomains X-Frame-Options: DENY X-XSS-Protection: 1; mode=blocksuch that "Strict-Transport-Security" is only added on secure requests. An example configuration is provided below:
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
// ...
.headers()
// customize frame options to be same origin
.frameOptions()
.mode(XFrameOptionsServerHttpHeadersWriter.Mode.SAMEORIGIN)
.and()
// disable cache control
.cache().disable();
return http.build();
}
ServerHttpSecurity.HeaderSpec to customizepublic ServerHttpSecurity.ExceptionHandlingSpec exceptionHandling()
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
// ...
.exceptionHandling()
// customize how to request for authentication
.authenticationEntryPoint(entryPoint);
return http.build();
}
ServerHttpSecurity.ExceptionHandlingSpec to customizepublic ServerHttpSecurity.AuthorizeExchangeSpec authorizeExchange()
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
// ...
.authorizeExchange()
// any URL that starts with /admin/ requires the role "ROLE_ADMIN"
.pathMatchers("/admin/**").hasRole("ADMIN")
// a POST to /users requires the role "USER_POST"
.pathMatchers(HttpMethod.POST, "/users").hasAuthority("USER_POST")
// a request to /users/{username} requires the current authentication's username
// to be equal to the {username}
.pathMatchers("/users/{username}").access((authentication, context) ->
authentication
.map(Authentication::getName)
.map(username -> username.equals(context.getVariables().get("username")))
.map(AuthorizationDecision::new)
)
// allows providing a custom matching strategy that requires the role "ROLE_CUSTOM"
.matchers(customMatcher).hasRole("CUSTOM")
// any other request requires the user to be authenticated
.anyExchange().authenticated();
return http.build();
}
ServerHttpSecurity.AuthorizeExchangeSpec to customizepublic ServerHttpSecurity.LogoutSpec logout()
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
// ...
.logout()
// configures how log out is done
.logoutHandler(logoutHandler)
// log out will be performed on POST /signout
.logoutUrl("/signout")
// configure what is done on logout success
.logoutSuccessHandler(successHandler);
return http.build();
}
ServerHttpSecurity.LogoutSpec to customizepublic ServerHttpSecurity.RequestCacheSpec requestCache()
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
// ...
.requestCache()
// configures how the request is cached
.requestCache(requestCache);
return http.build();
}
ServerHttpSecurity.RequestCacheSpec to customizepublic ServerHttpSecurity authenticationManager(ReactiveAuthenticationManager manager)
manager - the authentication manager to useServerHttpSecurity to customizepublic SecurityWebFilterChain build()
SecurityWebFilterChainpublic static ServerHttpSecurity http()
ServerHttpSecurity instanceprotected void setApplicationContext(org.springframework.context.ApplicationContext applicationContext)
throws org.springframework.beans.BeansException
org.springframework.beans.BeansException