Class HttpSecurity
- All Implemented Interfaces:
SecurityBuilder<DefaultSecurityFilterChain>,HttpSecurityBuilder<HttpSecurity>
HttpSecurity is similar to Spring Security's XML <http> element in the
namespace configuration. It allows configuring web based security for specific http
requests. By default it will be applied to all requests, but can be restricted using
#requestMatcher(RequestMatcher) or other similar methods.
Example Usage
The most basic form based configuration can be seen below. The configuration will require that any URL that is requested will require a User with the role "ROLE_USER". It also defines an in memory authentication scheme with a user that has the username "user", the password "password", and the role "ROLE_USER". For additional examples, refer to the Java Doc of individual methods onHttpSecurity.
@Configuration
@EnableWebSecurity
public class FormLoginSecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests().requestMatchers("/**").hasRole("USER").and().formLogin();
return http.build();
}
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
}
- Since:
- 3.2
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionclassAllows mapping HTTP requests that thisHttpSecuritywill be used for -
Constructor Summary
ConstructorsConstructorDescriptionHttpSecurity(ObjectPostProcessor<Object> objectPostProcessor, AuthenticationManagerBuilder authenticationBuilder, Map<Class<?>, Object> sharedObjects) Deprecated, for removal: This API element is subject to removal in a future version.HttpSecurity(ObjectPostProcessor<Object> objectPostProcessor, AuthenticationManagerBuilder authenticationBuilder, Map<Class<?>, Object> sharedObjects) Creates a new instance -
Method Summary
Modifier and TypeMethodDescriptionaddFilter(jakarta.servlet.Filter filter) Adds aFilterthat must be an instance of or extend one of the Filters provided within the Security framework.addFilterAfter(jakarta.servlet.Filter filter, Class<? extends jakarta.servlet.Filter> afterFilter) Allows adding aFilterafter one of the knownFilterclasses.addFilterAt(jakarta.servlet.Filter filter, Class<? extends jakarta.servlet.Filter> atFilter) Adds the Filter at the location of the specified Filter class.addFilterBefore(jakarta.servlet.Filter filter, Class<? extends jakarta.servlet.Filter> beforeFilter) Allows adding aFilterbefore one of the knownFilterclasses.Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.anonymous(Customizer<AnonymousConfigurer<HttpSecurity>> anonymousCustomizer) Allows configuring how an anonymous user is represented.authenticationManager(AuthenticationManager authenticationManager) Configure the defaultAuthenticationManager.authenticationProvider(AuthenticationProvider authenticationProvider) Allows adding an additionalAuthenticationProviderto be usedDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.authorizeHttpRequests(Customizer<AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizationManagerRequestMatcherRegistry> authorizeHttpRequestsCustomizer) Allows restricting access based upon theHttpServletRequestusingRequestMatcherimplementations (i.e.Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.authorizeRequests(Customizer<ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry> authorizeRequestsCustomizer) Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.protected voidInvoked prior to invoking eachSecurityConfigurer.configure(SecurityBuilder)method.cors()Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.cors(Customizer<CorsConfigurer<HttpSecurity>> corsCustomizer) Adds aCorsFilterto be used.csrf()Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.csrf(Customizer<CsrfConfigurer<HttpSecurity>> csrfCustomizer) Enables CSRF protection.Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.exceptionHandling(Customizer<ExceptionHandlingConfigurer<HttpSecurity>> exceptionHandlingCustomizer) Allows configuring exception handling.Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.formLogin(Customizer<FormLoginConfigurer<HttpSecurity>> formLoginCustomizer) Specifies to support form based authentication.headers()Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.headers(Customizer<HeadersConfigurer<HttpSecurity>> headersCustomizer) Adds the Security headers to the response.Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.httpBasic(Customizer<HttpBasicConfigurer<HttpSecurity>> httpBasicCustomizer) Configures HTTP Basic authentication.jee()Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.jee(Customizer<JeeConfigurer<HttpSecurity>> jeeCustomizer) Configures container based pre authentication.logout()Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.logout(Customizer<LogoutConfigurer<HttpSecurity>> logoutCustomizer) Provides logout support.Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.oauth2Client(Customizer<OAuth2ClientConfigurer<HttpSecurity>> oauth2ClientCustomizer) Configures OAuth 2.0 Client support.Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.oauth2Login(Customizer<OAuth2LoginConfigurer<HttpSecurity>> oauth2LoginCustomizer) Configures authentication support using an OAuth 2.0 and/or OpenID Connect 1.0 Provider.Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.oauth2ResourceServer(Customizer<OAuth2ResourceServerConfigurer<HttpSecurity>> oauth2ResourceServerCustomizer) Configures OAuth 2.0 Resource Server support.oidcLogout(Customizer<OidcLogoutConfigurer<HttpSecurity>> oidcLogoutCustomizer) oneTimeTokenLogin(Customizer<OneTimeTokenLoginConfigurer<HttpSecurity>> oneTimeTokenLoginConfigurerCustomizer) Configures One-Time Token Login Support.passwordManagement(Customizer<PasswordManagementConfigurer<HttpSecurity>> passwordManagementCustomizer) Adds support for the password management.protected DefaultSecurityFilterChainSubclasses must implement this method to build the object that is being returned.Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.portMapper(Customizer<PortMapperConfigurer<HttpSecurity>> portMapperCustomizer) Allows configuring aPortMapperthat is available fromAbstractConfiguredSecurityBuilder.getSharedObject(Class).redirectToHttps(Customizer<HttpsRedirectConfigurer<HttpSecurity>> httpsRedirectConfigurerCustomizer) Configures channel security.Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.rememberMe(Customizer<RememberMeConfigurer<HttpSecurity>> rememberMeCustomizer) Allows configuring of Remember Me authentication.Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.requestCache(Customizer<RequestCacheConfigurer<HttpSecurity>> requestCacheCustomizer) Allows configuring the Request Cache.Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.requiresChannel(Customizer<ChannelSecurityConfigurer<HttpSecurity>.ChannelRequestMatcherRegistry> requiresChannelCustomizer) Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.saml2Login(Customizer<Saml2LoginConfigurer<HttpSecurity>> saml2LoginCustomizer) Configures authentication support using an SAML 2.0 Service Provider.Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.saml2Logout(Customizer<Saml2LogoutConfigurer<HttpSecurity>> saml2LogoutCustomizer) Configures logout support for an SAML 2.0 Relying Party.Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.saml2Metadata(Customizer<Saml2MetadataConfigurer<HttpSecurity>> saml2MetadataConfigurer) Configures a SAML 2.0 metadata endpoint that presents relying party configurations in an<md:EntityDescriptor>payload.Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.securityContext(Customizer<SecurityContextConfigurer<HttpSecurity>> securityContextCustomizer) Sets up management of theSecurityContexton theSecurityContextHolderbetweenHttpServletRequest's.securityMatcher(String... patterns) Allows configuring theHttpSecurityto only be invoked when matching the provided pattern.securityMatcher(RequestMatcher requestMatcher) Allows configuring theHttpSecurityto only be invoked when matching the providedRequestMatcher.Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.securityMatchers(Customizer<HttpSecurity.RequestMatcherConfigurer> requestMatcherCustomizer) Allows specifying whichHttpServletRequestinstances thisHttpSecuritywill be invoked on.Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.servletApi(Customizer<ServletApiConfigurer<HttpSecurity>> servletApiCustomizer) Integrates theHttpServletRequestmethods with the values found on theSecurityContext.Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.sessionManagement(Customizer<SessionManagementConfigurer<HttpSecurity>> sessionManagementCustomizer) Allows configuring of Session Management.<C> voidsetSharedObject(Class<C> sharedType, C object) Sets an object that is shared by multipleSecurityConfigurer.userDetailsService(UserDetailsService userDetailsService) Allows adding an additionalUserDetailsServiceto be usedwebAuthn(Customizer<WebAuthnConfigurer<HttpSecurity>> webAuthn) Specifies webAuthn/passkeys based authentication.x509()Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0.x509(Customizer<X509Configurer<HttpSecurity>> x509Customizer) Configures X509 based pre authentication.Methods inherited from class org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder
apply, beforeInit, doBuild, getConfigurer, getConfigurers, getOrBuild, getSharedObject, getSharedObjects, objectPostProcessor, postProcess, removeConfigurer, removeConfigurers, withMethods inherited from class org.springframework.security.config.annotation.AbstractSecurityBuilder
build, getObjectMethods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface org.springframework.security.config.annotation.web.HttpSecurityBuilder
getConfigurer, getSharedObject, removeConfigurerMethods inherited from interface org.springframework.security.config.annotation.SecurityBuilder
build
-
Constructor Details
-
HttpSecurity
public HttpSecurity(ObjectPostProcessor<Object> objectPostProcessor, AuthenticationManagerBuilder authenticationBuilder, Map<Class<?>, Object> sharedObjects) Creates a new instance- Parameters:
objectPostProcessor- theObjectPostProcessorthat should be usedauthenticationBuilder- theAuthenticationManagerBuilderto use for additional updatessharedObjects- the shared Objects to initialize theHttpSecuritywith- See Also:
-
HttpSecurity
@Deprecated(since="6.4", forRemoval=true) public HttpSecurity(ObjectPostProcessor<Object> objectPostProcessor, AuthenticationManagerBuilder authenticationBuilder, Map<Class<?>, Object> sharedObjects) Deprecated, for removal: This API element is subject to removal in a future version.
-
-
Method Details
-
headers
@Deprecated(since="6.1", forRemoval=true) public HeadersConfigurer<HttpSecurity> headers() throws ExceptionDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. Useheaders(Customizer)orheaders(Customizer.withDefaults())to stick with defaults. See the documentation for more details.Adds the Security headers to the response. This is activated by default when usingEnableWebSecurity. Accepting the default provided byEnableWebSecurityor only invokingheaders()without invoking additional methods on it, is the equivalent of:@Configuration @EnableWebSecurity public class CsrfSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .headers() .contentTypeOptions() .and() .xssProtection() .and() .cacheControl() .and() .httpStrictTransportSecurity() .and() .frameOptions() .and() ...; return http.build(); } }You can disable the headers using the following:@Configuration @EnableWebSecurity public class CsrfSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .headers().disable() ...; return http.build(); } }You can enable only a few of the headers by first invokingHeadersConfigurer.defaultsDisabled()and then invoking the appropriate methods on theheaders()result. For example, the following will enableHeadersConfigurer.cacheControl()andHeadersConfigurer.frameOptions()only.@Configuration @EnableWebSecurity public class CsrfSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .headers() .defaultsDisabled() .cacheControl() .and() .frameOptions() .and() ...; return http.build(); } }You can also choose to keep the defaults but explicitly disable a subset of headers. For example, the following will enable all the default headers exceptHeadersConfigurer.frameOptions().@Configuration @EnableWebSecurity public class CsrfSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .headers() .frameOptions() .disable() .and() ...; return http.build(); } }- Returns:
- the
HeadersConfigurerfor further customizations - Throws:
Exception- See Also:
-
headers
public HttpSecurity headers(Customizer<HeadersConfigurer<HttpSecurity>> headersCustomizer) throws Exception Adds the Security headers to the response. This is activated by default when usingEnableWebSecurity.Example Configurations
Accepting the default provided byEnableWebSecurityor only invokingheaders()without invoking additional methods on it, is the equivalent of:@Configuration @EnableWebSecurity public class CsrfSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .headers((headers) -> headers .contentTypeOptions(withDefaults()) .xssProtection(withDefaults()) .cacheControl(withDefaults()) .httpStrictTransportSecurity(withDefaults()) .frameOptions(withDefaults() ); return http.build(); } }You can disable the headers using the following:@Configuration @EnableWebSecurity public class CsrfSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .headers((headers) -> headers.disable()); return http.build(); } }You can enable only a few of the headers by first invokingHeadersConfigurer.defaultsDisabled()and then invoking the appropriate methods on theheaders()result. For example, the following will enableHeadersConfigurer.cacheControl()andHeadersConfigurer.frameOptions()only.@Configuration @EnableWebSecurity public class CsrfSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .headers((headers) -> headers .defaultsDisabled() .cacheControl(withDefaults()) .frameOptions(withDefaults()) ); return http.build(); } }You can also choose to keep the defaults but explicitly disable a subset of headers. For example, the following will enable all the default headers exceptHeadersConfigurer.frameOptions().@Configuration @EnableWebSecurity public class CsrfSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .headers((headers) -> headers .frameOptions((frameOptions) -> frameOptions.disable()) ); return http.build(); } }- Parameters:
headersCustomizer- theCustomizerto provide more options for theHeadersConfigurer- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception
-
cors
@Deprecated(since="6.1", forRemoval=true) public CorsConfigurer<HttpSecurity> cors() throws ExceptionDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. Usecors(Customizer)orcors(Customizer.withDefaults())to stick with defaults. See the documentation for more details.Adds aCorsFilterto be used. If a bean by the name of corsFilter is provided, thatCorsFilteris used. Else if corsConfigurationSource is defined, then thatCorsConfigurationis used. Otherwise, if Spring MVC is on the classpath aHandlerMappingIntrospectoris used.- Returns:
- the
CorsConfigurerfor customizations - Throws:
Exception
-
cors
Adds aCorsFilterto be used. If a bean by the name of corsFilter is provided, thatCorsFilteris used. Else if corsConfigurationSource is defined, then thatCorsConfigurationis used. Otherwise, if Spring MVC is on the classpath aHandlerMappingIntrospectoris used. You can enable CORS using:@Configuration @EnableWebSecurity public class CorsSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .cors(withDefaults()); return http.build(); } }- Parameters:
corsCustomizer- theCustomizerto provide more options for theCorsConfigurer- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception
-
sessionManagement
@Deprecated(since="6.1", forRemoval=true) public SessionManagementConfigurer<HttpSecurity> sessionManagement() throws ExceptionDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. UsesessionManagement(Customizer)orsessionManagement(Customizer.withDefaults())to stick with defaults. See the documentation for more details.Allows configuring of Session Management.Example Configuration
The following configuration demonstrates how to enforce that only a single instance of a user is authenticated at a time. If a user authenticates with the username "user" without logging out and an attempt to authenticate with "user" is made the first session will be forcibly terminated and sent to the "/login?expired" URL.@Configuration @EnableWebSecurity public class SessionManagementSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeRequests().anyRequest().hasRole("USER").and().formLogin() .permitAll().and().sessionManagement().maximumSessions(1) .expiredUrl("/login?expired"); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }When usingSessionManagementConfigurer.maximumSessions(int), do not forget to configureHttpSessionEventPublisherfor the application to ensure that expired sessions are cleaned up. In a web.xml this can be configured using the following:<listener> <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class> </listener>Alternatively,AbstractSecurityWebApplicationInitializer.enableHttpSessionEventPublisher()could return true.- Returns:
- the
SessionManagementConfigurerfor further customizations - Throws:
Exception
-
sessionManagement
public HttpSecurity sessionManagement(Customizer<SessionManagementConfigurer<HttpSecurity>> sessionManagementCustomizer) throws Exception Allows configuring of Session Management.Example Configuration
The following configuration demonstrates how to enforce that only a single instance of a user is authenticated at a time. If a user authenticates with the username "user" without logging out and an attempt to authenticate with "user" is made the first session will be forcibly terminated and sent to the "/login?expired" URL.@Configuration @EnableWebSecurity public class SessionManagementSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .anyRequest().hasRole("USER") ) .formLogin((formLogin) -> formLogin .permitAll() ) .sessionManagement((sessionManagement) -> sessionManagement .sessionConcurrency((sessionConcurrency) -> sessionConcurrency .maximumSessions(1) .expiredUrl("/login?expired") ) ); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }When usingSessionManagementConfigurer.maximumSessions(int), do not forget to configureHttpSessionEventPublisherfor the application to ensure that expired sessions are cleaned up. In a web.xml this can be configured using the following:<listener> <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class> </listener>Alternatively,AbstractSecurityWebApplicationInitializer.enableHttpSessionEventPublisher()could return true.- Parameters:
sessionManagementCustomizer- theCustomizerto provide more options for theSessionManagementConfigurer- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception
-
portMapper
@Deprecated(since="6.1", forRemoval=true) public PortMapperConfigurer<HttpSecurity> portMapper() throws ExceptionDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. UseportMapper(Customizer)orportMapper(Customizer.withDefaults())to stick with defaults. See the documentation for more details.Allows configuring aPortMapperthat is available fromAbstractConfiguredSecurityBuilder.getSharedObject(Class). Other providedSecurityConfigurerobjects use this configuredPortMapperas a defaultPortMapperwhen redirecting from HTTP to HTTPS or from HTTPS to HTTP (for example when used in combination withrequiresChannel(). By default Spring Security uses aPortMapperImplwhich maps the HTTP port 8080 to the HTTPS port 8443 and the HTTP port of 80 to the HTTPS port of 443.Example Configuration
The following configuration will ensure that redirects within Spring Security from HTTP of a port of 9090 will redirect to HTTPS port of 9443 and the HTTP port of 80 to the HTTPS port of 443.@Configuration @EnableWebSecurity public class PortMapperSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeRequests().requestMatchers("/**").hasRole("USER").and().formLogin() .permitAll().and() // Example portMapper() configuration .portMapper().http(9090).mapsTo(9443).http(80).mapsTo(443); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }- Returns:
- the
PortMapperConfigurerfor further customizations - Throws:
Exception- See Also:
-
portMapper
public HttpSecurity portMapper(Customizer<PortMapperConfigurer<HttpSecurity>> portMapperCustomizer) throws Exception Allows configuring aPortMapperthat is available fromAbstractConfiguredSecurityBuilder.getSharedObject(Class). Other providedSecurityConfigurerobjects use this configuredPortMapperas a defaultPortMapperwhen redirecting from HTTP to HTTPS or from HTTPS to HTTP (for example when used in combination withrequiresChannel(). By default Spring Security uses aPortMapperImplwhich maps the HTTP port 8080 to the HTTPS port 8443 and the HTTP port of 80 to the HTTPS port of 443.Example Configuration
The following configuration will ensure that redirects within Spring Security from HTTP of a port of 9090 will redirect to HTTPS port of 9443 and the HTTP port of 80 to the HTTPS port of 443.@Configuration @EnableWebSecurity public class PortMapperSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .requiresChannel((requiresChannel) -> requiresChannel .anyRequest().requiresSecure() ) .portMapper((portMapper) -> portMapper .http(9090).mapsTo(9443) .http(80).mapsTo(443) ); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }- Parameters:
portMapperCustomizer- theCustomizerto provide more options for thePortMapperConfigurer- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception- See Also:
-
jee
Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. Usejee(Customizer)orjee(Customizer.withDefaults())to stick with defaults. See the documentation for more details.Configures container based pre authentication. In this case, authentication is managed by the Servlet Container.Example Configuration
The following configuration will use the principal found on theHttpServletRequestand if the user is in the role "ROLE_USER" or "ROLE_ADMIN" will add that to the resultingAuthentication.@Configuration @EnableWebSecurity public class JeeSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeRequests().requestMatchers("/**").hasRole("USER").and() // Example jee() configuration .jee().mappableRoles("USER", "ADMIN"); return http.build(); } }Developers wishing to use pre authentication with the container will need to ensure their web.xml configures the security constraints. For example, the web.xml (there is no equivalent Java based configuration supported by the Servlet specification) might look like:<login-config> <auth-method>FORM</auth-method> <form-login-config> <form-login-page>/login</form-login-page> <form-error-page>/login?error</form-error-page> </form-login-config> </login-config> <security-role> <role-name>ROLE_USER</role-name> </security-role> <security-constraint> <web-resource-collection> <web-resource-name>Public</web-resource-name> <description>Matches unconstrained pages</description> <url-pattern>/login</url-pattern> <url-pattern>/logout</url-pattern> <url-pattern>/resources/*</url-pattern> </web-resource-collection> </security-constraint> <security-constraint> <web-resource-collection> <web-resource-name>Secured Areas</web-resource-name> <url-pattern>/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>ROLE_USER</role-name> </auth-constraint> </security-constraint>Last you will need to configure your container to contain the user with the correct roles. This configuration is specific to the Servlet Container, so consult your Servlet Container's documentation.- Returns:
- the
JeeConfigurerfor further customizations - Throws:
Exception
-
jee
Configures container based pre authentication. In this case, authentication is managed by the Servlet Container.Example Configuration
The following configuration will use the principal found on theHttpServletRequestand if the user is in the role "ROLE_USER" or "ROLE_ADMIN" will add that to the resultingAuthentication.@Configuration @EnableWebSecurity public class JeeSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/**").hasRole("USER") ) .jee((jee) -> jee .mappableRoles("USER", "ADMIN") ); return http.build(); } }Developers wishing to use pre authentication with the container will need to ensure their web.xml configures the security constraints. For example, the web.xml (there is no equivalent Java based configuration supported by the Servlet specification) might look like:<login-config> <auth-method>FORM</auth-method> <form-login-config> <form-login-page>/login</form-login-page> <form-error-page>/login?error</form-error-page> </form-login-config> </login-config> <security-role> <role-name>ROLE_USER</role-name> </security-role> <security-constraint> <web-resource-collection> <web-resource-name>Public</web-resource-name> <description>Matches unconstrained pages</description> <url-pattern>/login</url-pattern> <url-pattern>/logout</url-pattern> <url-pattern>/resources/*</url-pattern> </web-resource-collection> </security-constraint> <security-constraint> <web-resource-collection> <web-resource-name>Secured Areas</web-resource-name> <url-pattern>/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>ROLE_USER</role-name> </auth-constraint> </security-constraint>Last you will need to configure your container to contain the user with the correct roles. This configuration is specific to the Servlet Container, so consult your Servlet Container's documentation.- Parameters:
jeeCustomizer- theCustomizerto provide more options for theJeeConfigurer- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception
-
x509
@Deprecated(since="6.1", forRemoval=true) public X509Configurer<HttpSecurity> x509() throws ExceptionDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. Usex509(Customizer)orx509(Customizer.withDefaults())to stick with defaults. See the documentation for more details.Configures X509 based pre authentication.Example Configuration
The following configuration will attempt to extract the username from the X509 certificate. Remember that the Servlet Container will need to be configured to request client certificates in order for this to work.@Configuration @EnableWebSecurity public class X509SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeRequests().requestMatchers("/**").hasRole("USER").and() // Example x509() configuration .x509(); return http.build(); } }- Returns:
- the
X509Configurerfor further customizations - Throws:
Exception
-
x509
Configures X509 based pre authentication.Example Configuration
The following configuration will attempt to extract the username from the X509 certificate. Remember that the Servlet Container will need to be configured to request client certificates in order for this to work.@Configuration @EnableWebSecurity public class X509SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/**").hasRole("USER") ) .x509(withDefaults()); return http.build(); } }- Parameters:
x509Customizer- theCustomizerto provide more options for theX509Configurer- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception
-
rememberMe
@Deprecated(since="6.1", forRemoval=true) public RememberMeConfigurer<HttpSecurity> rememberMe() throws ExceptionDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. UserememberMe(Customizer)orrememberMe(Customizer.withDefaults())to stick with defaults. See the documentation for more details.Allows configuring of Remember Me authentication.Example Configuration
The following configuration demonstrates how to allow token based remember me authentication. Upon authenticating if the HTTP parameter named "remember-me" exists, then the user will be remembered even after theirHttpSessionexpires.@Configuration @EnableWebSecurity public class RememberMeSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeRequests().requestMatchers("/**").hasRole("USER").and().formLogin() .permitAll().and() // Example Remember Me Configuration .rememberMe(); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }- Returns:
- the
RememberMeConfigurerfor further customizations - Throws:
Exception
-
rememberMe
public HttpSecurity rememberMe(Customizer<RememberMeConfigurer<HttpSecurity>> rememberMeCustomizer) throws Exception Allows configuring of Remember Me authentication.Example Configuration
The following configuration demonstrates how to allow token based remember me authentication. Upon authenticating if the HTTP parameter named "remember-me" exists, then the user will be remembered even after theirHttpSessionexpires.@Configuration @EnableWebSecurity public class RememberMeSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/**").hasRole("USER") ) .formLogin(withDefaults()) .rememberMe(withDefaults()); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }- Parameters:
rememberMeCustomizer- theCustomizerto provide more options for theRememberMeConfigurer- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception
-
authorizeRequests
@Deprecated(since="6.1", forRemoval=true) public ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry authorizeRequests() throws ExceptionDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. UseauthorizeHttpRequests(Customizer)insteadAllows restricting access based upon theHttpServletRequestusingRequestMatcherimplementations (i.e. via URL patterns).Example Configurations
The most basic example is to configure all URLs to require the role "ROLE_USER". The configuration below requires authentication to every URL and will grant access to both the user "admin" and "user".@Configuration @EnableWebSecurity public class AuthorizeUrlsSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeRequests().requestMatchers("/**").hasRole("USER").and().formLogin(); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); UserDetails admin = User.withDefaultPasswordEncoder() .username("admin") .password("password") .roles("ADMIN", "USER") .build(); return new InMemoryUserDetailsManager(user, admin); } }We can also configure multiple URLs. The configuration below requires authentication to every URL and will grant access to URLs starting with /admin/ to only the "admin" user. All other URLs either user can access.@Configuration @EnableWebSecurity public class AuthorizeUrlsSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeRequests().requestMatchers("/admin/**").hasRole("ADMIN") .requestMatchers("/**").hasRole("USER").and().formLogin(); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); UserDetails admin = User.withDefaultPasswordEncoder() .username("admin") .password("password") .roles("ADMIN", "USER") .build(); return new InMemoryUserDetailsManager(user, admin); } }Note that the matchers are considered in order. Therefore, the following is invalid because the first matcher matches every request and will never get to the second mapping:@Configuration @EnableWebSecurity public class AuthorizeUrlsSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeRequests().requestMatchers("/**").hasRole("USER").requestMatchers("/admin/**") .hasRole("ADMIN") return http.build(); } }- Returns:
- the
ExpressionUrlAuthorizationConfigurerfor further customizations - Throws:
Exception
-
authorizeRequests
@Deprecated(since="6.1", forRemoval=true) public HttpSecurity authorizeRequests(Customizer<ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry> authorizeRequestsCustomizer) throws Exception Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. UseauthorizeHttpRequests(Customizer)insteadAllows restricting access based upon theHttpServletRequestusingRequestMatcherimplementations (i.e. via URL patterns).Example Configurations
The most basic example is to configure all URLs to require the role "ROLE_USER". The configuration below requires authentication to every URL and will grant access to both the user "admin" and "user".@Configuration @EnableWebSecurity public class AuthorizeUrlsSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/**").hasRole("USER") ) .formLogin(withDefaults()); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); UserDetails admin = User.withDefaultPasswordEncoder() .username("admin") .password("password") .roles("ADMIN", "USER") .build(); return new InMemoryUserDetailsManager(user, admin); } }We can also configure multiple URLs. The configuration below requires authentication to every URL and will grant access to URLs starting with /admin/ to only the "admin" user. All other URLs either user can access.@Configuration @EnableWebSecurity public class AuthorizeUrlsSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/admin/**").hasRole("ADMIN") .requestMatchers("/**").hasRole("USER") ) .formLogin(withDefaults()); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); UserDetails admin = User.withDefaultPasswordEncoder() .username("admin") .password("password") .roles("ADMIN", "USER") .build(); return new InMemoryUserDetailsManager(user, admin); } }Note that the matchers are considered in order. Therefore, the following is invalid because the first matcher matches every request and will never get to the second mapping:@Configuration @EnableWebSecurity public class AuthorizeUrlsSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/**").hasRole("USER") .requestMatchers("/admin/**").hasRole("ADMIN") ); return http.build(); } }- Parameters:
authorizeRequestsCustomizer- theCustomizerto provide more options for theExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception
-
authorizeHttpRequests
@Deprecated(since="6.1", forRemoval=true) public AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizationManagerRequestMatcherRegistry authorizeHttpRequests() throws ExceptionDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. UseauthorizeHttpRequests(Customizer)insteadAllows restricting access based upon theHttpServletRequestusingRequestMatcherimplementations (i.e. via URL patterns).Example Configurations
The most basic example is to configure all URLs to require the role "ROLE_USER". The configuration below requires authentication to every URL and will grant access to both the user "admin" and "user".@Configuration @EnableWebSecurity public class AuthorizeUrlsSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests() .requestMatchers("/**").hasRole("USER") .and() .formLogin(); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); UserDetails admin = User.withDefaultPasswordEncoder() .username("admin") .password("password") .roles("ADMIN", "USER") .build(); return new InMemoryUserDetailsManager(user, admin); } }We can also configure multiple URLs. The configuration below requires authentication to every URL and will grant access to URLs starting with /admin/ to only the "admin" user. All other URLs either user can access.@Configuration @EnableWebSecurity public class AuthorizeUrlsSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests() .requestMatchers("/admin").hasRole("ADMIN") .requestMatchers("/**").hasRole("USER") .and() .formLogin(); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); UserDetails admin = User.withDefaultPasswordEncoder() .username("admin") .password("password") .roles("ADMIN", "USER") .build(); return new InMemoryUserDetailsManager(user, admin); } }Note that the matchers are considered in order. Therefore, the following is invalid because the first matcher matches every request and will never get to the second mapping:@Configuration @EnableWebSecurity public class AuthorizeUrlsSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests() .requestMatchers("/**").hasRole("USER") .requestMatchers("/admin/**").hasRole("ADMIN") .and() .formLogin(); return http.build(); } }- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception- Since:
- 5.6
-
authorizeHttpRequests
public HttpSecurity authorizeHttpRequests(Customizer<AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizationManagerRequestMatcherRegistry> authorizeHttpRequestsCustomizer) throws Exception Allows restricting access based upon theHttpServletRequestusingRequestMatcherimplementations (i.e. via URL patterns).Example Configurations
The most basic example is to configure all URLs to require the role "ROLE_USER". The configuration below requires authentication to every URL and will grant access to both the user "admin" and "user".@Configuration @EnableWebSecurity public class AuthorizeUrlsSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests((authorizeHttpRequests) -> authorizeHttpRequests .requestMatchers("/**").hasRole("USER") ) .formLogin(withDefaults()); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); UserDetails admin = User.withDefaultPasswordEncoder() .username("admin") .password("password") .roles("ADMIN", "USER") .build(); return new InMemoryUserDetailsManager(user, admin); } }We can also configure multiple URLs. The configuration below requires authentication to every URL and will grant access to URLs starting with /admin/ to only the "admin" user. All other URLs either user can access.@Configuration @EnableWebSecurity public class AuthorizeUrlsSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests((authorizeHttpRequests) -> authorizeHttpRequests .requestMatchers("/admin/**").hasRole("ADMIN") .requestMatchers("/**").hasRole("USER") ) .formLogin(withDefaults()); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); UserDetails admin = User.withDefaultPasswordEncoder() .username("admin") .password("password") .roles("ADMIN", "USER") .build(); return new InMemoryUserDetailsManager(user, admin); } }Note that the matchers are considered in order. Therefore, the following is invalid because the first matcher matches every request and will never get to the second mapping:@Configuration @EnableWebSecurity public class AuthorizeUrlsSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests((authorizeHttpRequests) -> authorizeHttpRequests .requestMatchers("/**").hasRole("USER") .requestMatchers("/admin/**").hasRole("ADMIN") ); return http.build(); } }- Parameters:
authorizeHttpRequestsCustomizer- theCustomizerto provide more options for theAuthorizeHttpRequestsConfigurer.AuthorizationManagerRequestMatcherRegistry- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception- Since:
- 5.5
-
requestCache
@Deprecated(since="6.1", forRemoval=true) public RequestCacheConfigurer<HttpSecurity> requestCache() throws ExceptionDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. UserequestCache(Customizer)orrequestCache(Customizer.withDefaults())to stick with defaults. See the documentation for more details.Allows configuring the Request Cache. For example, a protected page (/protected) may be requested prior to authentication. The application will redirect the user to a login page. After authentication, Spring Security will redirect the user to the originally requested protected page (/protected). This is automatically applied when usingEnableWebSecurity.- Returns:
- the
RequestCacheConfigurerfor further customizations - Throws:
Exception
-
requestCache
public HttpSecurity requestCache(Customizer<RequestCacheConfigurer<HttpSecurity>> requestCacheCustomizer) throws Exception Allows configuring the Request Cache. For example, a protected page (/protected) may be requested prior to authentication. The application will redirect the user to a login page. After authentication, Spring Security will redirect the user to the originally requested protected page (/protected). This is automatically applied when usingEnableWebSecurity.Example Custom Configuration
The following example demonstrates how to disable request caching.@Configuration @EnableWebSecurity public class RequestCacheDisabledSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/**").hasRole("USER") ) .requestCache((requestCache) -> requestCache.disable() ); return http.build(); } }- Parameters:
requestCacheCustomizer- theCustomizerto provide more options for theRequestCacheConfigurer- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception
-
exceptionHandling
@Deprecated(since="6.1", forRemoval=true) public ExceptionHandlingConfigurer<HttpSecurity> exceptionHandling() throws ExceptionDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. UseexceptionHandling(Customizer)orexceptionHandling(Customizer.withDefaults())to stick with defaults. See the documentation for more details.Allows configuring exception handling. This is automatically applied when usingEnableWebSecurity.- Returns:
- the
ExceptionHandlingConfigurerfor further customizations - Throws:
Exception
-
exceptionHandling
public HttpSecurity exceptionHandling(Customizer<ExceptionHandlingConfigurer<HttpSecurity>> exceptionHandlingCustomizer) throws Exception Allows configuring exception handling. This is automatically applied when usingEnableWebSecurity.Example Custom Configuration
The following customization will ensure that users who are denied access are forwarded to the page "/errors/access-denied".@Configuration @EnableWebSecurity public class ExceptionHandlingSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/**").hasRole("USER") ) // sample exception handling customization .exceptionHandling((exceptionHandling) -> exceptionHandling .accessDeniedPage("/errors/access-denied") ); return http.build(); } }- Parameters:
exceptionHandlingCustomizer- theCustomizerto provide more options for theExceptionHandlingConfigurer- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception
-
securityContext
@Deprecated(since="6.1", forRemoval=true) public SecurityContextConfigurer<HttpSecurity> securityContext() throws ExceptionDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. UsesecurityContext(Customizer)orsecurityContext(Customizer.withDefaults())to stick with defaults. See the documentation for more details.Sets up management of theSecurityContexton theSecurityContextHolderbetweenHttpServletRequest's. This is automatically applied when usingEnableWebSecurity.- Returns:
- the
SecurityContextConfigurerfor further customizations - Throws:
Exception
-
securityContext
public HttpSecurity securityContext(Customizer<SecurityContextConfigurer<HttpSecurity>> securityContextCustomizer) throws Exception Sets up management of theSecurityContexton theSecurityContextHolderbetweenHttpServletRequest's. This is automatically applied when usingEnableWebSecurity. The following customization specifies the sharedSecurityContextRepository@Configuration @EnableWebSecurity public class SecurityContextSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .securityContext((securityContext) -> securityContext .securityContextRepository(SCR) ); return http.build(); } }- Parameters:
securityContextCustomizer- theCustomizerto provide more options for theSecurityContextConfigurer- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception
-
servletApi
@Deprecated(since="6.1", forRemoval=true) public ServletApiConfigurer<HttpSecurity> servletApi() throws ExceptionDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. UseservletApi(Customizer)orservletApi(Customizer.withDefaults())to stick with defaults. See the documentation for more details.Integrates theHttpServletRequestmethods with the values found on theSecurityContext. This is automatically applied when usingEnableWebSecurity.- Returns:
- the
ServletApiConfigurerfor further customizations - Throws:
Exception
-
servletApi
public HttpSecurity servletApi(Customizer<ServletApiConfigurer<HttpSecurity>> servletApiCustomizer) throws Exception Integrates theHttpServletRequestmethods with the values found on theSecurityContext. This is automatically applied when usingEnableWebSecurity. You can disable it using:@Configuration @EnableWebSecurity public class ServletApiSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .servletApi((servletApi) -> servletApi.disable() ); return http.build(); } }- Parameters:
servletApiCustomizer- theCustomizerto provide more options for theServletApiConfigurer- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception
-
csrf
@Deprecated(since="6.1", forRemoval=true) public CsrfConfigurer<HttpSecurity> csrf() throws ExceptionDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. Usecsrf(Customizer)orcsrf(Customizer.withDefaults())to stick with defaults. See the documentation for more details.Enables CSRF protection. This is activated by default when usingEnableWebSecurity's default constructor. You can disable it using:@Configuration @EnableWebSecurity public class CsrfSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .csrf().disable() ...; return http.build(); } }- Returns:
- the
CsrfConfigurerfor further customizations - Throws:
Exception
-
csrf
Enables CSRF protection. This is activated by default when usingEnableWebSecurity. You can disable it using:@Configuration @EnableWebSecurity public class CsrfSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .csrf((csrf) -> csrf.disable()); return http.build(); } }- Parameters:
csrfCustomizer- theCustomizerto provide more options for theCsrfConfigurer- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception
-
logout
@Deprecated(since="6.1", forRemoval=true) public LogoutConfigurer<HttpSecurity> logout() throws ExceptionDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. Uselogout(Customizer)orlogout(Customizer.withDefaults())to stick with defaults. See the documentation for more details.Provides logout support. This is automatically applied when usingEnableWebSecurity. The default is that accessing the URL "/logout" will log the user out by invalidating the HTTP Session, cleaning up anyrememberMe()authentication that was configured, clearing theSecurityContextHolder, and then redirect to "/login?success".Example Custom Configuration
The following customization to log out when the URL "/custom-logout" is invoked. Log out will remove the cookie named "remove", not invalidate the HttpSession, clear the SecurityContextHolder, and upon completion redirect to "/logout-success".@Configuration @EnableWebSecurity public class LogoutSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeRequests().requestMatchers("/**").hasRole("USER").and().formLogin() .and() // sample logout customization .logout().deleteCookies("remove").invalidateHttpSession(false) .logoutUrl("/custom-logout").logoutSuccessUrl("/logout-success"); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }- Returns:
- the
LogoutConfigurerfor further customizations - Throws:
Exception
-
logout
public HttpSecurity logout(Customizer<LogoutConfigurer<HttpSecurity>> logoutCustomizer) throws Exception Provides logout support. This is automatically applied when usingEnableWebSecurity. The default is that accessing the URL "/logout" will log the user out by invalidating the HTTP Session, cleaning up anyrememberMe()authentication that was configured, clearing theSecurityContextHolder, and then redirect to "/login?success".Example Custom Configuration
The following customization to log out when the URL "/custom-logout" is invoked. Log out will remove the cookie named "remove", not invalidate the HttpSession, clear the SecurityContextHolder, and upon completion redirect to "/logout-success".@Configuration @EnableWebSecurity public class LogoutSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/**").hasRole("USER") ) .formLogin(withDefaults()) // sample logout customization .logout((logout) -> logout.deleteCookies("remove") .invalidateHttpSession(false) .logoutUrl("/custom-logout") .logoutSuccessUrl("/logout-success") ); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }- Parameters:
logoutCustomizer- theCustomizerto provide more options for theLogoutConfigurer- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception
-
anonymous
@Deprecated(since="6.1", forRemoval=true) public AnonymousConfigurer<HttpSecurity> anonymous() throws ExceptionDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. Useanonymous(Customizer)oranonymous(Customizer.withDefaults())to stick with defaults. See the documentation for more details.Allows configuring how an anonymous user is represented. This is automatically applied when used in conjunction withEnableWebSecurity. By default anonymous users will be represented with anAnonymousAuthenticationTokenand contain the role "ROLE_ANONYMOUS".Example Configuration
The following configuration demonstrates how to specify that anonymous users should contain the role "ROLE_ANON" instead.@Configuration @EnableWebSecurity public class AnonymousSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests() .requestMatchers("/**").hasRole("USER") .and() .formLogin() .and() // sample anonymous customization .anonymous().authorities("ROLE_ANON"); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }The following demonstrates how to represent anonymous users as null. Note that this can causeNullPointerExceptionin code that assumes anonymous authentication is enabled.@Configuration @EnableWebSecurity public class AnonymousSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests() .requestMatchers("/**").hasRole("USER") .and() .formLogin() .and() // sample anonymous customization .anonymous().disable(); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }- Returns:
- the
AnonymousConfigurerfor further customizations - Throws:
Exception
-
anonymous
public HttpSecurity anonymous(Customizer<AnonymousConfigurer<HttpSecurity>> anonymousCustomizer) throws Exception Allows configuring how an anonymous user is represented. This is automatically applied when used in conjunction withEnableWebSecurity. By default anonymous users will be represented with anAnonymousAuthenticationTokenand contain the role "ROLE_ANONYMOUS".Example Configuration
The following configuration demonstrates how to specify that anonymous users should contain the role "ROLE_ANON" instead.@Configuration @EnableWebSecurity public class AnonymousSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/**").hasRole("USER") ) .formLogin(withDefaults()) // sample anonymous customization .anonymous((anonymous) -> anonymous .authorities("ROLE_ANON") ); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }The following demonstrates how to represent anonymous users as null. Note that this can causeNullPointerExceptionin code that assumes anonymous authentication is enabled.@Configuration @EnableWebSecurity public class AnonymousSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/**").hasRole("USER") ) .formLogin(withDefaults()) // sample anonymous customization .anonymous((anonymous) -> anonymous.disable() ); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }- Parameters:
anonymousCustomizer- theCustomizerto provide more options for theAnonymousConfigurer- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception
-
formLogin
@Deprecated(since="6.1", forRemoval=true) public FormLoginConfigurer<HttpSecurity> formLogin() throws ExceptionDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. UseformLogin(Customizer)orformLogin(Customizer.withDefaults())to stick with defaults. See the documentation for more details.Specifies to support form based authentication. IfFormLoginConfigurer.loginPage(String)is not specified a default login page will be generated.Example Configurations
The most basic configuration defaults to automatically generating a login page at the URL "/login", redirecting to "/login?error" for authentication failure. The details of the login page can be found onFormLoginConfigurer.loginPage(String)@Configuration @EnableWebSecurity public class FormLoginSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeRequests().requestMatchers("/**").hasRole("USER").and().formLogin(); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }The configuration below demonstrates customizing the defaults.@Configuration @EnableWebSecurity public class FormLoginSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeRequests().requestMatchers("/**").hasRole("USER").and().formLogin() .usernameParameter("username") // default is username .passwordParameter("password") // default is password .loginPage("/authentication/login") // default is /login with an HTTP get .failureUrl("/authentication/login?failed") // default is /login?error .loginProcessingUrl("/authentication/login/process"); // default is /login // with an HTTP // post return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }- Returns:
- the
FormLoginConfigurerfor further customizations - Throws:
Exception- See Also:
-
formLogin
public HttpSecurity formLogin(Customizer<FormLoginConfigurer<HttpSecurity>> formLoginCustomizer) throws Exception Specifies to support form based authentication. IfFormLoginConfigurer.loginPage(String)is not specified a default login page will be generated.Example Configurations
The most basic configuration defaults to automatically generating a login page at the URL "/login", redirecting to "/login?error" for authentication failure. The details of the login page can be found onFormLoginConfigurer.loginPage(String)@Configuration @EnableWebSecurity public class FormLoginSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/**").hasRole("USER") ) .formLogin(withDefaults()); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }The configuration below demonstrates customizing the defaults.@Configuration @EnableWebSecurity public class FormLoginSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/**").hasRole("USER") ) .formLogin((formLogin) -> formLogin .usernameParameter("username") .passwordParameter("password") .loginPage("/authentication/login") .failureUrl("/authentication/login?failed") .loginProcessingUrl("/authentication/login/process") ); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }- Parameters:
formLoginCustomizer- theCustomizerto provide more options for theFormLoginConfigurer- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception- See Also:
-
saml2Login
@Deprecated(since="6.1", forRemoval=true) public Saml2LoginConfigurer<HttpSecurity> saml2Login() throws ExceptionDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. Usesaml2Login(Customizer)orsaml2Login(Customizer.withDefaults())to stick with defaults. See the documentation for more details.Configures authentication support using an SAML 2.0 Service Provider.
The "authentication flow" is implemented using the Web Browser SSO Profile, using POST and REDIRECT bindings, as documented in the SAML V2.0 Core,Profiles and Bindings specifications.
As a prerequisite to using this feature, is that you have a SAML v2.0 Identity Provider to provide an assertion. The representation of the Service Provider, the relying party, and the remote Identity Provider, the asserting party is contained withinRelyingPartyRegistration.
RelyingPartyRegistration(s) are composed within aRelyingPartyRegistrationRepository, which is required and must be registered with theApplicationContextor configured viasaml2Login().relyingPartyRegistrationRepository(..).
The default configuration provides an auto-generated login page at"/login"and redirects to"/login?error"when an authentication error occurs. The login page will display each of the identity providers with a link that is capable of initiating the "authentication flow".
Example Configuration
The following example shows the minimal configuration required, using SimpleSamlPhp as the Authentication Provider.@Configuration @EnableWebSecurity public class Saml2LoginSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .saml2Login(); return http.build(); } @Bean public RelyingPartyRegistrationRepository relyingPartyRegistrationRepository() { return new InMemoryRelyingPartyRegistrationRepository(this.getSaml2RelyingPartyRegistration()); } private RelyingPartyRegistration getSaml2RelyingPartyRegistration() { //remote IDP entity ID String idpEntityId = "https://simplesaml-for-spring-saml.apps.pcfone.io/saml2/idp/metadata.php"; //remote WebSSO Endpoint - Where to Send AuthNRequests to String webSsoEndpoint = "https://simplesaml-for-spring-saml.apps.pcfone.io/saml2/idp/SSOService.php"; //local registration ID String registrationId = "simplesamlphp"; //local entity ID - autogenerated based on URL String localEntityIdTemplate = "{baseUrl}/saml2/service-provider-metadata/{registrationId}"; //local signing (and decryption key) Saml2X509Credential signingCredential = getSigningCredential(); //IDP certificate for verification of incoming messages Saml2X509Credential idpVerificationCertificate = getVerificationCertificate(); return RelyingPartyRegistration.withRegistrationId(registrationId) .remoteIdpEntityId(idpEntityId) .idpWebSsoUrl(webSsoEndpoint) .credential(signingCredential) .credential(idpVerificationCertificate) .localEntityIdTemplate(localEntityIdTemplate) .build(); } }- Returns:
- the
Saml2LoginConfigurerfor further customizations - Throws:
Exception- Since:
- 5.2
-
saml2Login
public HttpSecurity saml2Login(Customizer<Saml2LoginConfigurer<HttpSecurity>> saml2LoginCustomizer) throws Exception Configures authentication support using an SAML 2.0 Service Provider.
The "authentication flow" is implemented using the Web Browser SSO Profile, using POST and REDIRECT bindings, as documented in the SAML V2.0 Core,Profiles and Bindings specifications.
As a prerequisite to using this feature, is that you have a SAML v2.0 Identity Provider to provide an assertion. The representation of the Service Provider, the relying party, and the remote Identity Provider, the asserting party is contained withinRelyingPartyRegistration.
RelyingPartyRegistration(s) are composed within aRelyingPartyRegistrationRepository, which is required and must be registered with theApplicationContextor configured viasaml2Login().relyingPartyRegistrationRepository(..).
The default configuration provides an auto-generated login page at"/login"and redirects to"/login?error"when an authentication error occurs. The login page will display each of the identity providers with a link that is capable of initiating the "authentication flow".
Example Configuration
The following example shows the minimal configuration required, using SimpleSamlPhp as the Authentication Provider.@Configuration @EnableWebSecurity public class Saml2LoginSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .anyRequest().authenticated() ) .saml2Login(withDefaults()); return http.build(); } @Bean public RelyingPartyRegistrationRepository relyingPartyRegistrationRepository() { return new InMemoryRelyingPartyRegistrationRepository(this.getSaml2RelyingPartyRegistration()); } private RelyingPartyRegistration getSaml2RelyingPartyRegistration() { //remote IDP entity ID String idpEntityId = "https://simplesaml-for-spring-saml.apps.pcfone.io/saml2/idp/metadata.php"; //remote WebSSO Endpoint - Where to Send AuthNRequests to String webSsoEndpoint = "https://simplesaml-for-spring-saml.apps.pcfone.io/saml2/idp/SSOService.php"; //local registration ID String registrationId = "simplesamlphp"; //local entity ID - autogenerated based on URL String localEntityIdTemplate = "{baseUrl}/saml2/service-provider-metadata/{registrationId}"; //local signing (and decryption key) Saml2X509Credential signingCredential = getSigningCredential(); //IDP certificate for verification of incoming messages Saml2X509Credential idpVerificationCertificate = getVerificationCertificate(); return RelyingPartyRegistration.withRegistrationId(registrationId) .remoteIdpEntityId(idpEntityId) .idpWebSsoUrl(webSsoEndpoint) .credential(signingCredential) .credential(idpVerificationCertificate) .localEntityIdTemplate(localEntityIdTemplate) .build(); } }- Parameters:
saml2LoginCustomizer- theCustomizerto provide more options for theSaml2LoginConfigurer- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception- Since:
- 5.2
-
saml2Logout
public HttpSecurity saml2Logout(Customizer<Saml2LogoutConfigurer<HttpSecurity>> saml2LogoutCustomizer) throws Exception Configures logout support for an SAML 2.0 Relying Party.
Implements the Single Logout Profile, using POST and REDIRECT bindings, as documented in the SAML V2.0 Core, Profiles and Bindings specifications.
As a prerequisite to using this feature, is that you have a SAML v2.0 Asserting Party to sent a logout request to. The representation of the relying party and the asserting party is contained withinRelyingPartyRegistration.
RelyingPartyRegistration(s) are composed within aRelyingPartyRegistrationRepository, which is required and must be registered with theApplicationContextor configured viasaml2Login(Customizer).
The default configuration provides an auto-generated logout endpoint at"/logout"and redirects to/login?logoutwhen logout completes.
Example Configuration
The following example shows the minimal configuration required, using a hypothetical asserting party.@EnableWebSecurity @Configuration public class Saml2LogoutSecurityConfig { @Bean public SecurityFilterChain web(HttpSecurity http) throws Exception { http .authorizeRequests((authorize) -> authorize .anyRequest().authenticated() ) .saml2Login(withDefaults()) .saml2Logout(withDefaults()); return http.build(); } @Bean public RelyingPartyRegistrationRepository relyingPartyRegistrationRepository() { RelyingPartyRegistration registration = RelyingPartyRegistrations .withMetadataLocation("https://ap.example.org/metadata") .registrationId("simple") .build(); return new InMemoryRelyingPartyRegistrationRepository(registration); } }- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception- Since:
- 5.6
-
saml2Logout
@Deprecated(since="6.1", forRemoval=true) public Saml2LogoutConfigurer<HttpSecurity> saml2Logout() throws ExceptionDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. Usesaml2Logout(Customizer)orsaml2Logout(Customizer.withDefaults())to stick with defaults. See the documentation for more details.Configures logout support for an SAML 2.0 Relying Party.
Implements the Single Logout Profile, using POST and REDIRECT bindings, as documented in the SAML V2.0 Core, Profiles and Bindings specifications.
As a prerequisite to using this feature, is that you have a SAML v2.0 Asserting Party to sent a logout request to. The representation of the relying party and the asserting party is contained withinRelyingPartyRegistration.
RelyingPartyRegistration(s) are composed within aRelyingPartyRegistrationRepository, which is required and must be registered with theApplicationContextor configured viasaml2Login().
The default configuration provides an auto-generated logout endpoint at"/logout"and redirects to/login?logoutwhen logout completes.
Example Configuration
The following example shows the minimal configuration required, using a hypothetical asserting party.@EnableWebSecurity @Configuration public class Saml2LogoutSecurityConfig { @Bean public SecurityFilterChain web(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .saml2Login() .and() .saml2Logout(); return http.build(); } @Bean public RelyingPartyRegistrationRepository relyingPartyRegistrationRepository() { RelyingPartyRegistration registration = RelyingPartyRegistrations .withMetadataLocation("https://ap.example.org/metadata") .registrationId("simple") .build(); return new InMemoryRelyingPartyRegistrationRepository(registration); } }- Returns:
- the
Saml2LoginConfigurerfor further customizations - Throws:
Exception- Since:
- 5.6
-
saml2Metadata
public HttpSecurity saml2Metadata(Customizer<Saml2MetadataConfigurer<HttpSecurity>> saml2MetadataConfigurer) throws Exception Configures a SAML 2.0 metadata endpoint that presents relying party configurations in an<md:EntityDescriptor>payload.By default, the endpoints are
/saml2/metadataand/saml2/metadata/{registrationId}though note that also/saml2/service-provider-metadata/{registrationId}is recognized for backward compatibility purposes.Example Configuration
The following example shows the minimal configuration required, using a hypothetical asserting party.@EnableWebSecurity @Configuration public class Saml2LogoutSecurityConfig { @Bean public SecurityFilterChain web(HttpSecurity http) throws Exception { http .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated()) .saml2Metadata(Customizer.withDefaults()); return http.build(); } @Bean public RelyingPartyRegistrationRepository relyingPartyRegistrationRepository() { RelyingPartyRegistration registration = RelyingPartyRegistrations .withMetadataLocation("https://ap.example.org/metadata") .registrationId("simple") .build(); return new InMemoryRelyingPartyRegistrationRepository(registration); } }- Parameters:
saml2MetadataConfigurer- theCustomizerto provide more options for theSaml2MetadataConfigurer- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception- Since:
- 6.1
-
saml2Metadata
@Deprecated(since="6.1", forRemoval=true) public Saml2MetadataConfigurer<HttpSecurity> saml2Metadata() throws ExceptionDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. Usesaml2Metadata(Customizer)orsaml2Metadata(Customizer.withDefaults())to stick with defaults. See the documentation for more details.Configures a SAML 2.0 metadata endpoint that presents relying party configurations in an<md:EntityDescriptor>payload.By default, the endpoints are
/saml2/metadataand/saml2/metadata/{registrationId}though note that also/saml2/service-provider-metadata/{registrationId}is recognized for backward compatibility purposes.Example Configuration
The following example shows the minimal configuration required, using a hypothetical asserting party.@EnableWebSecurity @Configuration public class Saml2LogoutSecurityConfig { @Bean public SecurityFilterChain web(HttpSecurity http) throws Exception { http .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated()) .saml2Metadata(Customizer.withDefaults()); return http.build(); } @Bean public RelyingPartyRegistrationRepository relyingPartyRegistrationRepository() { RelyingPartyRegistration registration = RelyingPartyRegistrations .withMetadataLocation("https://ap.example.org/metadata") .registrationId("simple") .build(); return new InMemoryRelyingPartyRegistrationRepository(registration); } }- Returns:
- the
Saml2MetadataConfigurerfor further customizations - Throws:
Exception- Since:
- 6.1
-
oauth2Login
@Deprecated(since="6.1", forRemoval=true) public OAuth2LoginConfigurer<HttpSecurity> oauth2Login() throws ExceptionDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. Useoauth2Login(Customizer)oroauth2Login(Customizer.withDefaults())to stick with defaults. See the documentation for more details.Configures authentication support using an OAuth 2.0 and/or OpenID Connect 1.0 Provider.
The "authentication flow" is implemented using the Authorization Code Grant, as specified in the OAuth 2.0 Authorization Framework and OpenID Connect Core 1.0 specification.
As a prerequisite to using this feature, you must register a client with a provider. The client registration information may than be used for configuring aClientRegistrationusing aClientRegistration.Builder.
ClientRegistration(s) are composed within aClientRegistrationRepository, which is required and must be registered with theApplicationContextor configured viaoauth2Login().clientRegistrationRepository(..).
The default configuration provides an auto-generated login page at"/login"and redirects to"/login?error"when an authentication error occurs. The login page will display each of the clients with a link that is capable of initiating the "authentication flow".
Example Configuration
The following example shows the minimal configuration required, using Google as the Authentication Provider.@Configuration @EnableWebSecurity public class OAuth2LoginSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .oauth2Login(); return http.build(); } @Bean public ClientRegistrationRepository clientRegistrationRepository() { return new InMemoryClientRegistrationRepository(this.googleClientRegistration()); } private ClientRegistration googleClientRegistration() { return ClientRegistration.withRegistrationId("google") .clientId("google-client-id") .clientSecret("google-client-secret") .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") .scope("openid", "profile", "email", "address", "phone") .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") .tokenUri("https://www.googleapis.com/oauth2/v4/token") .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") .userNameAttributeName(IdTokenClaimNames.SUB) .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") .clientName("Google") .build(); } }For more advanced configuration, see
OAuth2LoginConfigurerfor available options to customize the defaults.- Returns:
- the
OAuth2LoginConfigurerfor further customizations - Throws:
Exception- Since:
- 5.0
- See Also:
-
oauth2Login
public HttpSecurity oauth2Login(Customizer<OAuth2LoginConfigurer<HttpSecurity>> oauth2LoginCustomizer) throws Exception Configures authentication support using an OAuth 2.0 and/or OpenID Connect 1.0 Provider.
The "authentication flow" is implemented using the Authorization Code Grant, as specified in the OAuth 2.0 Authorization Framework and OpenID Connect Core 1.0 specification.
As a prerequisite to using this feature, you must register a client with a provider. The client registration information may than be used for configuring aClientRegistrationusing aClientRegistration.Builder.
ClientRegistration(s) are composed within aClientRegistrationRepository, which is required and must be registered with theApplicationContextor configured viaoauth2Login().clientRegistrationRepository(..).
The default configuration provides an auto-generated login page at"/login"and redirects to"/login?error"when an authentication error occurs. The login page will display each of the clients with a link that is capable of initiating the "authentication flow".
Example Configuration
The following example shows the minimal configuration required, using Google as the Authentication Provider.@Configuration @EnableWebSecurity public class OAuth2LoginSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .anyRequest().authenticated() ) .oauth2Login(withDefaults()); return http.build(); } @Bean public ClientRegistrationRepository clientRegistrationRepository() { return new InMemoryClientRegistrationRepository(this.googleClientRegistration()); } private ClientRegistration googleClientRegistration() { return ClientRegistration.withRegistrationId("google") .clientId("google-client-id") .clientSecret("google-client-secret") .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") .scope("openid", "profile", "email", "address", "phone") .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") .tokenUri("https://www.googleapis.com/oauth2/v4/token") .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") .userNameAttributeName(IdTokenClaimNames.SUB) .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") .clientName("Google") .build(); } }For more advanced configuration, see
OAuth2LoginConfigurerfor available options to customize the defaults.- Parameters:
oauth2LoginCustomizer- theCustomizerto provide more options for theOAuth2LoginConfigurer- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception- See Also:
-
oidcLogout
- Throws:
Exception
-
oidcLogout
public HttpSecurity oidcLogout(Customizer<OidcLogoutConfigurer<HttpSecurity>> oidcLogoutCustomizer) throws Exception - Throws:
Exception
-
oauth2Client
@Deprecated(since="6.1", forRemoval=true) public OAuth2ClientConfigurer<HttpSecurity> oauth2Client() throws ExceptionDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. Useoauth2Client(Customizer)oroauth2Client(Customizer.withDefaults())to stick with defaults. See the documentation for more details.Configures OAuth 2.0 Client support.- Returns:
- the
OAuth2ClientConfigurerfor further customizations - Throws:
Exception- Since:
- 5.1
- See Also:
-
oauth2Client
public HttpSecurity oauth2Client(Customizer<OAuth2ClientConfigurer<HttpSecurity>> oauth2ClientCustomizer) throws Exception Configures OAuth 2.0 Client support.Example Configuration
The following example demonstrates how to enable OAuth 2.0 Client support for all endpoints.@Configuration @EnableWebSecurity public class OAuth2ClientSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .anyRequest().authenticated() ) .oauth2Client(withDefaults()); return http.build(); } }- Parameters:
oauth2ClientCustomizer- theCustomizerto provide more options for theOAuth2ClientConfigurer- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception- See Also:
-
oauth2ResourceServer
@Deprecated(since="6.1", forRemoval=true) public OAuth2ResourceServerConfigurer<HttpSecurity> oauth2ResourceServer() throws ExceptionDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. Useoauth2ResourceServer(Customizer)insteadConfigures OAuth 2.0 Resource Server support.- Returns:
- the
OAuth2ResourceServerConfigurerfor further customizations - Throws:
Exception- Since:
- 5.1
- See Also:
-
oauth2ResourceServer
public HttpSecurity oauth2ResourceServer(Customizer<OAuth2ResourceServerConfigurer<HttpSecurity>> oauth2ResourceServerCustomizer) throws Exception Configures OAuth 2.0 Resource Server support.Example Configuration
The following example demonstrates how to configure a custom JWT authentication converter.@Configuration @EnableWebSecurity public class OAuth2ResourceServerSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .anyRequest().authenticated() ) .oauth2ResourceServer((oauth2ResourceServer) -> oauth2ResourceServer .jwt((jwt) -> jwt .decoder(jwtDecoder()) ) ); return http.build(); } @Bean public JwtDecoder jwtDecoder() { return NimbusJwtDecoder.withPublicKey(this.key).build(); } }- Parameters:
oauth2ResourceServerCustomizer- theCustomizerto provide more options for theOAuth2ResourceServerConfigurer- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception- See Also:
-
oneTimeTokenLogin
public HttpSecurity oneTimeTokenLogin(Customizer<OneTimeTokenLoginConfigurer<HttpSecurity>> oneTimeTokenLoginConfigurerCustomizer) throws Exception Configures One-Time Token Login Support.Example Configuration
@Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests((authorize) -> authorize .anyRequest().authenticated() ) .oneTimeTokenLogin(Customizer.withDefaults()); return http.build(); } @Bean public OneTimeTokenGenerationSuccessHandler oneTimeTokenGenerationSuccessHandler() { return new MyMagicLinkOneTimeTokenGenerationSuccessHandler(); } }- Parameters:
oneTimeTokenLoginConfigurerCustomizer- theCustomizerto provide more options for theOneTimeTokenLoginConfigurer- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception
-
requiresChannel
@Deprecated(since="6.1", forRemoval=true) public ChannelSecurityConfigurer<HttpSecurity>.ChannelRequestMatcherRegistry requiresChannel() throws ExceptionDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. UserequiresChannel(Customizer)orrequiresChannel(Customizer.withDefaults())to stick with defaults. See the documentation for more details.Configures channel security. In order for this configuration to be useful at least one mapping to a required channel must be provided.Example Configuration
The example below demonstrates how to require HTTPs for every request. Only requiring HTTPS for some requests is supported, but not recommended since an application that allows for HTTP introduces many security vulnerabilities. For one such example, read about Firesheep.@Configuration @EnableWebSecurity public class ChannelSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeRequests().requestMatchers("/**").hasRole("USER").and().formLogin() .and().requiresChannel().anyRequest().requiresSecure(); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }- Returns:
- the
ChannelSecurityConfigurerfor further customizations - Throws:
Exception
-
requiresChannel
@Deprecated public HttpSecurity requiresChannel(Customizer<ChannelSecurityConfigurer<HttpSecurity>.ChannelRequestMatcherRegistry> requiresChannelCustomizer) throws Exception Configures channel security. In order for this configuration to be useful at least one mapping to a required channel must be provided.Example Configuration
The example below demonstrates how to require HTTPs for every request. Only requiring HTTPS for some requests is supported, but not recommended since an application that allows for HTTP introduces many security vulnerabilities. For one such example, read about Firesheep.@Configuration @EnableWebSecurity public class ChannelSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/**").hasRole("USER") ) .formLogin(withDefaults()) .requiresChannel((requiresChannel) -> requiresChannel .anyRequest().requiresSecure() ); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }- Parameters:
requiresChannelCustomizer- theCustomizerto provide more options for theChannelSecurityConfigurer.ChannelRequestMatcherRegistry- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception
-
redirectToHttps
public HttpSecurity redirectToHttps(Customizer<HttpsRedirectConfigurer<HttpSecurity>> httpsRedirectConfigurerCustomizer) throws Exception Configures channel security. In order for this configuration to be useful at least one mapping to a required channel must be provided.Example Configuration
The example below demonstrates how to require HTTPS for every request. Only requiring HTTPS for some requests is supported, for example if you need to differentiate between local and production deployments.@Configuration @EnableWebSecurity public class RequireHttpsConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests((authorize) -> authorize anyRequest().authenticated() ) .formLogin(withDefaults()) .redirectToHttps(withDefaults()); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }- Parameters:
httpsRedirectConfigurerCustomizer- theCustomizerto provide more options for theHttpsRedirectConfigurer- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception
-
httpBasic
@Deprecated(since="6.1", forRemoval=true) public HttpBasicConfigurer<HttpSecurity> httpBasic() throws ExceptionDeprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. UsehttpBasic(Customizer)orhttpBasic(Customizer.withDefaults())to stick with defaults. See the documentation for more details.Configures HTTP Basic authentication.Example Configuration
The example below demonstrates how to configure HTTP Basic authentication for an application. The default realm is "Realm", but can be customized usingHttpBasicConfigurer.realmName(String).@Configuration @EnableWebSecurity public class HttpBasicSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeRequests().requestMatchers("/**").hasRole("USER").and().httpBasic(); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }- Returns:
- the
HttpBasicConfigurerfor further customizations - Throws:
Exception
-
httpBasic
public HttpSecurity httpBasic(Customizer<HttpBasicConfigurer<HttpSecurity>> httpBasicCustomizer) throws Exception Configures HTTP Basic authentication.Example Configuration
The example below demonstrates how to configure HTTP Basic authentication for an application. The default realm is "Realm", but can be customized usingHttpBasicConfigurer.realmName(String).@Configuration @EnableWebSecurity public class HttpBasicSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/**").hasRole("USER") ) .httpBasic(withDefaults()); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }- Parameters:
httpBasicCustomizer- theCustomizerto provide more options for theHttpBasicConfigurer- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception
-
passwordManagement
public HttpSecurity passwordManagement(Customizer<PasswordManagementConfigurer<HttpSecurity>> passwordManagementCustomizer) throws Exception Adds support for the password management.Example Configuration
The example below demonstrates how to configure password management for an application. The default change password page is "/change-password", but can be customized usingPasswordManagementConfigurer.changePasswordPage(String).@Configuration @EnableWebSecurity public class PasswordManagementSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeRequests(authorizeRequests -> authorizeRequests .requestMatchers("/**").hasRole("USER") ) .passwordManagement(passwordManagement -> passwordManagement .changePasswordPage("/custom-change-password-page") ); return http.build(); } }- Parameters:
passwordManagementCustomizer- theCustomizerto provide more options for thePasswordManagementConfigurer- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception- Since:
- 5.6
-
authenticationManager
Configure the defaultAuthenticationManager.- Parameters:
authenticationManager- theAuthenticationManagerto use- Returns:
- the
HttpSecurityfor further customizations - Since:
- 5.6
-
beforeConfigure
Description copied from class:AbstractConfiguredSecurityBuilderInvoked prior to invoking eachSecurityConfigurer.configure(SecurityBuilder)method. Subclasses may override this method to hook into the lifecycle without using aSecurityConfigurer.- Overrides:
beforeConfigurein classAbstractConfiguredSecurityBuilder<DefaultSecurityFilterChain,HttpSecurity> - Throws:
Exception
-
performBuild
Description copied from class:AbstractConfiguredSecurityBuilderSubclasses must implement this method to build the object that is being returned.- Specified by:
performBuildin classAbstractConfiguredSecurityBuilder<DefaultSecurityFilterChain,HttpSecurity> - Returns:
- the Object to be buit or null if the implementation allows it
-
authenticationProvider
Description copied from interface:HttpSecurityBuilderAllows adding an additionalAuthenticationProviderto be used- Specified by:
authenticationProviderin interfaceHttpSecurityBuilder<HttpSecurity>- Parameters:
authenticationProvider- theAuthenticationProviderto be added- Returns:
- the
HttpSecurityfor further customizations
-
userDetailsService
Description copied from interface:HttpSecurityBuilderAllows adding an additionalUserDetailsServiceto be used- Specified by:
userDetailsServicein interfaceHttpSecurityBuilder<HttpSecurity>- Parameters:
userDetailsService- theUserDetailsServiceto be added- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception
-
addFilterAfter
public HttpSecurity addFilterAfter(jakarta.servlet.Filter filter, Class<? extends jakarta.servlet.Filter> afterFilter) Description copied from interface:HttpSecurityBuilderAllows adding aFilterafter one of the knownFilterclasses. The knownFilterinstances are either aFilterlisted inHttpSecurityBuilder.addFilter(Filter)or aFilterthat has already been added usingHttpSecurityBuilder.addFilterAfter(Filter, Class)orHttpSecurityBuilder.addFilterBefore(Filter, Class).- Specified by:
addFilterAfterin interfaceHttpSecurityBuilder<HttpSecurity>- Parameters:
filter- theFilterto register after the typeafterFilterafterFilter- the Class of the knownFilter.- Returns:
- the
HttpSecurityfor further customizations
-
addFilterBefore
public HttpSecurity addFilterBefore(jakarta.servlet.Filter filter, Class<? extends jakarta.servlet.Filter> beforeFilter) Description copied from interface:HttpSecurityBuilderAllows adding aFilterbefore one of the knownFilterclasses. The knownFilterinstances are either aFilterlisted inHttpSecurityBuilder.addFilter(Filter)or aFilterthat has already been added usingHttpSecurityBuilder.addFilterAfter(Filter, Class)orHttpSecurityBuilder.addFilterBefore(Filter, Class).- Specified by:
addFilterBeforein interfaceHttpSecurityBuilder<HttpSecurity>- Parameters:
filter- theFilterto register before the typebeforeFilterbeforeFilter- the Class of the knownFilter.- Returns:
- the
HttpSecurityfor further customizations
-
addFilter
Description copied from interface:HttpSecurityBuilderAdds aFilterthat must be an instance of or extend one of the Filters provided within the Security framework. The method ensures that the ordering of the Filters is automatically taken care of. The ordering of the Filters is:DisableEncodeUrlFilterForceEagerSessionCreationFilterChannelProcessingFilterHttpsRedirectFilterWebAsyncManagerIntegrationFilterSecurityContextHolderFilterSecurityContextPersistenceFilterHeaderWriterFilterCorsFilterCsrfFilterLogoutFilterOAuth2AuthorizationRequestRedirectFilterSaml2WebSsoAuthenticationRequestFilterX509AuthenticationFilterAbstractPreAuthenticatedProcessingFilter- CasAuthenticationFilter
OAuth2LoginAuthenticationFilterSaml2WebSsoAuthenticationFilterUsernamePasswordAuthenticationFilterDefaultLoginPageGeneratingFilterDefaultLogoutPageGeneratingFilterConcurrentSessionFilterDigestAuthenticationFilterBearerTokenAuthenticationFilterBasicAuthenticationFilterAuthenticationFilterRequestCacheAwareFilterSecurityContextHolderAwareRequestFilterJaasApiIntegrationFilterRememberMeAuthenticationFilterAnonymousAuthenticationFilterOAuth2AuthorizationCodeGrantFilterSessionManagementFilterExceptionTranslationFilterFilterSecurityInterceptorAuthorizationFilterSwitchUserFilter
- Specified by:
addFilterin interfaceHttpSecurityBuilder<HttpSecurity>- Parameters:
filter- theFilterto add- Returns:
- the
HttpSecurityfor further customizations
-
addFilterAt
public HttpSecurity addFilterAt(jakarta.servlet.Filter filter, Class<? extends jakarta.servlet.Filter> atFilter) Adds the Filter at the location of the specified Filter class. For example, if you want the filter CustomFilter to be registered in the same position asUsernamePasswordAuthenticationFilter, you can invoke:addFilterAt(new CustomFilter(), UsernamePasswordAuthenticationFilter.class)
Registration of multiple Filters in the same location means their ordering is not deterministic. More concretely, registering multiple Filters in the same location does not override existing Filters. Instead, do not register Filters you do not want to use.- Parameters:
filter- the Filter to registeratFilter- the location of anotherFilterthat is already registered (i.e. known) with Spring Security.- Returns:
- the
HttpSecurityfor further customizations
-
securityMatchers
@Deprecated(since="6.1", forRemoval=true) public HttpSecurity.RequestMatcherConfigurer securityMatchers()Deprecated, for removal: This API element is subject to removal in a future version.For removal in 7.0. UsesecurityMatchers(Customizer)orsecurityMatchers(Customizer.withDefaults())to stick with defaults. See the documentation for more details.Allows specifying whichHttpServletRequestinstances thisHttpSecuritywill be invoked on. This method allows for easily invoking theHttpSecurityfor multiple differentRequestMatcherinstances. If only a singleRequestMatcheris necessary consider usingsecurityMatcher(String...), orsecurityMatcher(RequestMatcher).Invoking
securityMatchers()will not override previous invocations ofsecurityMatchers()},securityMatchers(Customizer)securityMatcher(String...)andsecurityMatcher(RequestMatcher)Example Configurations
The following configuration enables theHttpSecurityfor URLs that begin with "/api/" or "/oauth/".@Configuration @EnableWebSecurity public class RequestMatchersSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .securityMatchers((matchers) -> matchers .requestMatchers("/api/**", "/oauth/**") ) .authorizeHttpRequests((authorize) -> authorize anyRequest().hasRole("USER") ) .httpBasic(withDefaults()); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }The configuration below is the same as the previous configuration.@Configuration @EnableWebSecurity public class RequestMatchersSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .securityMatchers((matchers) -> matchers .requestMatchers("/api/**") .requestMatchers("/oauth/**") ) .authorizeHttpRequests((authorize) -> authorize anyRequest().hasRole("USER") ) .httpBasic(withDefaults()); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }The configuration below is also the same as the above configuration.@Configuration @EnableWebSecurity public class RequestMatchersSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .securityMatchers((matchers) -> matchers .requestMatchers("/api/**") ) .securityMatchers((matchers) -> matchers .requestMatchers("/oauth/**") ) .authorizeHttpRequests((authorize) -> authorize anyRequest().hasRole("USER") ) .httpBasic(withDefaults()); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }- Returns:
- the
HttpSecurity.RequestMatcherConfigurerfor further customizations
-
securityMatchers
public HttpSecurity securityMatchers(Customizer<HttpSecurity.RequestMatcherConfigurer> requestMatcherCustomizer) Allows specifying whichHttpServletRequestinstances thisHttpSecuritywill be invoked on. This method allows for easily invoking theHttpSecurityfor multiple differentRequestMatcherinstances. If only a singleRequestMatcheris necessary consider usingsecurityMatcher(String...), orsecurityMatcher(RequestMatcher).Invoking
securityMatchers(Customizer)will not override previous invocations ofsecurityMatchers()},securityMatchers(Customizer)securityMatcher(String...)andsecurityMatcher(RequestMatcher)Example Configurations
The following configuration enables theHttpSecurityfor URLs that begin with "/api/" or "/oauth/".@Configuration @EnableWebSecurity public class RequestMatchersSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .securityMatchers((matchers) -> matchers .requestMatchers("/api/**", "/oauth/**") ) .authorizeHttpRequests((authorize) -> authorize .anyRequest().hasRole("USER") ) .httpBasic(withDefaults()); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }The configuration below is the same as the previous configuration.@Configuration @EnableWebSecurity public class RequestMatchersSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .securityMatchers((matchers) -> matchers .requestMatchers("/api/**") .requestMatchers("/oauth/**") ) .authorizeHttpRequests((authorize) -> authorize .anyRequest().hasRole("USER") ) .httpBasic(withDefaults()); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }The configuration below is also the same as the above configuration.@Configuration @EnableWebSecurity public class RequestMatchersSecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .securityMatchers((matchers) -> matchers .requestMatchers("/api/**") ) .securityMatchers((matchers) -> matchers .requestMatchers("/oauth/**") ) .authorizeHttpRequests((authorize) -> authorize .anyRequest().hasRole("USER") ) .httpBasic(withDefaults()); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }- Parameters:
requestMatcherCustomizer- theCustomizerto provide more options for theHttpSecurity.RequestMatcherConfigurer- Returns:
- the
HttpSecurityfor further customizations
-
securityMatcher
Allows configuring theHttpSecurityto only be invoked when matching the providedRequestMatcher. If more advanced configuration is necessary, consider usingsecurityMatchers(Customizer)()}.Invoking
securityMatcher(RequestMatcher)will override previous invocations ofsecurityMatcher(RequestMatcher),securityMatcher(String...),securityMatchers(Customizer)andsecurityMatchers()- Parameters:
requestMatcher- theRequestMatcherto use, for example,PathPatternRequestMatcher.withDefaults().matcher(HttpMethod.GET, "/admin/**")- Returns:
- the
HttpSecurityfor further customizations - See Also:
-
securityMatcher
Allows configuring theHttpSecurityto only be invoked when matching the provided pattern. This method creates aMvcRequestMatcherif Spring MVC is in the classpath or creates anAntPathRequestMatcherif not. If more advanced configuration is necessary, consider usingsecurityMatchers(Customizer)orsecurityMatcher(RequestMatcher).Invoking
securityMatcher(String...)will override previous invocations ofsecurityMatcher(String...)(String)}},securityMatcher(RequestMatcher)()},securityMatchers(Customizer)(String)} andsecurityMatchers()(String)}.- Parameters:
patterns- the pattern to match on (i.e. "/admin/**")- Returns:
- the
HttpSecurityfor further customizations - See Also:
-
webAuthn
public HttpSecurity webAuthn(Customizer<WebAuthnConfigurer<HttpSecurity>> webAuthn) throws Exception Specifies webAuthn/passkeys based authentication.@Bean SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http // ... .webAuthn((webAuthn) -> webAuthn .rpName("Spring Security Relying Party") .rpId("example.com") .allowedOrigins("https://example.com") ); return http.build(); }- Parameters:
webAuthn- the customizer to apply- Returns:
- the
HttpSecurityfor further customizations - Throws:
Exception
-