public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<DefaultSecurityFilterChain,HttpSecurity> implements SecurityBuilder<DefaultSecurityFilterChain>, HttpSecurityBuilder<HttpSecurity>
HttpSecurity is similar to Spring Security's XML requestMatcher(RequestMatcher)
or other similar methods.
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 configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
}
}
EnableWebSecurity| Modifier and Type | Class and Description |
|---|---|
class |
HttpSecurity.RequestMatcherConfigurer
Allows mapping HTTP requests that this
HttpSecurity will be used for |
| Constructor and Description |
|---|
HttpSecurity(ObjectPostProcessor<Object> objectPostProcessor,
AuthenticationManagerBuilder authenticationBuilder,
Map<Class<Object>,Object> sharedObjects)
Creates a new instance
|
| Modifier and Type | Method and Description |
|---|---|
HttpSecurity |
addFilter(javax.servlet.Filter filter)
Adds a
Filter that must be an instance of or extend one of the
Filters provided within the Security framework. |
HttpSecurity |
addFilterAfter(javax.servlet.Filter filter,
Class<? extends javax.servlet.Filter> afterFilter)
Allows adding a
Filter after one of the known Filter
classes. |
HttpSecurity |
addFilterBefore(javax.servlet.Filter filter,
Class<? extends javax.servlet.Filter> beforeFilter)
Allows adding a
Filter before one of the known Filter
classes. |
AnonymousConfigurer<HttpSecurity> |
anonymous()
Allows configuring how an anonymous user is represented.
|
HttpSecurity |
antMatcher(String antPattern)
Allows configuring the
HttpSecurity to only be invoked when
matching the provided ant pattern. |
HttpSecurity |
authenticationProvider(AuthenticationProvider authenticationProvider)
Allows adding an additional
AuthenticationProvider to be used |
ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry |
authorizeRequests()
Allows restricting access based upon the
HttpServletRequest using |
protected void |
beforeConfigure()
Invoked prior to invoking each
SecurityConfigurer.configure(SecurityBuilder) method. |
CsrfConfigurer<HttpSecurity> |
csrf()
Adds CSRF support.
|
ExceptionHandlingConfigurer<HttpSecurity> |
exceptionHandling()
Allows configuring exception handling.
|
FormLoginConfigurer<HttpSecurity> |
formLogin()
Specifies to support form based authentication.
|
HeadersConfigurer<HttpSecurity> |
headers()
Adds the Security headers to the response.
|
HttpBasicConfigurer<HttpSecurity> |
httpBasic()
Configures HTTP Basic authentication.
|
JeeConfigurer<HttpSecurity> |
jee()
Configures container based based pre authentication.
|
LogoutConfigurer<HttpSecurity> |
logout()
Provides logout support.
|
OpenIDLoginConfigurer<HttpSecurity> |
openidLogin()
Allows configuring OpenID based authentication.
|
protected DefaultSecurityFilterChain |
performBuild()
Subclasses must implement this method to build the object that is being returned.
|
PortMapperConfigurer<HttpSecurity> |
portMapper()
Allows configuring a
PortMapper that is available from
AbstractConfiguredSecurityBuilder.getSharedObject(Class). |
HttpSecurity |
regexMatcher(String pattern)
Allows configuring the
HttpSecurity to only be invoked when
matching the provided regex pattern. |
RememberMeConfigurer<HttpSecurity> |
rememberMe()
Allows configuring of Remember Me authentication.
|
RequestCacheConfigurer<HttpSecurity> |
requestCache()
Allows configuring the Request Cache.
|
HttpSecurity |
requestMatcher(RequestMatcher requestMatcher)
Allows configuring the
HttpSecurity to only be invoked when
matching the provided RequestMatcher. |
HttpSecurity.RequestMatcherConfigurer |
requestMatchers()
Allows specifying which
HttpServletRequest instances this
HttpSecurity will be invoked on. |
ChannelSecurityConfigurer.ChannelRequestMatcherRegistry |
requiresChannel()
Configures channel security.
|
SecurityContextConfigurer<HttpSecurity> |
securityContext()
Sets up management of the
SecurityContext on the
SecurityContextHolder between HttpServletRequest's. |
ServletApiConfigurer<HttpSecurity> |
servletApi()
Integrates the
HttpServletRequest methods with the values found
on the SecurityContext. |
SessionManagementConfigurer<HttpSecurity> |
sessionManagement()
Allows configuring of Session Management.
|
HttpSecurity |
userDetailsService(UserDetailsService userDetailsService)
Allows adding an additional
UserDetailsService to be used |
X509Configurer<HttpSecurity> |
x509()
Configures X509 based pre authentication.
|
apply, apply, beforeInit, doBuild, getConfigurer, getConfigurers, getOrBuild, getSharedObject, getSharedObjects, objectPostProcessor, postProcess, removeConfigurer, removeConfigurers, setSharedObjectbuild, getObjectclone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitgetConfigurer, getSharedObject, removeConfigurer, setSharedObjectbuildpublic HttpSecurity(ObjectPostProcessor<Object> objectPostProcessor, AuthenticationManagerBuilder authenticationBuilder, Map<Class<Object>,Object> sharedObjects)
objectPostProcessor - the ObjectPostProcessor that should be usedauthenticationBuilder - the AuthenticationManagerBuilder to use for additional updatessharedObjects - the shared Objects to initialize the HttpSecurity withWebSecurityConfigurationpublic OpenIDLoginConfigurer<HttpSecurity> openidLogin() throws Exception
@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("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"));
}
}
OpenIDLoginConfigurer for further customizations.ExceptionOpenIDLoginConfigurerpublic HeadersConfigurer<HttpSecurity> headers() throws Exception
WebSecurityConfigurerAdapter's default constructor.
Only invoking the headers() without invoking additional methods
on it, or accepting the default provided by
WebSecurityConfigurerAdapter, is the equivalent of:
@Configuration
@EnableWebSecurity
public class CsrfSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.headers()
.contentTypeOptions();
.xssProtection()
.cacheControl()
.httpStrictTransportSecurity()
.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 invoking the appropriate
methods on headers() result. For example, the following will
enable HeadersConfigurer.cacheControl() and
HeadersConfigurer.frameOptions() only.
@Configuration
@EnableWebSecurity
public class CsrfSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.headers()
.cacheControl()
.frameOptions()
.and()
...;
}
}
ExceptionHeadersConfigurer}public SessionManagementConfigurer<HttpSecurity> sessionManagement() throws Exception
@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 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.SessionManagementConfigurer for further
customizationsExceptionpublic PortMapperConfigurer<HttpSecurity> portMapper() throws Exception
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.
@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");
}
}
PortMapperConfigurer for further customizationsException#requiresChannel()}public JeeConfigurer<HttpSecurity> jee() throws Exception
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.JeeConfigurer for further customizationsExceptionpublic X509Configurer<HttpSecurity> x509() throws Exception
@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();
}
}
X509Configurer for further customizationsExceptionpublic RememberMeConfigurer<HttpSecurity> rememberMe() throws Exception
HttpSession 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();
}
}
RememberMeConfigurer for further customizationsExceptionpublic ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry authorizeRequests() throws Exception
HttpServletRequest using
@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("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 configure(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")
ExceptionrequestMatcher(RequestMatcher)public RequestCacheConfigurer<HttpSecurity> requestCache() throws Exception
WebSecurityConfigurerAdapter.RequestCacheConfigurer for further customizationsExceptionpublic ExceptionHandlingConfigurer<HttpSecurity> exceptionHandling() throws Exception
WebSecurityConfigurerAdapter.ExceptionHandlingConfigurer for further customizationsExceptionpublic SecurityContextConfigurer<HttpSecurity> securityContext() throws Exception
SecurityContext on the
SecurityContextHolder between HttpServletRequest's. This is automatically
applied when using WebSecurityConfigurerAdapter.SecurityContextConfigurer for further customizationsExceptionpublic ServletApiConfigurer<HttpSecurity> servletApi() throws Exception
HttpServletRequest methods with the values found
on the SecurityContext. This is automatically applied when using
WebSecurityConfigurerAdapter.ServletApiConfigurer for further customizationsExceptionpublic CsrfConfigurer<HttpSecurity> csrf() throws Exception
WebSecurityConfigurerAdapter'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()
...;
}
}
ServletApiConfigurer for further customizationsExceptionpublic LogoutConfigurer<HttpSecurity> logout() throws Exception
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".
@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 configure(AuthenticationManagerBuilder auth)
throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
}
}
Exceptionpublic AnonymousConfigurer<HttpSecurity> anonymous() throws Exception
WebSecurityConfigurerAdapter. By default anonymous
users will be represented with an AnonymousAuthenticationToken and contain the role
"ROLE_ANONYMOUS".
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 configure(AuthenticationManagerBuilder auth)
throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
}
}
Exceptionpublic FormLoginConfigurer<HttpSecurity> formLogin() throws Exception
FormLoginConfigurer.loginPage(String) is not specified a
default login page will be generated.
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 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("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 configure(AuthenticationManagerBuilder auth)
throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
}
}
ExceptionFormLoginConfigurer.loginPage(String)public ChannelSecurityConfigurer.ChannelRequestMatcherRegistry requiresChannel() throws Exception
@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");
}
}
ChannelSecurityConfigurer for further customizationsExceptionpublic HttpBasicConfigurer<HttpSecurity> httpBasic() throws Exception
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 configure(AuthenticationManagerBuilder auth)
throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
}
}
HttpBasicConfigurer for further customizationsExceptionprotected void beforeConfigure()
throws Exception
AbstractConfiguredSecurityBuilderSecurityConfigurer.configure(SecurityBuilder) method.
Subclasses may override this method to hook into the lifecycle without
using a SecurityConfigurer.beforeConfigure in class AbstractConfiguredSecurityBuilder<DefaultSecurityFilterChain,HttpSecurity>Exceptionprotected DefaultSecurityFilterChain performBuild() throws Exception
AbstractConfiguredSecurityBuilderperformBuild in class AbstractConfiguredSecurityBuilder<DefaultSecurityFilterChain,HttpSecurity>Exceptionpublic HttpSecurity authenticationProvider(AuthenticationProvider authenticationProvider)
HttpSecurityBuilderAuthenticationProvider to be usedauthenticationProvider in interface HttpSecurityBuilder<HttpSecurity>authenticationProvider - the AuthenticationProvider to be addedHttpSecurity for further customizationspublic HttpSecurity userDetailsService(UserDetailsService userDetailsService) throws Exception
HttpSecurityBuilderUserDetailsService to be useduserDetailsService in interface HttpSecurityBuilder<HttpSecurity>userDetailsService - the UserDetailsService to be addedHttpSecurity for further customizationsExceptionpublic HttpSecurity addFilterAfter(javax.servlet.Filter filter, Class<? extends javax.servlet.Filter> afterFilter)
HttpSecurityBuilderFilter 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).addFilterAfter in interface HttpSecurityBuilder<HttpSecurity>filter - the Filter to register before the type afterFilterafterFilter - the Class of the known Filter.HttpSecurity for further customizationspublic HttpSecurity addFilterBefore(javax.servlet.Filter filter, Class<? extends javax.servlet.Filter> beforeFilter)
HttpSecurityBuilderFilter 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).addFilterBefore in interface HttpSecurityBuilder<HttpSecurity>filter - the Filter to register before the type beforeFilterbeforeFilter - the Class of the known Filter.HttpSecurity for further customizationspublic HttpSecurity addFilter(javax.servlet.Filter filter)
HttpSecurityBuilderFilter 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:
ChannelProcessingFilterConcurrentSessionFilterSecurityContextPersistenceFilterLogoutFilterX509AuthenticationFilterAbstractPreAuthenticatedProcessingFilterCasAuthenticationFilterUsernamePasswordAuthenticationFilterConcurrentSessionFilterOpenIDAuthenticationFilterDefaultLoginPageGeneratingFilterConcurrentSessionFilterDigestAuthenticationFilterBasicAuthenticationFilterRequestCacheAwareFilterSecurityContextHolderAwareRequestFilterJaasApiIntegrationFilterRememberMeAuthenticationFilterAnonymousAuthenticationFilterSessionManagementFilterExceptionTranslationFilterFilterSecurityInterceptorSwitchUserFilteraddFilter in interface HttpSecurityBuilder<HttpSecurity>filter - the Filter to addHttpSecurity for further customizationspublic HttpSecurity.RequestMatcherConfigurer requestMatchers()
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).
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 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");
}
}
HttpSecurity.RequestMatcherConfigurer for further customizationspublic HttpSecurity requestMatcher(RequestMatcher requestMatcher)
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).
requestMatcher - the RequestMatcher to use (i.e. new AntPathRequestMatcher("/admin/**","GET") )HttpSecurity for further customizationsrequestMatchers(),
antMatcher(String),
regexMatcher(String)public HttpSecurity antMatcher(String antPattern)
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).
antPattern - the Ant Pattern to match on (i.e. "/admin/**")HttpSecurity for further customizationsAntPathRequestMatcherpublic HttpSecurity regexMatcher(String pattern)
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).
pattern - the Regular Expression to match on (i.e. "/admin/.+")HttpSecurity for further customizationsRegexRequestMatcher