org.springframework.security.config.annotation.web.builders
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>
A HttpSecurity
is similar to Spring Security's XML element in the namespace
configuration. It allows configuring web based security for specific http requests. By default
it will be applied to all requests, but can be restricted using requestMatcher(RequestMatcher)
or other similar methods.
Example Usage
The most basic form based configuration can be seen below. The configuration will require that any URL
that is requested will require a User with the role "ROLE_USER". It also defines an in memory authentication
scheme with a user that has the username "user", the password "password", and the role "ROLE_USER". For
additional examples, refer to the Java Doc of individual methods on HttpSecurity
.
@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 registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
}
}
- Since:
- 3.2
- See Also:
EnableWebSecurity
Methods inherited from class org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder |
apply, apply, beforeInit, doBuild, getConfigurer, getConfigurers, getOrBuild, getSharedObject, getSharedObjects, objectPostProcessor, postProcess, removeConfigurer, removeConfigurers, setSharedObject |
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.SecurityBuilder |
build |
HttpSecurity
public HttpSecurity(ObjectPostProcessor<Object> objectPostProcessor,
AuthenticationManagerBuilder authenticationBuilder,
Map<Class<Object>,Object> sharedObjects)
- Creates a new instance
- Parameters:
objectPostProcessor
- the ObjectPostProcessor
that should be usedauthenticationBuilder
- the AuthenticationManagerBuilder
to use for additional updatessharedObjects
- the shared Objects to initialize the HttpSecurity
with- See Also:
WebSecurityConfiguration
openidLogin
public OpenIDLoginConfigurer<HttpSecurity> openidLogin()
throws Exception
- 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 registerAuthentication(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("http://axschema.org/contact/email")
.required(true)
.and()
.attribute("firstname")
.type("http://axschema.org/namePerson/first")
.required(true)
.and()
.attribute("lastname")
.type("http://axschema.org/namePerson/last")
.required(true)
.and()
.and()
.attributeExchange(".*yahoo.com.*")
.attribute("email")
.type("http://schema.openid.net/contact/email")
.required(true)
.and()
.attribute("fullname")
.type("http://axschema.org/namePerson")
.required(true)
.and()
.and()
.attributeExchange(".*myopenid.com.*")
.attribute("email")
.type("http://schema.openid.net/contact/email")
.required(true)
.and()
.attribute("fullname")
.type("http://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:
Exception
- See Also:
OpenIDLoginConfigurer
headers
public HeadersConfigurer<HttpSecurity> headers()
throws Exception
- Throws:
Exception
sessionManagement
public SessionManagementConfigurer<HttpSecurity> sessionManagement()
throws Exception
- Allows configuring of Session Management.
Example Configuration
The following configuration demonstrates how to enforce that only a
single instance of a user is authenticated at a time. If a user
authenticates with the username "user" without logging out and an attempt
to authenticate with "user" is made the first session will be forcibly
terminated and sent to the "/login?expired" URL.
@Configuration
@EnableWebSecurity
public class SessionManagementSecurityConfig 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 registerAuthentication(AuthenticationManagerBuilder auth)
throws Exception {
auth.
inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
}
}
When using SessionManagementConfigurer.maximumSessions(int)
, do
not forget to configure HttpSessionEventPublisher
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:
Exception
portMapper
public PortMapperConfigurer<HttpSecurity> portMapper()
throws Exception
- Allows configuring a
PortMapper
that is available from
AbstractConfiguredSecurityBuilder.getSharedObject(Class)
. Other provided
SecurityConfigurer
objects use this configured
PortMapper
as a default PortMapper
when redirecting from
HTTP to HTTPS or from HTTPS to HTTP (for example when used in combination
with requiresChannel()
. By default Spring Security uses a
PortMapperImpl
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 registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
}
}
- Returns:
- the
PortMapperConfigurer
for further customizations
- Throws:
Exception
- See Also:
#requiresChannel()}
jee
public JeeConfigurer<HttpSecurity> jee()
throws Exception
- Configures container based based pre authentication. In this case,
authentication is managed by the Servlet Container.
Example Configuration
The following configuration will use the principal found on the
HttpServletRequest
and if the user is in the role "ROLE_USER" or
"ROLE_ADMIN" will add that to the resulting Authentication
.
@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("ROLE_USER", "ROLE_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:
Exception
x509
public X509Configurer<HttpSecurity> x509()
throws 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:
Exception
rememberMe
public RememberMeConfigurer<HttpSecurity> rememberMe()
throws Exception
- Allows configuring of Remember Me authentication.
Example Configuration
The following configuration demonstrates how to allow token based remember me
authentication. Upon authenticating if the HTTP parameter named "remember-me" exists,
then the user will be remembered even after their HttpSession
expires.
@Configuration
@EnableWebSecurity
public class RememberMeSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void registerAuthentication(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:
Exception
authorizeRequests
public ExpressionUrlAuthorizationConfigurer<HttpSecurity> authorizeRequests()
throws Exception
- Allows restricting access based upon the
HttpServletRequest
using
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 registerAuthentication(AuthenticationManagerBuilder auth)
throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER")
.and()
.withUser("adminr")
.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 registerAuthentication(AuthenticationManagerBuilder auth)
throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER")
.and()
.withUser("adminr")
.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:
-
- Throws:
Exception
- See Also:
requestMatcher(RequestMatcher)
requestCache
public RequestCacheConfigurer<HttpSecurity> requestCache()
throws Exception
- Allows configuring the Request Cache. For example, a protected page (/protected) may be requested prior
to authentication. The application will redirect the user to a login page. After authentication, Spring
Security will redirect the user to the originally requested protected page (/protected). This is
automatically applied when using
WebSecurityConfigurerAdapter
.
- Returns:
- the
RequestCacheConfigurer
for further customizations
- Throws:
Exception
exceptionHandling
public ExceptionHandlingConfigurer<HttpSecurity> exceptionHandling()
throws Exception
- Allows configuring exception handling. This is automatically applied when using
WebSecurityConfigurerAdapter
.
- Returns:
- the
ExceptionHandlingConfigurer
for further customizations
- Throws:
Exception
securityContext
public SecurityContextConfigurer<HttpSecurity> securityContext()
throws Exception
- Sets up management of the
SecurityContext
on the
SecurityContextHolder
between HttpServletRequest
's. This is automatically
applied when using WebSecurityConfigurerAdapter
.
- Returns:
- the
SecurityContextConfigurer
for further customizations
- Throws:
Exception
servletApi
public ServletApiConfigurer<HttpSecurity> servletApi()
throws Exception
- Integrates the
HttpServletRequest
methods with the values found
on the SecurityContext
. This is automatically applied when using
WebSecurityConfigurerAdapter
.
- Returns:
- the
ServletApiConfigurer
for further customizations
- Throws:
Exception
csrf
public CsrfConfigurer<HttpSecurity> csrf()
throws Exception
- Adds CSRF support
- Returns:
- the
ServletApiConfigurer
for further customizations
- Throws:
Exception
logout
public LogoutConfigurer<HttpSecurity> logout()
throws Exception
- Provides logout support. This is automatically applied when using
WebSecurityConfigurerAdapter
. The default is that accessing
the URL "/logout" will log the user out by invalidating the HTTP Session,
cleaning up any rememberMe()
authentication that was configured,
clearing the SecurityContextHolder
, 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()
.logout()
.deleteCookies("remove")
.invalidateHttpSession(false)
.logoutUrl("/custom-logout")
.logoutSuccessUrl("/logout-success");
}
@Override
protected void registerAuthentication(AuthenticationManagerBuilder auth)
throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
}
}
- Returns:
-
- Throws:
Exception
anonymous
public AnonymousConfigurer<HttpSecurity> anonymous()
throws Exception
- Allows configuring how an anonymous user is represented. This is automatically applied
when used in conjunction with
WebSecurityConfigurerAdapter
. By default anonymous
users will be represented with an AnonymousAuthenticationToken
and contain the role
"ROLE_ANONYMOUS".
Example Configuration
@Configuration
@EnableWebSecurity
public class AnononymousSecurityConfig 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 registerAuthentication(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 cause
NullPointerException
in code that assumes anonymous authentication is enabled.
@Configuration
@EnableWebSecurity
public class AnononymousSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**").hasRole("USER")
.and()
.formLogin()
.and()
// sample anonymous customization
.anonymous()
.disabled();
}
@Override
protected void registerAuthentication(AuthenticationManagerBuilder auth)
throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
}
}
- Returns:
-
- Throws:
Exception
formLogin
public FormLoginConfigurer<HttpSecurity> formLogin()
throws Exception
- Specifies to support form based authentication. If
FormLoginConfigurer.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 on
FormLoginConfigurer.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 registerAuthentication(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("j_username") // default is username
.passwordParameter("j_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 registerAuthentication(AuthenticationManagerBuilder auth)
throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
}
}
- Returns:
-
- Throws:
Exception
- See Also:
FormLoginConfigurer.loginPage(String)
requiresChannel
public ChannelSecurityConfigurer<HttpSecurity> requiresChannel()
throws Exception
- Configures channel security. In order for this configuration to be useful at least
one mapping to a required channel must be provided.
Example Configuration
The example below demonstrates how to require HTTPs for every request. Only requiring HTTPS
for some requests is supported, but not recommended since an application that allows for HTTP
introduces many security vulnerabilities. For one such example, read about
Firesheep.
@Configuration
@EnableWebSecurity
public class ChannelSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**").hasRole("USER")
.and()
.formLogin()
.and()
.channelSecurity()
.anyRequest().requiresSecure();
}
@Override
protected void registerAuthentication(AuthenticationManagerBuilder auth)
throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
}
}
- Returns:
- the
ChannelSecurityConfigurer
for further customizations
- Throws:
Exception
httpBasic
public HttpBasicConfigurer<HttpSecurity> httpBasic()
throws Exception
- Configures HTTP Basic authentication.
Example Configuration
The example below demonstrates how to configure HTTP Basic authentication
for an application. The default realm is "Spring Security Application",
but can be customized using
HttpBasicConfigurer.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 registerAuthentication(AuthenticationManagerBuilder auth)
throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
}
}
- Returns:
- the
HttpBasicConfigurer
for further customizations
- Throws:
Exception
beforeConfigure
protected void beforeConfigure()
throws Exception
- Description copied from class:
AbstractConfiguredSecurityBuilder
- Invoked prior to invoking each
SecurityConfigurer.configure(SecurityBuilder)
method.
Subclasses may override this method to hook into the lifecycle without
using a SecurityConfigurer
.
- Overrides:
beforeConfigure
in class AbstractConfiguredSecurityBuilder<DefaultSecurityFilterChain,HttpSecurity>
- Throws:
Exception
performBuild
protected DefaultSecurityFilterChain performBuild()
throws Exception
- Description copied from class:
AbstractConfiguredSecurityBuilder
- Subclasses must implement this method to build the object that is being returned.
- Specified by:
performBuild
in class AbstractConfiguredSecurityBuilder<DefaultSecurityFilterChain,HttpSecurity>
- Returns:
-
- Throws:
Exception
authenticationProvider
public HttpSecurity authenticationProvider(AuthenticationProvider authenticationProvider)
- Description copied from interface:
HttpSecurityBuilder
- Allows adding an additional
AuthenticationProvider
to be used
- Specified by:
authenticationProvider
in interface HttpSecurityBuilder<HttpSecurity>
- Parameters:
authenticationProvider
- the AuthenticationProvider
to be added
- Returns:
- the
HttpSecurity
for further customizations
userDetailsService
public HttpSecurity userDetailsService(UserDetailsService userDetailsService)
throws Exception
- Description copied from interface:
HttpSecurityBuilder
- Allows adding an additional
UserDetailsService
to be used
- Specified by:
userDetailsService
in interface HttpSecurityBuilder<HttpSecurity>
- Parameters:
userDetailsService
- the UserDetailsService
to be added
- Returns:
- the
HttpSecurity
for further customizations
- Throws:
Exception
addFilterAfter
public HttpSecurity addFilterAfter(javax.servlet.Filter filter,
Class<? extends javax.servlet.Filter> afterFilter)
- Description copied from interface:
HttpSecurityBuilder
- Allows adding a
Filter
after one of the known Filter
classes. The known Filter
instances are either a Filter
listed in HttpSecurityBuilder.addFilter(Filter)
or a Filter
that has already
been added using HttpSecurityBuilder.addFilterAfter(Filter, Class)
or
HttpSecurityBuilder.addFilterBefore(Filter, Class)
.
- Specified by:
addFilterAfter
in interface HttpSecurityBuilder<HttpSecurity>
- Parameters:
filter
- the Filter
to register before the type afterFilter
afterFilter
- the Class of the known Filter
.
- Returns:
- the
HttpSecurity
for further customizations
addFilterBefore
public HttpSecurity addFilterBefore(javax.servlet.Filter filter,
Class<? extends javax.servlet.Filter> beforeFilter)
- Description copied from interface:
HttpSecurityBuilder
- Allows adding a
Filter
before one of the known Filter
classes. The known Filter
instances are either a Filter
listed in HttpSecurityBuilder.addFilter(Filter)
or a Filter
that has already
been added using HttpSecurityBuilder.addFilterAfter(Filter, Class)
or
HttpSecurityBuilder.addFilterBefore(Filter, Class)
.
- Specified by:
addFilterBefore
in interface HttpSecurityBuilder<HttpSecurity>
- Parameters:
filter
- the Filter
to register before the type beforeFilter
beforeFilter
- the Class of the known Filter
.
- Returns:
- the
HttpSecurity
for further customizations
addFilter
public HttpSecurity addFilter(javax.servlet.Filter filter)
- Description copied from interface:
HttpSecurityBuilder
- Adds a
Filter
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:
- Specified by:
addFilter
in interface HttpSecurityBuilder<HttpSecurity>
- Parameters:
filter
- the Filter
to add
- Returns:
- the
HttpSecurity
for further customizations
requestMatchers
public HttpSecurity.RequestMatcherConfigurer requestMatchers()
- Allows specifying which
HttpServletRequest
instances this
HttpSecurity
will be invoked on. This method allows for
easily invoking the HttpSecurity
for multiple
different RequestMatcher
instances. If only a single RequestMatcher
is necessary consider using antMatcher(String)
,
regexMatcher(String)
, or requestMatcher(RequestMatcher)
.
Invoking requestMatchers()
will override previous invocations of
requestMatchers()
, antMatcher(String)
, regexMatcher(String)
,
and requestMatcher(RequestMatcher)
.
Example Configurations
The following configuration enables the HttpSecurity
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 registerAuthentication(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 registerAuthentication(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 registerAuthentication(AuthenticationManagerBuilder auth)
throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
}
}
- Returns:
- the
HttpSecurity.RequestMatcherConfigurer
for further customizations
requestMatcher
public HttpSecurity requestMatcher(RequestMatcher requestMatcher)
- Allows configuring the
HttpSecurity
to only be invoked when
matching the provided RequestMatcher
. If more advanced configuration is
necessary, consider using requestMatchers()
.
Invoking requestMatcher(RequestMatcher)
will override previous invocations of
requestMatchers()
, antMatcher(String)
, regexMatcher(String)
,
and requestMatcher(RequestMatcher)
.
- Parameters:
requestMatcher
- the RequestMatcher
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(String antPattern)
- Allows configuring the
HttpSecurity
to only be invoked when
matching the provided ant pattern. If more advanced configuration is
necessary, consider using requestMatchers()
or
requestMatcher(RequestMatcher)
.
Invoking antMatcher(String)
will override previous invocations of
requestMatchers()
, antMatcher(String)
, regexMatcher(String)
,
and requestMatcher(RequestMatcher)
.
- Parameters:
antPattern
- the Ant Pattern to match on (i.e. "/admin/**")
- Returns:
- the
HttpSecurity
for further customizations - See Also:
AntPathRequestMatcher
regexMatcher
public HttpSecurity regexMatcher(String pattern)
- Allows configuring the
HttpSecurity
to only be invoked when
matching the provided regex pattern. If more advanced configuration is
necessary, consider using requestMatchers()
or
requestMatcher(RequestMatcher)
.
Invoking regexMatcher(String)
will override previous invocations of
requestMatchers()
, antMatcher(String)
, regexMatcher(String)
,
and requestMatcher(RequestMatcher)
.
- Parameters:
pattern
- the Regular Expression to match on (i.e. "/admin/.+")
- Returns:
- the
HttpSecurity
for further customizations - See Also:
RegexRequestMatcher