Class HttpSecurity
- java.lang.Object
-
- org.springframework.security.config.annotation.AbstractSecurityBuilder<O>
-
- org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder<DefaultSecurityFilterChain,HttpSecurity>
-
- org.springframework.security.config.annotation.web.builders.HttpSecurity
-
- All Implemented Interfaces:
SecurityBuilder<DefaultSecurityFilterChain>
,HttpSecurityBuilder<HttpSecurity>
public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<DefaultSecurityFilterChain,HttpSecurity> implements SecurityBuilder<DefaultSecurityFilterChain>, HttpSecurityBuilder<HttpSecurity>
AHttpSecurity
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 usingrequestMatcher(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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); } }
- Since:
- 3.2
- See Also:
EnableWebSecurity
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description class
HttpSecurity.MvcMatchersRequestMatcherConfigurer
An extension toHttpSecurity.RequestMatcherConfigurer
that allows optionally configuring the servlet path.class
HttpSecurity.RequestMatcherConfigurer
Allows mapping HTTP requests that thisHttpSecurity
will be used for
-
Constructor Summary
Constructors Constructor Description HttpSecurity(ObjectPostProcessor<java.lang.Object> objectPostProcessor, AuthenticationManagerBuilder authenticationBuilder, java.util.Map<java.lang.Class<?>,java.lang.Object> sharedObjects)
Creates a new instance
-
Method Summary
All Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description HttpSecurity
addFilter(javax.servlet.Filter filter)
Adds aFilter
that must be an instance of or extend one of the Filters provided within the Security framework.HttpSecurity
addFilterAfter(javax.servlet.Filter filter, java.lang.Class<? extends javax.servlet.Filter> afterFilter)
Allows adding aFilter
after one of the knownFilter
classes.HttpSecurity
addFilterAt(javax.servlet.Filter filter, java.lang.Class<? extends javax.servlet.Filter> atFilter)
Adds the Filter at the location of the specified Filter class.HttpSecurity
addFilterBefore(javax.servlet.Filter filter, java.lang.Class<? extends javax.servlet.Filter> beforeFilter)
Allows adding aFilter
before one of the knownFilter
classes.AnonymousConfigurer<HttpSecurity>
anonymous()
Allows configuring how an anonymous user is represented.HttpSecurity
anonymous(Customizer<AnonymousConfigurer<HttpSecurity>> anonymousCustomizer)
Allows configuring how an anonymous user is represented.HttpSecurity
antMatcher(java.lang.String antPattern)
Allows configuring theHttpSecurity
to only be invoked when matching the provided ant pattern.HttpSecurity
authenticationProvider(AuthenticationProvider authenticationProvider)
Allows adding an additionalAuthenticationProvider
to be usedHttpSecurity
authorizeHttpRequests(Customizer<AuthorizeHttpRequestsConfigurer.AuthorizationManagerRequestMatcherRegistry> authorizeHttpRequestsCustomizer)
Allows restricting access based upon theHttpServletRequest
usingRequestMatcher
implementations (i.e.ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry
authorizeRequests()
Allows restricting access based upon theHttpServletRequest
usingRequestMatcher
implementations (i.e.HttpSecurity
authorizeRequests(Customizer<ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry> authorizeRequestsCustomizer)
Allows restricting access based upon theHttpServletRequest
usingRequestMatcher
implementations (i.e.protected void
beforeConfigure()
Invoked prior to invoking eachSecurityConfigurer.configure(SecurityBuilder)
method.CorsConfigurer<HttpSecurity>
cors()
Adds aCorsFilter
to be used.HttpSecurity
cors(Customizer<CorsConfigurer<HttpSecurity>> corsCustomizer)
Adds aCorsFilter
to be used.CsrfConfigurer<HttpSecurity>
csrf()
Enables CSRF protection.HttpSecurity
csrf(Customizer<CsrfConfigurer<HttpSecurity>> csrfCustomizer)
Enables CSRF protection.ExceptionHandlingConfigurer<HttpSecurity>
exceptionHandling()
Allows configuring exception handling.HttpSecurity
exceptionHandling(Customizer<ExceptionHandlingConfigurer<HttpSecurity>> exceptionHandlingCustomizer)
Allows configuring exception handling.FormLoginConfigurer<HttpSecurity>
formLogin()
Specifies to support form based authentication.HttpSecurity
formLogin(Customizer<FormLoginConfigurer<HttpSecurity>> formLoginCustomizer)
Specifies to support form based authentication.HeadersConfigurer<HttpSecurity>
headers()
Adds the Security headers to the response.HttpSecurity
headers(Customizer<HeadersConfigurer<HttpSecurity>> headersCustomizer)
Adds the Security headers to the response.HttpBasicConfigurer<HttpSecurity>
httpBasic()
Configures HTTP Basic authentication.HttpSecurity
httpBasic(Customizer<HttpBasicConfigurer<HttpSecurity>> httpBasicCustomizer)
Configures HTTP Basic authentication.JeeConfigurer<HttpSecurity>
jee()
Configures container based pre authentication.HttpSecurity
jee(Customizer<JeeConfigurer<HttpSecurity>> jeeCustomizer)
Configures container based pre authentication.LogoutConfigurer<HttpSecurity>
logout()
Provides logout support.HttpSecurity
logout(Customizer<LogoutConfigurer<HttpSecurity>> logoutCustomizer)
Provides logout support.HttpSecurity
mvcMatcher(java.lang.String mvcPattern)
Allows configuring theHttpSecurity
to only be invoked when matching the provided Spring MVC pattern.OAuth2ClientConfigurer<HttpSecurity>
oauth2Client()
Configures OAuth 2.0 Client support.HttpSecurity
oauth2Client(Customizer<OAuth2ClientConfigurer<HttpSecurity>> oauth2ClientCustomizer)
Configures OAuth 2.0 Client support.OAuth2LoginConfigurer<HttpSecurity>
oauth2Login()
Configures authentication support using an OAuth 2.0 and/or OpenID Connect 1.0 Provider.HttpSecurity
oauth2Login(Customizer<OAuth2LoginConfigurer<HttpSecurity>> oauth2LoginCustomizer)
Configures authentication support using an OAuth 2.0 and/or OpenID Connect 1.0 Provider.OAuth2ResourceServerConfigurer<HttpSecurity>
oauth2ResourceServer()
Configures OAuth 2.0 Resource Server support.HttpSecurity
oauth2ResourceServer(Customizer<OAuth2ResourceServerConfigurer<HttpSecurity>> oauth2ResourceServerCustomizer)
Configures OAuth 2.0 Resource Server support.OpenIDLoginConfigurer<HttpSecurity>
openidLogin()
Deprecated.The OpenID 1.0 and 2.0 protocols have been deprecated and users are encouraged to migrate to OpenID Connect, which is supported byspring-security-oauth2
.HttpSecurity
openidLogin(Customizer<OpenIDLoginConfigurer<HttpSecurity>> openidLoginCustomizer)
Deprecated.The OpenID 1.0 and 2.0 protocols have been deprecated and users are encouraged to migrate to OpenID Connect, which is supported byspring-security-oauth2
.protected DefaultSecurityFilterChain
performBuild()
Subclasses must implement this method to build the object that is being returned.PortMapperConfigurer<HttpSecurity>
portMapper()
Allows configuring aPortMapper
that is available fromAbstractConfiguredSecurityBuilder.getSharedObject(Class)
.HttpSecurity
portMapper(Customizer<PortMapperConfigurer<HttpSecurity>> portMapperCustomizer)
Allows configuring aPortMapper
that is available fromAbstractConfiguredSecurityBuilder.getSharedObject(Class)
.HttpSecurity
regexMatcher(java.lang.String pattern)
Allows configuring theHttpSecurity
to only be invoked when matching the provided regex pattern.RememberMeConfigurer<HttpSecurity>
rememberMe()
Allows configuring of Remember Me authentication.HttpSecurity
rememberMe(Customizer<RememberMeConfigurer<HttpSecurity>> rememberMeCustomizer)
Allows configuring of Remember Me authentication.RequestCacheConfigurer<HttpSecurity>
requestCache()
Allows configuring the Request Cache.HttpSecurity
requestCache(Customizer<RequestCacheConfigurer<HttpSecurity>> requestCacheCustomizer)
Allows configuring the Request Cache.HttpSecurity
requestMatcher(RequestMatcher requestMatcher)
Allows configuring theHttpSecurity
to only be invoked when matching the providedRequestMatcher
.HttpSecurity.RequestMatcherConfigurer
requestMatchers()
Allows specifying whichHttpServletRequest
instances thisHttpSecurity
will be invoked on.HttpSecurity
requestMatchers(Customizer<HttpSecurity.RequestMatcherConfigurer> requestMatcherCustomizer)
Allows specifying whichHttpServletRequest
instances thisHttpSecurity
will be invoked on.ChannelSecurityConfigurer.ChannelRequestMatcherRegistry
requiresChannel()
Configures channel security.HttpSecurity
requiresChannel(Customizer<ChannelSecurityConfigurer.ChannelRequestMatcherRegistry> requiresChannelCustomizer)
Configures channel security.Saml2LoginConfigurer<HttpSecurity>
saml2Login()
Configures authentication support using an SAML 2.0 Service Provider.HttpSecurity
saml2Login(Customizer<Saml2LoginConfigurer<HttpSecurity>> saml2LoginCustomizer)
Configures authentication support using an SAML 2.0 Service Provider.SecurityContextConfigurer<HttpSecurity>
securityContext()
Sets up management of theSecurityContext
on theSecurityContextHolder
betweenHttpServletRequest
's.HttpSecurity
securityContext(Customizer<SecurityContextConfigurer<HttpSecurity>> securityContextCustomizer)
Sets up management of theSecurityContext
on theSecurityContextHolder
betweenHttpServletRequest
's.ServletApiConfigurer<HttpSecurity>
servletApi()
Integrates theHttpServletRequest
methods with the values found on theSecurityContext
.HttpSecurity
servletApi(Customizer<ServletApiConfigurer<HttpSecurity>> servletApiCustomizer)
Integrates theHttpServletRequest
methods with the values found on theSecurityContext
.SessionManagementConfigurer<HttpSecurity>
sessionManagement()
Allows configuring of Session Management.HttpSecurity
sessionManagement(Customizer<SessionManagementConfigurer<HttpSecurity>> sessionManagementCustomizer)
Allows configuring of Session Management.<C> void
setSharedObject(java.lang.Class<C> sharedType, C object)
Sets an object that is shared by multipleSecurityConfigurer
.HttpSecurity
userDetailsService(UserDetailsService userDetailsService)
Allows adding an additionalUserDetailsService
to be usedX509Configurer<HttpSecurity>
x509()
Configures X509 based pre authentication.HttpSecurity
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
-
Methods inherited from class org.springframework.security.config.annotation.AbstractSecurityBuilder
build, getObject
-
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
-
Methods inherited from interface org.springframework.security.config.annotation.web.HttpSecurityBuilder
getConfigurer, getSharedObject, removeConfigurer
-
Methods inherited from interface org.springframework.security.config.annotation.SecurityBuilder
build
-
-
-
-
Constructor Detail
-
HttpSecurity
public HttpSecurity(ObjectPostProcessor<java.lang.Object> objectPostProcessor, AuthenticationManagerBuilder authenticationBuilder, java.util.Map<java.lang.Class<?>,java.lang.Object> sharedObjects)
Creates a new instance- Parameters:
objectPostProcessor
- theObjectPostProcessor
that should be usedauthenticationBuilder
- theAuthenticationManagerBuilder
to use for additional updatessharedObjects
- the shared Objects to initialize theHttpSecurity
with- See Also:
WebSecurityConfiguration
-
-
Method Detail
-
openidLogin
@Deprecated public OpenIDLoginConfigurer<HttpSecurity> openidLogin() throws java.lang.Exception
Deprecated.The OpenID 1.0 and 2.0 protocols have been deprecated and users are encouraged to migrate to OpenID Connect, which is supported byspring-security-oauth2
.Allows configuring OpenID based authentication.Example Configurations
A basic example accepting the defaults and not using attribute exchange:@Configuration @EnableWebSecurity public class OpenIDLoginConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) { http.authorizeRequests().antMatchers("/**").hasRole("USER").and().openidLogin() .permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() // the username must match the OpenID of the user you are // logging in with .withUser( "https://www.google.com/accounts/o8/id?id=lmkCn9xzPdsxVwG7pjYMuDgNNdASFmobNkcRPaWU") .password("password").roles("USER"); } }
A more advanced example demonstrating using attribute exchange and providing a custom AuthenticationUserDetailsService that will make any user that authenticates a valid user.@Configuration @EnableWebSecurity public class OpenIDLoginConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) { http.authorizeRequests() .antMatchers("/**") .hasRole("USER") .and() .openidLogin() .loginPage("/login") .permitAll() .authenticationUserDetailsService( new AutoProvisioningUserDetailsService()) .attributeExchange("https://www.google.com/.*").attribute("email") .type("https://axschema.org/contact/email").required(true).and() .attribute("firstname").type("https://axschema.org/namePerson/first") .required(true).and().attribute("lastname") .type("https://axschema.org/namePerson/last").required(true).and().and() .attributeExchange(".*yahoo.com.*").attribute("email") .type("https://schema.openid.net/contact/email").required(true).and() .attribute("fullname").type("https://axschema.org/namePerson") .required(true).and().and().attributeExchange(".*myopenid.com.*") .attribute("email").type("https://schema.openid.net/contact/email") .required(true).and().attribute("fullname") .type("https://schema.openid.net/namePerson").required(true); } } public class AutoProvisioningUserDetailsService implements AuthenticationUserDetailsService<OpenIDAuthenticationToken> { public UserDetails loadUserDetails(OpenIDAuthenticationToken token) throws UsernameNotFoundException { return new User(token.getName(), "NOTUSED", AuthorityUtils.createAuthorityList("ROLE_USER")); } }
- Returns:
- the
OpenIDLoginConfigurer
for further customizations. - Throws:
java.lang.Exception
- See Also:
OpenIDLoginConfigurer
-
openidLogin
@Deprecated public HttpSecurity openidLogin(Customizer<OpenIDLoginConfigurer<HttpSecurity>> openidLoginCustomizer) throws java.lang.Exception
Deprecated.The OpenID 1.0 and 2.0 protocols have been deprecated and users are encouraged to migrate to OpenID Connect, which is supported byspring-security-oauth2
.Allows configuring OpenID based authentication.Example Configurations
A basic example accepting the defaults and not using attribute exchange:@Configuration @EnableWebSecurity public class OpenIDLoginConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) { http .authorizeRequests((authorizeRequests) -> authorizeRequests .antMatchers("/**").hasRole("USER") ) .openidLogin((openidLogin) -> openidLogin .permitAll() ); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() // the username must match the OpenID of the user you are // logging in with .withUser( "https://www.google.com/accounts/o8/id?id=lmkCn9xzPdsxVwG7pjYMuDgNNdASFmobNkcRPaWU") .password("password").roles("USER"); } }
A more advanced example demonstrating using attribute exchange and providing a custom AuthenticationUserDetailsService that will make any user that authenticates a valid user.@Configuration @EnableWebSecurity public class OpenIDLoginConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests((authorizeRequests) -> authorizeRequests .antMatchers("/**").hasRole("USER") ) .openidLogin((openidLogin) -> openidLogin .loginPage("/login") .permitAll() .authenticationUserDetailsService( new AutoProvisioningUserDetailsService()) .attributeExchange((googleExchange) -> googleExchange .identifierPattern("https://www.google.com/.*") .attribute((emailAttribute) -> emailAttribute .name("email") .type("https://axschema.org/contact/email") .required(true) ) .attribute((firstnameAttribute) -> firstnameAttribute .name("firstname") .type("https://axschema.org/namePerson/first") .required(true) ) .attribute((lastnameAttribute) -> lastnameAttribute .name("lastname") .type("https://axschema.org/namePerson/last") .required(true) ) ) .attributeExchange((yahooExchange) -> yahooExchange .identifierPattern(".*yahoo.com.*") .attribute((emailAttribute) -> emailAttribute .name("email") .type("https://schema.openid.net/contact/email") .required(true) ) .attribute((fullnameAttribute) -> fullnameAttribute .name("fullname") .type("https://axschema.org/namePerson") .required(true) ) ) ); } } public class AutoProvisioningUserDetailsService implements AuthenticationUserDetailsService<OpenIDAuthenticationToken> { public UserDetails loadUserDetails(OpenIDAuthenticationToken token) throws UsernameNotFoundException { return new User(token.getName(), "NOTUSED", AuthorityUtils.createAuthorityList("ROLE_USER")); } }
- Parameters:
openidLoginCustomizer
- theCustomizer
to provide more options for theOpenIDLoginConfigurer
- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
- See Also:
OpenIDLoginConfigurer
-
headers
public HeadersConfigurer<HttpSecurity> headers() throws java.lang.Exception
Adds the Security headers to the response. This is activated by default when usingWebSecurityConfigurerAdapter
's default constructor. Accepting the default provided byWebSecurityConfigurerAdapter
or only invokingheaders()
without invoking additional methods on it, is the equivalent of:@Configuration @EnableWebSecurity public class CsrfSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .headers() .contentTypeOptions() .and() .xssProtection() .and() .cacheControl() .and() .httpStrictTransportSecurity() .and() .frameOptions() .and() ...; } }
You can disable the headers using the following:@Configuration @EnableWebSecurity public class CsrfSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .headers().disable() ...; } }
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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .headers() .defaultsDisabled() .cacheControl() .and() .frameOptions() .and() ...; } }
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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .headers() .frameOptions() .disable() .and() ...; } }
- Returns:
- the
HeadersConfigurer
for further customizations - Throws:
java.lang.Exception
- See Also:
HeadersConfigurer
-
headers
public HttpSecurity headers(Customizer<HeadersConfigurer<HttpSecurity>> headersCustomizer) throws java.lang.Exception
Adds the Security headers to the response. This is activated by default when usingWebSecurityConfigurerAdapter
's default constructor.Example Configurations
Accepting the default provided byWebSecurityConfigurerAdapter
or only invokingheaders()
without invoking additional methods on it, is the equivalent of:@Configuration @EnableWebSecurity public class CsrfSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .headers((headers) -> headers .contentTypeOptions(withDefaults()) .xssProtection(withDefaults()) .cacheControl(withDefaults()) .httpStrictTransportSecurity(withDefaults()) .frameOptions(withDefaults() ); } }
You can disable the headers using the following:@Configuration @EnableWebSecurity public class CsrfSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .headers((headers) -> headers.disable()); } }
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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .headers((headers) -> headers .defaultsDisabled() .cacheControl(withDefaults()) .frameOptions(withDefaults()) ); } }
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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .headers((headers) -> headers .frameOptions((frameOptions) -> frameOptions.disable()) ); }
- Parameters:
headersCustomizer
- theCustomizer
to provide more options for theHeadersConfigurer
- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
-
cors
public CorsConfigurer<HttpSecurity> cors() throws java.lang.Exception
Adds aCorsFilter
to be used. If a bean by the name of corsFilter is provided, thatCorsFilter
is used. Else if corsConfigurationSource is defined, then thatCorsConfiguration
is used. Otherwise, if Spring MVC is on the classpath aHandlerMappingIntrospector
is used.- Returns:
- the
CorsConfigurer
for customizations - Throws:
java.lang.Exception
-
cors
public HttpSecurity cors(Customizer<CorsConfigurer<HttpSecurity>> corsCustomizer) throws java.lang.Exception
Adds aCorsFilter
to be used. If a bean by the name of corsFilter is provided, thatCorsFilter
is used. Else if corsConfigurationSource is defined, then thatCorsConfiguration
is used. Otherwise, if Spring MVC is on the classpath aHandlerMappingIntrospector
is used. You can enable CORS using:@Configuration @EnableWebSecurity public class CorsSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .cors(withDefaults()); } }
- Parameters:
corsCustomizer
- theCustomizer
to provide more options for theCorsConfigurer
- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
-
sessionManagement
public SessionManagementConfigurer<HttpSecurity> sessionManagement() throws java.lang.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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().anyRequest().hasRole("USER").and().formLogin() .permitAll().and().sessionManagement().maximumSessions(1) .expiredUrl("/login?expired"); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); } }
When usingSessionManagementConfigurer.maximumSessions(int)
, do not forget to configureHttpSessionEventPublisher
for 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
SessionManagementConfigurer
for further customizations - Throws:
java.lang.Exception
-
sessionManagement
public HttpSecurity sessionManagement(Customizer<SessionManagementConfigurer<HttpSecurity>> sessionManagementCustomizer) throws java.lang.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 extends WebSecurityConfigurerAdapter { @Override protected void configure(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") ) ); } }
When usingSessionManagementConfigurer.maximumSessions(int)
, do not forget to configureHttpSessionEventPublisher
for 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
- theCustomizer
to provide more options for theSessionManagementConfigurer
- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
-
portMapper
public PortMapperConfigurer<HttpSecurity> portMapper() throws java.lang.Exception
Allows configuring aPortMapper
that is available fromAbstractConfiguredSecurityBuilder.getSharedObject(Class)
. Other providedSecurityConfigurer
objects use this configuredPortMapper
as a defaultPortMapper
when redirecting from HTTP to HTTPS or from HTTPS to HTTP (for example when used in combination withrequiresChannel()
. By default Spring Security uses aPortMapperImpl
which 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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin() .permitAll().and() // Example portMapper() configuration .portMapper().http(9090).mapsTo(9443).http(80).mapsTo(443); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); } }
- Returns:
- the
PortMapperConfigurer
for further customizations - Throws:
java.lang.Exception
- See Also:
requiresChannel()
-
portMapper
public HttpSecurity portMapper(Customizer<PortMapperConfigurer<HttpSecurity>> portMapperCustomizer) throws java.lang.Exception
Allows configuring aPortMapper
that is available fromAbstractConfiguredSecurityBuilder.getSharedObject(Class)
. Other providedSecurityConfigurer
objects use this configuredPortMapper
as a defaultPortMapper
when redirecting from HTTP to HTTPS or from HTTPS to HTTP (for example when used in combination withrequiresChannel()
. By default Spring Security uses aPortMapperImpl
which 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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .requiresChannel((requiresChannel) -> requiresChannel .anyRequest().requiresSecure() ) .portMapper((portMapper) -> portMapper .http(9090).mapsTo(9443) .http(80).mapsTo(443) ); } }
- Parameters:
portMapperCustomizer
- theCustomizer
to provide more options for thePortMapperConfigurer
- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
- See Also:
requiresChannel()
-
jee
public JeeConfigurer<HttpSecurity> jee() throws java.lang.Exception
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 theHttpServletRequest
and if the user is in the role "ROLE_USER" or "ROLE_ADMIN" will add that to the resultingAuthentication
.@Configuration @EnableWebSecurity public class JeeSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/**").hasRole("USER").and() // Example jee() configuration .jee().mappableRoles("USER", "ADMIN"); } }
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
JeeConfigurer
for further customizations - Throws:
java.lang.Exception
-
jee
public HttpSecurity jee(Customizer<JeeConfigurer<HttpSecurity>> jeeCustomizer) throws java.lang.Exception
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 theHttpServletRequest
and if the user is in the role "ROLE_USER" or "ROLE_ADMIN" will add that to the resultingAuthentication
.@Configuration @EnableWebSecurity public class JeeSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .antMatchers("/**").hasRole("USER") ) .jee((jee) -> jee .mappableRoles("USER", "ADMIN") ); } }
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
- theCustomizer
to provide more options for theJeeConfigurer
- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
-
x509
public X509Configurer<HttpSecurity> x509() throws java.lang.Exception
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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/**").hasRole("USER").and() // Example x509() configuration .x509(); } }
- Returns:
- the
X509Configurer
for further customizations - Throws:
java.lang.Exception
-
x509
public HttpSecurity x509(Customizer<X509Configurer<HttpSecurity>> x509Customizer) throws java.lang.Exception
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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .antMatchers("/**").hasRole("USER") ) .x509(withDefaults()); } }
- Parameters:
x509Customizer
- theCustomizer
to provide more options for theX509Configurer
- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
-
rememberMe
public RememberMeConfigurer<HttpSecurity> rememberMe() throws java.lang.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 theirHttpSession
expires.@Configuration @EnableWebSecurity public class RememberMeSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin() .permitAll().and() // Example Remember Me Configuration .rememberMe(); } }
- Returns:
- the
RememberMeConfigurer
for further customizations - Throws:
java.lang.Exception
-
rememberMe
public HttpSecurity rememberMe(Customizer<RememberMeConfigurer<HttpSecurity>> rememberMeCustomizer) throws java.lang.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 theirHttpSession
expires.@Configuration @EnableWebSecurity public class RememberMeSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .antMatchers("/**").hasRole("USER") ) .formLogin(withDefaults()) .rememberMe(withDefaults()); } }
- Parameters:
rememberMeCustomizer
- theCustomizer
to provide more options for theRememberMeConfigurer
- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
-
authorizeRequests
public ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry authorizeRequests() throws java.lang.Exception
Allows restricting access based upon theHttpServletRequest
usingRequestMatcher
implementations (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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password("password").roles("USER") .and().withUser("admin").password("password").roles("ADMIN", "USER"); } }
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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/**").hasRole("USER").and().formLogin(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password("password").roles("USER") .and().withUser("admin").password("password").roles("ADMIN", "USER"); } }
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:http.authorizeRequests().antMatchers("/**").hasRole("USER").antMatchers("/admin/**") .hasRole("ADMIN")
- Returns:
- the
ExpressionUrlAuthorizationConfigurer
for further customizations - Throws:
java.lang.Exception
- See Also:
requestMatcher(RequestMatcher)
-
authorizeRequests
public HttpSecurity authorizeRequests(Customizer<ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry> authorizeRequestsCustomizer) throws java.lang.Exception
Allows restricting access based upon theHttpServletRequest
usingRequestMatcher
implementations (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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .antMatchers("/**").hasRole("USER") ) .formLogin(withDefaults()); } }
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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/**").hasRole("USER") ) .formLogin(withDefaults()); } }
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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .antMatchers("/**").hasRole("USER") .antMatchers("/admin/**").hasRole("ADMIN") ); } }
- Parameters:
authorizeRequestsCustomizer
- theCustomizer
to provide more options for theExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry
- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
- See Also:
requestMatcher(RequestMatcher)
-
authorizeHttpRequests
public HttpSecurity authorizeHttpRequests(Customizer<AuthorizeHttpRequestsConfigurer.AuthorizationManagerRequestMatcherRegistry> authorizeHttpRequestsCustomizer) throws java.lang.Exception
Allows restricting access based upon theHttpServletRequest
usingRequestMatcher
implementations (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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeHttpRequests((authorizeHttpRequests) -> authorizeHttpRequests .antMatchers("/**").hasRole("USER") ) .formLogin(withDefaults()); } }
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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeHttpRequests((authorizeHttpRequests) -> authorizeHttpRequests .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/**").hasRole("USER") ) .formLogin(withDefaults()); } }
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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeHttpRequests((authorizeHttpRequests) -> authorizeHttpRequests .antMatchers("/**").hasRole("USER") .antMatchers("/admin/**").hasRole("ADMIN") ); } }
- Parameters:
authorizeHttpRequestsCustomizer
- theCustomizer
to provide more options for theAuthorizeHttpRequestsConfigurer.AuthorizationManagerRequestMatcherRegistry
- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
- Since:
- 5.5
- See Also:
requestMatcher(RequestMatcher)
-
requestCache
public RequestCacheConfigurer<HttpSecurity> requestCache() throws java.lang.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 usingWebSecurityConfigurerAdapter
.- Returns:
- the
RequestCacheConfigurer
for further customizations - Throws:
java.lang.Exception
-
requestCache
public HttpSecurity requestCache(Customizer<RequestCacheConfigurer<HttpSecurity>> requestCacheCustomizer) throws java.lang.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 usingWebSecurityConfigurerAdapter
.Example Custom Configuration
The following example demonstrates how to disable request caching.@Configuration @EnableWebSecurity public class RequestCacheDisabledSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .antMatchers("/**").hasRole("USER") ) .requestCache((requestCache) -> requestCache.disable() ); } }
- Parameters:
requestCacheCustomizer
- theCustomizer
to provide more options for theRequestCacheConfigurer
- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
-
exceptionHandling
public ExceptionHandlingConfigurer<HttpSecurity> exceptionHandling() throws java.lang.Exception
Allows configuring exception handling. This is automatically applied when usingWebSecurityConfigurerAdapter
.- Returns:
- the
ExceptionHandlingConfigurer
for further customizations - Throws:
java.lang.Exception
-
exceptionHandling
public HttpSecurity exceptionHandling(Customizer<ExceptionHandlingConfigurer<HttpSecurity>> exceptionHandlingCustomizer) throws java.lang.Exception
Allows configuring exception handling. This is automatically applied when usingWebSecurityConfigurerAdapter
.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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .antMatchers("/**").hasRole("USER") ) // sample exception handling customization .exceptionHandling((exceptionHandling) -> exceptionHandling .accessDeniedPage("/errors/access-denied") ); } }
- Parameters:
exceptionHandlingCustomizer
- theCustomizer
to provide more options for theExceptionHandlingConfigurer
- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
-
securityContext
public SecurityContextConfigurer<HttpSecurity> securityContext() throws java.lang.Exception
Sets up management of theSecurityContext
on theSecurityContextHolder
betweenHttpServletRequest
's. This is automatically applied when usingWebSecurityConfigurerAdapter
.- Returns:
- the
SecurityContextConfigurer
for further customizations - Throws:
java.lang.Exception
-
securityContext
public HttpSecurity securityContext(Customizer<SecurityContextConfigurer<HttpSecurity>> securityContextCustomizer) throws java.lang.Exception
Sets up management of theSecurityContext
on theSecurityContextHolder
betweenHttpServletRequest
's. This is automatically applied when usingWebSecurityConfigurerAdapter
. The following customization specifies the sharedSecurityContextRepository
@Configuration @EnableWebSecurity public class SecurityContextSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .securityContext((securityContext) -> securityContext .securityContextRepository(SCR) ); } }
- Parameters:
securityContextCustomizer
- theCustomizer
to provide more options for theSecurityContextConfigurer
- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
-
servletApi
public ServletApiConfigurer<HttpSecurity> servletApi() throws java.lang.Exception
Integrates theHttpServletRequest
methods with the values found on theSecurityContext
. This is automatically applied when usingWebSecurityConfigurerAdapter
.- Returns:
- the
ServletApiConfigurer
for further customizations - Throws:
java.lang.Exception
-
servletApi
public HttpSecurity servletApi(Customizer<ServletApiConfigurer<HttpSecurity>> servletApiCustomizer) throws java.lang.Exception
Integrates theHttpServletRequest
methods with the values found on theSecurityContext
. This is automatically applied when usingWebSecurityConfigurerAdapter
. You can disable it using:@Configuration @EnableWebSecurity public class ServletApiSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .servletApi((servletApi) -> servletApi.disable() ); } }
- Parameters:
servletApiCustomizer
- theCustomizer
to provide more options for theServletApiConfigurer
- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
-
csrf
public CsrfConfigurer<HttpSecurity> csrf() throws java.lang.Exception
Enables CSRF protection. This is activated by default when usingWebSecurityConfigurerAdapter
's default constructor. You can disable it using:@Configuration @EnableWebSecurity public class CsrfSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() ...; } }
- Returns:
- the
CsrfConfigurer
for further customizations - Throws:
java.lang.Exception
-
csrf
public HttpSecurity csrf(Customizer<CsrfConfigurer<HttpSecurity>> csrfCustomizer) throws java.lang.Exception
Enables CSRF protection. This is activated by default when usingWebSecurityConfigurerAdapter
's default constructor. You can disable it using:@Configuration @EnableWebSecurity public class CsrfSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .csrf((csrf) -> csrf.disable()); } }
- Parameters:
csrfCustomizer
- theCustomizer
to provide more options for theCsrfConfigurer
- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
-
logout
public LogoutConfigurer<HttpSecurity> logout() throws java.lang.Exception
Provides logout support. This is automatically applied when usingWebSecurityConfigurerAdapter
. 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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin() .and() // sample logout customization .logout().deleteCookies("remove").invalidateHttpSession(false) .logoutUrl("/custom-logout").logoutSuccessUrl("/logout-success"); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); } }
- Returns:
- the
LogoutConfigurer
for further customizations - Throws:
java.lang.Exception
-
logout
public HttpSecurity logout(Customizer<LogoutConfigurer<HttpSecurity>> logoutCustomizer) throws java.lang.Exception
Provides logout support. This is automatically applied when usingWebSecurityConfigurerAdapter
. 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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .antMatchers("/**").hasRole("USER") ) .formLogin(withDefaults()) // sample logout customization .logout((logout) -> logout.deleteCookies("remove") .invalidateHttpSession(false) .logoutUrl("/custom-logout") .logoutSuccessUrl("/logout-success") ); } }
- Parameters:
logoutCustomizer
- theCustomizer
to provide more options for theLogoutConfigurer
- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
-
anonymous
public AnonymousConfigurer<HttpSecurity> anonymous() throws java.lang.Exception
Allows configuring how an anonymous user is represented. This is automatically applied when used in conjunction withWebSecurityConfigurerAdapter
. By default anonymous users will be represented with anAnonymousAuthenticationToken
and 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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/**").hasRole("USER") .and() .formLogin() .and() // sample anonymous customization .anonymous().authorities("ROLE_ANON"); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); } }
The following demonstrates how to represent anonymous users as null. Note that this can causeNullPointerException
in code that assumes anonymous authentication is enabled.@Configuration @EnableWebSecurity public class AnonymousSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/**").hasRole("USER") .and() .formLogin() .and() // sample anonymous customization .anonymous().disable(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); } }
- Returns:
- the
AnonymousConfigurer
for further customizations - Throws:
java.lang.Exception
-
anonymous
public HttpSecurity anonymous(Customizer<AnonymousConfigurer<HttpSecurity>> anonymousCustomizer) throws java.lang.Exception
Allows configuring how an anonymous user is represented. This is automatically applied when used in conjunction withWebSecurityConfigurerAdapter
. By default anonymous users will be represented with anAnonymousAuthenticationToken
and 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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .antMatchers("/**").hasRole("USER") ) .formLogin(withDefaults()) // sample anonymous customization .anonymous((anonymous) -> anonymous .authorities("ROLE_ANON") ) } }
The following demonstrates how to represent anonymous users as null. Note that this can causeNullPointerException
in code that assumes anonymous authentication is enabled.@Configuration @EnableWebSecurity public class AnonymousSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .antMatchers("/**").hasRole("USER") ) .formLogin(withDefaults()) // sample anonymous customization .anonymous((anonymous) -> anonymous.disable() ); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); } }
- Parameters:
anonymousCustomizer
- theCustomizer
to provide more options for theAnonymousConfigurer
- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
-
formLogin
public FormLoginConfigurer<HttpSecurity> formLogin() throws java.lang.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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); } }
The configuration below demonstrates customizing the defaults.@Configuration @EnableWebSecurity public class FormLoginSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/**").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 } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); } }
- Returns:
- the
FormLoginConfigurer
for further customizations - Throws:
java.lang.Exception
- See Also:
FormLoginConfigurer.loginPage(String)
-
formLogin
public HttpSecurity formLogin(Customizer<FormLoginConfigurer<HttpSecurity>> formLoginCustomizer) throws java.lang.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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .antMatchers("/**").hasRole("USER") ) .formLogin(withDefaults()); } }
The configuration below demonstrates customizing the defaults.@Configuration @EnableWebSecurity public class FormLoginSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .antMatchers("/**").hasRole("USER") ) .formLogin((formLogin) -> formLogin .usernameParameter("username") .passwordParameter("password") .loginPage("/authentication/login") .failureUrl("/authentication/login?failed") .loginProcessingUrl("/authentication/login/process") ); } }
- Parameters:
formLoginCustomizer
- theCustomizer
to provide more options for theFormLoginConfigurer
- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
- See Also:
FormLoginConfigurer.loginPage(String)
-
saml2Login
public Saml2LoginConfigurer<HttpSecurity> saml2Login() throws java.lang.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 theApplicationContext
or 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 public class Saml2LoginConfig { @EnableWebSecurity public static class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .saml2Login(); } } @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
Saml2LoginConfigurer
for further customizations - Throws:
java.lang.Exception
- Since:
- 5.2
-
saml2Login
public HttpSecurity saml2Login(Customizer<Saml2LoginConfigurer<HttpSecurity>> saml2LoginCustomizer) throws java.lang.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 theApplicationContext
or 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 public class Saml2LoginConfig { @EnableWebSecurity public static class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .saml2Login(withDefaults()); } } @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
- theCustomizer
to provide more options for theSaml2LoginConfigurer
- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
- Since:
- 5.2
-
oauth2Login
public OAuth2LoginConfigurer<HttpSecurity> oauth2Login() throws java.lang.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 aClientRegistration
using aClientRegistration.Builder
.
ClientRegistration
(s) are composed within aClientRegistrationRepository
, which is required and must be registered with theApplicationContext
or 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 public class OAuth2LoginConfig { @EnableWebSecurity public static class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .oauth2Login(); } } @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
OAuth2LoginConfigurer
for available options to customize the defaults.- Returns:
- the
OAuth2LoginConfigurer
for further customizations - Throws:
java.lang.Exception
- Since:
- 5.0
- See Also:
- Section 4.1 Authorization Code
Grant,
Section 3.1
Authorization Code Flow,
ClientRegistration
,ClientRegistrationRepository
-
oauth2Login
public HttpSecurity oauth2Login(Customizer<OAuth2LoginConfigurer<HttpSecurity>> oauth2LoginCustomizer) throws java.lang.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 aClientRegistration
using aClientRegistration.Builder
.
ClientRegistration
(s) are composed within aClientRegistrationRepository
, which is required and must be registered with theApplicationContext
or 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 public class OAuth2LoginConfig { @EnableWebSecurity public static class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .anyRequest().authenticated() ) .oauth2Login(withDefaults()); } } @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
OAuth2LoginConfigurer
for available options to customize the defaults.- Parameters:
oauth2LoginCustomizer
- theCustomizer
to provide more options for theOAuth2LoginConfigurer
- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
- See Also:
- Section 4.1 Authorization Code
Grant,
Section 3.1
Authorization Code Flow,
ClientRegistration
,ClientRegistrationRepository
-
oauth2Client
public OAuth2ClientConfigurer<HttpSecurity> oauth2Client() throws java.lang.Exception
Configures OAuth 2.0 Client support.- Returns:
- the
OAuth2ClientConfigurer
for further customizations - Throws:
java.lang.Exception
- Since:
- 5.1
- See Also:
- OAuth 2.0 Authorization Framework
-
oauth2Client
public HttpSecurity oauth2Client(Customizer<OAuth2ClientConfigurer<HttpSecurity>> oauth2ClientCustomizer) throws java.lang.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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .anyRequest().authenticated() ) .oauth2Client(withDefaults()); } }
- Parameters:
oauth2ClientCustomizer
- theCustomizer
to provide more options for theOAuth2ClientConfigurer
- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
- See Also:
- OAuth 2.0 Authorization Framework
-
oauth2ResourceServer
public OAuth2ResourceServerConfigurer<HttpSecurity> oauth2ResourceServer() throws java.lang.Exception
Configures OAuth 2.0 Resource Server support.- Returns:
- the
OAuth2ResourceServerConfigurer
for further customizations - Throws:
java.lang.Exception
- Since:
- 5.1
- See Also:
- OAuth 2.0 Authorization Framework
-
oauth2ResourceServer
public HttpSecurity oauth2ResourceServer(Customizer<OAuth2ResourceServerConfigurer<HttpSecurity>> oauth2ResourceServerCustomizer) throws java.lang.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 OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter { @Value("${spring.security.oauth2.resourceserver.jwt.key-value}") RSAPublicKey key; @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .anyRequest().authenticated() ) .oauth2ResourceServer((oauth2ResourceServer) -> oauth2ResourceServer .jwt((jwt) -> jwt .decoder(jwtDecoder()) ) ); } @Bean public JwtDecoder jwtDecoder() { return NimbusJwtDecoder.withPublicKey(this.key).build(); } }
- Parameters:
oauth2ResourceServerCustomizer
- theCustomizer
to provide more options for theOAuth2ResourceServerConfigurer
- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
- See Also:
- OAuth 2.0 Authorization Framework
-
requiresChannel
public ChannelSecurityConfigurer.ChannelRequestMatcherRegistry requiresChannel() throws java.lang.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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin() .and().requiresChannel().anyRequest().requiresSecure(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); } }
- Returns:
- the
ChannelSecurityConfigurer
for further customizations - Throws:
java.lang.Exception
-
requiresChannel
public HttpSecurity requiresChannel(Customizer<ChannelSecurityConfigurer.ChannelRequestMatcherRegistry> requiresChannelCustomizer) throws java.lang.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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .antMatchers("/**").hasRole("USER") ) .formLogin(withDefaults()) .requiresChannel((requiresChannel) -> requiresChannel .anyRequest().requiresSecure() ); } }
- Parameters:
requiresChannelCustomizer
- theCustomizer
to provide more options for theChannelSecurityConfigurer.ChannelRequestMatcherRegistry
- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
-
httpBasic
public HttpBasicConfigurer<HttpSecurity> httpBasic() throws java.lang.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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/**").hasRole("USER").and().httpBasic(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); } }
- Returns:
- the
HttpBasicConfigurer
for further customizations - Throws:
java.lang.Exception
-
httpBasic
public HttpSecurity httpBasic(Customizer<HttpBasicConfigurer<HttpSecurity>> httpBasicCustomizer) throws java.lang.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 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests((authorizeRequests) -> authorizeRequests .antMatchers("/**").hasRole("USER") ) .httpBasic(withDefaults()); } }
- Parameters:
httpBasicCustomizer
- theCustomizer
to provide more options for theHttpBasicConfigurer
- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
-
setSharedObject
public <C> void setSharedObject(java.lang.Class<C> sharedType, C object)
Description copied from class:AbstractConfiguredSecurityBuilder
Sets an object that is shared by multipleSecurityConfigurer
.- Specified by:
setSharedObject
in interfaceHttpSecurityBuilder<HttpSecurity>
- Overrides:
setSharedObject
in classAbstractConfiguredSecurityBuilder<DefaultSecurityFilterChain,HttpSecurity>
- Parameters:
sharedType
- the Class to key the shared object by.object
- the Object to store
-
beforeConfigure
protected void beforeConfigure() throws java.lang.Exception
Description copied from class:AbstractConfiguredSecurityBuilder
Invoked prior to invoking eachSecurityConfigurer.configure(SecurityBuilder)
method. Subclasses may override this method to hook into the lifecycle without using aSecurityConfigurer
.- Overrides:
beforeConfigure
in classAbstractConfiguredSecurityBuilder<DefaultSecurityFilterChain,HttpSecurity>
- Throws:
java.lang.Exception
-
performBuild
protected DefaultSecurityFilterChain performBuild()
Description copied from class:AbstractConfiguredSecurityBuilder
Subclasses must implement this method to build the object that is being returned.- Specified by:
performBuild
in classAbstractConfiguredSecurityBuilder<DefaultSecurityFilterChain,HttpSecurity>
- Returns:
- the Object to be buit or null if the implementation allows it
-
authenticationProvider
public HttpSecurity authenticationProvider(AuthenticationProvider authenticationProvider)
Description copied from interface:HttpSecurityBuilder
Allows adding an additionalAuthenticationProvider
to be used- Specified by:
authenticationProvider
in interfaceHttpSecurityBuilder<HttpSecurity>
- Parameters:
authenticationProvider
- theAuthenticationProvider
to be added- Returns:
- the
HttpSecurity
for further customizations
-
userDetailsService
public HttpSecurity userDetailsService(UserDetailsService userDetailsService) throws java.lang.Exception
Description copied from interface:HttpSecurityBuilder
Allows adding an additionalUserDetailsService
to be used- Specified by:
userDetailsService
in interfaceHttpSecurityBuilder<HttpSecurity>
- Parameters:
userDetailsService
- theUserDetailsService
to be added- Returns:
- the
HttpSecurity
for further customizations - Throws:
java.lang.Exception
-
addFilterAfter
public HttpSecurity addFilterAfter(javax.servlet.Filter filter, java.lang.Class<? extends javax.servlet.Filter> afterFilter)
Description copied from interface:HttpSecurityBuilder
Allows adding aFilter
after one of the knownFilter
classes. The knownFilter
instances are either aFilter
listed inHttpSecurityBuilder.addFilter(Filter)
or aFilter
that has already been added usingHttpSecurityBuilder.addFilterAfter(Filter, Class)
orHttpSecurityBuilder.addFilterBefore(Filter, Class)
.- Specified by:
addFilterAfter
in interfaceHttpSecurityBuilder<HttpSecurity>
- Parameters:
filter
- theFilter
to register after the typeafterFilter
afterFilter
- the Class of the knownFilter
.- Returns:
- the
HttpSecurity
for further customizations
-
addFilterBefore
public HttpSecurity addFilterBefore(javax.servlet.Filter filter, java.lang.Class<? extends javax.servlet.Filter> beforeFilter)
Description copied from interface:HttpSecurityBuilder
Allows adding aFilter
before one of the knownFilter
classes. The knownFilter
instances are either aFilter
listed inHttpSecurityBuilder.addFilter(Filter)
or aFilter
that has already been added usingHttpSecurityBuilder.addFilterAfter(Filter, Class)
orHttpSecurityBuilder.addFilterBefore(Filter, Class)
.- Specified by:
addFilterBefore
in interfaceHttpSecurityBuilder<HttpSecurity>
- Parameters:
filter
- theFilter
to register before the typebeforeFilter
beforeFilter
- the Class of the knownFilter
.- Returns:
- the
HttpSecurity
for further customizations
-
addFilter
public HttpSecurity addFilter(javax.servlet.Filter filter)
Description copied from interface:HttpSecurityBuilder
Adds aFilter
that 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:ChannelProcessingFilter
SecurityContextPersistenceFilter
LogoutFilter
X509AuthenticationFilter
AbstractPreAuthenticatedProcessingFilter
- CasAuthenticationFilter
UsernamePasswordAuthenticationFilter
OpenIDAuthenticationFilter
DefaultLoginPageGeneratingFilter
DefaultLogoutPageGeneratingFilter
ConcurrentSessionFilter
DigestAuthenticationFilter
BearerTokenAuthenticationFilter
BasicAuthenticationFilter
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
JaasApiIntegrationFilter
RememberMeAuthenticationFilter
AnonymousAuthenticationFilter
SessionManagementFilter
ExceptionTranslationFilter
FilterSecurityInterceptor
SwitchUserFilter
- Specified by:
addFilter
in interfaceHttpSecurityBuilder<HttpSecurity>
- Parameters:
filter
- theFilter
to add- Returns:
- the
HttpSecurity
for further customizations
-
addFilterAt
public HttpSecurity addFilterAt(javax.servlet.Filter filter, java.lang.Class<? extends javax.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 anotherFilter
that is already registered (i.e. known) with Spring Security.- Returns:
- the
HttpSecurity
for further customizations
-
requestMatchers
public HttpSecurity.RequestMatcherConfigurer requestMatchers()
Allows specifying whichHttpServletRequest
instances thisHttpSecurity
will be invoked on. This method allows for easily invoking theHttpSecurity
for multiple differentRequestMatcher
instances. If only a singleRequestMatcher
is necessary consider usingmvcMatcher(String)
,antMatcher(String)
,regexMatcher(String)
, orrequestMatcher(RequestMatcher)
.Invoking
requestMatchers()
will not override previous invocations ofmvcMatcher(String)
},requestMatchers()
,antMatcher(String)
,regexMatcher(String)
, andrequestMatcher(RequestMatcher)
.Example Configurations
The following configuration enables theHttpSecurity
for URLs that begin with "/api/" or "/oauth/".@Configuration @EnableWebSecurity public class RequestMatchersSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .requestMatchers() .antMatchers("/api/**", "/oauth/**") .and() .authorizeRequests() .antMatchers("/**").hasRole("USER") .and() .httpBasic(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user").password("password").roles("USER"); } }
The configuration below is the same as the previous configuration.@Configuration @EnableWebSecurity public class RequestMatchersSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .requestMatchers() .antMatchers("/api/**") .antMatchers("/oauth/**") .and() .authorizeRequests() .antMatchers("/**").hasRole("USER") .and() .httpBasic(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user").password("password").roles("USER"); } }
The configuration below is also the same as the above configuration.@Configuration @EnableWebSecurity public class RequestMatchersSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .requestMatchers() .antMatchers("/api/**") .and() .requestMatchers() .antMatchers("/oauth/**") .and() .authorizeRequests() .antMatchers("/**").hasRole("USER") .and() .httpBasic(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user").password("password").roles("USER"); } }
- Returns:
- the
HttpSecurity.RequestMatcherConfigurer
for further customizations
-
requestMatchers
public HttpSecurity requestMatchers(Customizer<HttpSecurity.RequestMatcherConfigurer> requestMatcherCustomizer)
Allows specifying whichHttpServletRequest
instances thisHttpSecurity
will be invoked on. This method allows for easily invoking theHttpSecurity
for multiple differentRequestMatcher
instances. If only a singleRequestMatcher
is necessary consider usingmvcMatcher(String)
,antMatcher(String)
,regexMatcher(String)
, orrequestMatcher(RequestMatcher)
.Invoking
requestMatchers()
will not override previous invocations ofmvcMatcher(String)
},requestMatchers()
,antMatcher(String)
,regexMatcher(String)
, andrequestMatcher(RequestMatcher)
.Example Configurations
The following configuration enables theHttpSecurity
for URLs that begin with "/api/" or "/oauth/".@Configuration @EnableWebSecurity public class RequestMatchersSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .requestMatchers((requestMatchers) -> requestMatchers .antMatchers("/api/**", "/oauth/**") ) .authorizeRequests((authorizeRequests) -> authorizeRequests .antMatchers("/**").hasRole("USER") ) .httpBasic(withDefaults()); } }
The configuration below is the same as the previous configuration.@Configuration @EnableWebSecurity public class RequestMatchersSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .requestMatchers((requestMatchers) -> requestMatchers .antMatchers("/api/**") .antMatchers("/oauth/**") ) .authorizeRequests((authorizeRequests) -> authorizeRequests .antMatchers("/**").hasRole("USER") ) .httpBasic(withDefaults()); } }
The configuration below is also the same as the above configuration.@Configuration @EnableWebSecurity public class RequestMatchersSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .requestMatchers((requestMatchers) -> requestMatchers .antMatchers("/api/**") ) .requestMatchers((requestMatchers) -> requestMatchers .antMatchers("/oauth/**") ) .authorizeRequests((authorizeRequests) -> authorizeRequests .antMatchers("/**").hasRole("USER") ) .httpBasic(withDefaults()); } }
- Parameters:
requestMatcherCustomizer
- theCustomizer
to provide more options for theHttpSecurity.RequestMatcherConfigurer
- Returns:
- the
HttpSecurity
for further customizations
-
requestMatcher
public HttpSecurity requestMatcher(RequestMatcher requestMatcher)
Allows configuring theHttpSecurity
to only be invoked when matching the providedRequestMatcher
. If more advanced configuration is necessary, consider usingrequestMatchers()
.Invoking
requestMatcher(RequestMatcher)
will override previous invocations ofrequestMatchers()
,mvcMatcher(String)
,antMatcher(String)
,regexMatcher(String)
, andrequestMatcher(RequestMatcher)
.- Parameters:
requestMatcher
- theRequestMatcher
to use (i.e. new AntPathRequestMatcher("/admin/**","GET") )- Returns:
- the
HttpSecurity
for further customizations - See Also:
requestMatchers()
,antMatcher(String)
,regexMatcher(String)
-
antMatcher
public HttpSecurity antMatcher(java.lang.String antPattern)
Allows configuring theHttpSecurity
to only be invoked when matching the provided ant pattern. If more advanced configuration is necessary, consider usingrequestMatchers()
orrequestMatcher(RequestMatcher)
.Invoking
antMatcher(String)
will override previous invocations ofmvcMatcher(String)
},requestMatchers()
,antMatcher(String)
,regexMatcher(String)
, andrequestMatcher(RequestMatcher)
.- Parameters:
antPattern
- the Ant Pattern to match on (i.e. "/admin/**")- Returns:
- the
HttpSecurity
for further customizations - See Also:
AntPathRequestMatcher
-
mvcMatcher
public HttpSecurity mvcMatcher(java.lang.String mvcPattern)
Allows configuring theHttpSecurity
to only be invoked when matching the provided Spring MVC pattern. If more advanced configuration is necessary, consider usingrequestMatchers()
orrequestMatcher(RequestMatcher)
.Invoking
mvcMatcher(String)
will override previous invocations ofmvcMatcher(String)
},requestMatchers()
,antMatcher(String)
,regexMatcher(String)
, andrequestMatcher(RequestMatcher)
.- Parameters:
mvcPattern
- the Spring MVC Pattern to match on (i.e. "/admin/**")- Returns:
- the
HttpSecurity
for further customizations - See Also:
MvcRequestMatcher
-
regexMatcher
public HttpSecurity regexMatcher(java.lang.String pattern)
Allows configuring theHttpSecurity
to only be invoked when matching the provided regex pattern. If more advanced configuration is necessary, consider usingrequestMatchers()
orrequestMatcher(RequestMatcher)
.Invoking
regexMatcher(String)
will override previous invocations ofmvcMatcher(String)
},requestMatchers()
,antMatcher(String)
,regexMatcher(String)
, andrequestMatcher(RequestMatcher)
.- Parameters:
pattern
- the Regular Expression to match on (i.e. "/admin/.+")- Returns:
- the
HttpSecurity
for further customizations - See Also:
RegexRequestMatcher
-
-