Class HttpSecurity
Builds one SecurityFilterChain. A @Bean method that returns a chain
declares a parameter of this type and is handed a new one:
@Bean
SecurityFilterChain web(HttpSecurity http) {
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated())
.formLogin(Customizer.withDefaults())
.httpBasic(Customizer.withDefaults());
return http.build();
}
Out of the box a chain guards every request, writes the security headers, keeps who is signed in in the HTTP session, protects that session against CSRF and gives a request nobody signed in for an anonymous authentication. It has no way of signing in and no authorization rules until it is given them.
Everything else is there only when the chain asks for it, and a server
carries the code of only what its chains ask for: formLogin(Customizer) -- which
brings sign-out and the memory of where a request was going with it --
httpBasic(Customizer), oauth2Login(Customizer), oauth2ResourceServer(Customizer),
authorizationServer(Customizer), apiKey(Customizer), rateLimit(RequestMatcher, RateLimitKeyResolver, RateLimiter), rememberMe(Customizer), mfa(Customizer),
webAuthn(Customizer), logout(Customizer) and requestCache(Customizer). A server that only
verifies tokens has no login page, no password hashing and no user store in
it. This makes two departures from Spring Security. The first: a chain
without formLogin has no POST /logout until it calls logout(Customizer).
The second: a chain whose session policy is
SessionCreationPolicy.STATELESS keeps nothing a forged request could
ride on, and has no CSRF filter unless csrf(Customizer) asks for one. One that takes
HTTP Basic credentials from browsers should ask.
Users come from the application's beans: a
UserDetailsService and, if there is one, a
PasswordEncoder and a
UserDetailsPasswordService
-- or AuthenticationProvider beans, or an AuthenticationManager bean. A
chain can also be told directly, with userDetailsService,
authenticationProvider(AuthenticationProvider) or authenticationManager.
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final StringThe most passwords checked at one time; a sign-in beyond that is answered 503 at once.static final StringThe name of the one user a server with no user store has, whenUSER_PASSWORDis set;userunless set.static final StringThat user's password, as it would be stored; one written without an{id}is taken as{noop}, which verifies on a development profile only.static final StringThat user's roles, separated by commas. -
Method Summary
Modifier and TypeMethodDescriptionaddFilterAfter(SecurityFilter filter, Class<? extends SecurityFilter> afterFilter) Addsfilterjust after the filter of classafterFilter.addFilterAt(SecurityFilter filter, Class<? extends SecurityFilter> atFilter) Addsfilterat the place of the filter of classatFilter, beside it rather than instead of it: which of the two runs first is not defined.addFilterBefore(SecurityFilter filter, Class<? extends SecurityFilter> beforeFilter) Addsfilterjust before the filter of classbeforeFilter.anonymous(Customizer<AnonymousConfigurer> customizer) The authentication of a request nobody signed in for; seeAnonymousConfigurer.apiKey(Customizer<ApiKeyConfigurer> customizer) Sign-in with an API key; seeApiKeyConfigurer.Keeps one more kind ofAuthenticationin the session as itself; seeAuthenticationCodec.authenticationManager(AuthenticationManager authenticationManager) TheAuthenticationManagerthe chain's sign-in filters use, in place of what the application's beans would give.authenticationProvider(AuthenticationProvider authenticationProvider) One more provider for this chain, asked before those found among the application's beans.authorizationServer(Customizer<AuthorizationServerConfigurer> customizer) Makes this server an OAuth2 authorization server and OpenID Connect provider: the one that issues tokens; seeAuthorizationServerConfigurer.authorizeHttpRequests(Customizer<AuthorizeHttpRequestsConfigurer.AuthorizationManagerRequestMatcherRegistry> customizer) The authorization rules; seeAuthorizeHttpRequestsConfigurer.build()The chain.csrf(Customizer<CsrfConfigurer> customizer) CSRF protection; seeCsrfConfigurer.exceptionHandling(Customizer<ExceptionHandlingConfigurer> customizer) The answers to a request that must sign in or is denied; seeExceptionHandlingConfigurer.formLogin(Customizer<FormLoginConfigurer> customizer) Sign-in through an HTML form; seeFormLoginConfigurer.The configuration of the server the chain is built for.<C extends SecurityConfigurer>
CgetConfigurer(Class<C> type) The configurer of this class applied to the chain, or null.<C> CgetSharedObject(Class<C> sharedType) Something the parts of a chain share, by its class: one set withsetSharedObject(Class, C), or else the one bean of the application that is an instance ofsharedType.headers(Customizer<HeadersConfigurer> customizer) The security headers; seeHeadersConfigurer.httpBasic(Customizer<HttpBasicConfigurer> customizer) Sign-in with HTTP Basic credentials; seeHttpBasicConfigurer.logout(Customizer<LogoutConfigurer> customizer) Sign-out; seeLogoutConfigurer.mfa(Customizer<MfaConfigurer> customizer) A second factor at sign-in; seeMfaConfigurer.oauth2Login(Customizer<OAuth2LoginConfigurer> customizer) Sign-in through another identity provider, with OAuth2 or OpenID Connect; seeOAuth2LoginConfigurer.oauth2ResourceServer(Customizer<OAuth2ResourceServerConfigurer> customizer) Sign-in with a bearer token that is a JWT; seeOAuth2ResourceServerConfigurer.rateLimit(RequestMatcher matcher, RateLimitKeyResolver keyResolver, RateLimiter limiter) Limits how often the requestsmatchermatches may be made under one key, and answers 429 withRetry-Afterbeyond that.rateLimit(String pattern, RateLimitKeyResolver keyResolver, RateLimiter limiter) rateLimit(RequestMatcher, RateLimitKeyResolver, RateLimiter)for the requests whose path matches an Ant pattern.rememberMe(Customizer<RememberMeConfigurer> customizer) A cookie that signs a returning user in; seeRememberMeConfigurer.requestCache(Customizer<RequestCacheConfigurer> customizer) Where an anonymous request's address is remembered; seeRequestCacheConfigurer.securityContext(Customizer<SecurityContextConfigurer> customizer) Where who is signed in is kept; seeSecurityContextConfigurer.securityMatcher(RequestMatcher requestMatcher) Limits the chain to the requestsrequestMatchermatches.securityMatcher(String... patterns) Limits the chain to the requests whose path matches any of these Ant patterns; seeAntPathRequestMatcher.sessionManagement(Customizer<SessionManagementConfigurer> customizer) The use of the HTTP session; seeSessionManagementConfigurer.<C> voidsetSharedObject(Class<C> sharedType, C object) Sharesobjectwith the parts of this chain undersharedType.userDetailsService(UserDetailsService userDetailsService) The users of this chain, in place of the application'sUserDetailsServicebean.webAuthn(Customizer<WebAuthnConfigurer> customizer) Passkeys: registering one for a user who is signed in, and signing in with one; seeWebAuthnConfigurer.<C extends SecurityConfigurer>
HttpSecuritywith(C configurer, Customizer<C> customizer) Applies a configurer of the application's or a library's own, and letscustomizerset it up.
-
Field Details
-
USER_NAME
The name of the one user a server with no user store has, whenUSER_PASSWORDis set;userunless set.- See Also:
-
USER_PASSWORD
That user's password, as it would be stored; one written without an{id}is taken as{noop}, which verifies on a development profile only.- See Also:
-
USER_ROLES
-
PASSWORD_MAX_CONCURRENT
The most passwords checked at one time; a sign-in beyond that is answered 503 at once. No bound unless set. SeeDaoAuthenticationProvider.setMaxConcurrentPasswordChecks(int).- See Also:
-
-
Method Details
-
securityMatcher
Limits the chain to the requests whose path matches any of these Ant patterns; seeAntPathRequestMatcher. A chain without one guards every request, and must then be the last in@Order. -
securityMatcher
Limits the chain to the requestsrequestMatchermatches. -
authorizeHttpRequests
public HttpSecurity authorizeHttpRequests(Customizer<AuthorizeHttpRequestsConfigurer.AuthorizationManagerRequestMatcherRegistry> customizer) The authorization rules; seeAuthorizeHttpRequestsConfigurer. -
formLogin
Sign-in through an HTML form; seeFormLoginConfigurer. Brings sign-out (logout(Customizer)) and the memory of where a request was going (requestCache(Customizer)) with it, unless the chain has turned those off. -
httpBasic
Sign-in with HTTP Basic credentials; seeHttpBasicConfigurer. -
oauth2ResourceServer
Sign-in with a bearer token that is a JWT; seeOAuth2ResourceServerConfigurer. -
oauth2Login
Sign-in through another identity provider, with OAuth2 or OpenID Connect; seeOAuth2LoginConfigurer. Brings sign-out and the memory of where a request was going with it, asformLogin(Customizer)does. -
authorizationServer
Makes this server an OAuth2 authorization server and OpenID Connect provider: the one that issues tokens; seeAuthorizationServerConfigurer. How a user signs in to it is whatever else the chain declares. -
rememberMe
A cookie that signs a returning user in; seeRememberMeConfigurer. Brings sign-out with it, asformLogin(Customizer)does. -
mfa
A second factor at sign-in; seeMfaConfigurer. Brings sign-out with it, asformLogin(Customizer)does. -
webAuthn
Passkeys: registering one for a user who is signed in, and signing in with one; seeWebAuthnConfigurer. Brings sign-out with it, asformLogin(Customizer)does. -
apiKey
Sign-in with an API key; seeApiKeyConfigurer. -
rateLimit
public HttpSecurity rateLimit(RequestMatcher matcher, RateLimitKeyResolver keyResolver, RateLimiter limiter) Limits how often the requests
matchermatches may be made under one key, and answers 429 withRetry-Afterbeyond that.http.rateLimit(AntPathRequestMatcher.antMatcher("/login"), RateLimitKeys.clientAddress(), new InMemoryRateLimiter(5, 60)); http.rateLimit("/api/**", RateLimitKeys.firstOf(RateLimitKeys.apiKeyId(), RateLimitKeys.principal()), new InMemoryRateLimiter(600, 60));A limit keyed by something the request has from the start -- its client's address, its session -- is applied before anything else in the chain. One keyed by who signed in is applied once that is known, and does not apply to a request nobody signed in for. Rules are consulted in the order given, and a request counts against every rule that matches it up to the one that refuses it.
Two rules given the same limiter share its counts for any key they have in common; give each its own unless that is what is meant.
- Parameters:
keyResolver- which key a request counts under; seeRateLimitKeyslimiter- what counts; null for the application's oneRateLimiterbean.InMemoryRateLimitercounts in this process alone.
-
rateLimit
public HttpSecurity rateLimit(String pattern, RateLimitKeyResolver keyResolver, RateLimiter limiter) rateLimit(RequestMatcher, RateLimitKeyResolver, RateLimiter)for the requests whose path matches an Ant pattern. -
logout
Sign-out; seeLogoutConfigurer. A chain withformLogin(Customizer)has it already; any other chain has none until it calls this. -
csrf
CSRF protection; seeCsrfConfigurer. On for every chain that keeps a session; aSessionCreationPolicy.STATELESSchain has it only when it calls this. -
sessionManagement
The use of the HTTP session; seeSessionManagementConfigurer. -
headers
The security headers; seeHeadersConfigurer. -
requestCache
Where an anonymous request's address is remembered; seeRequestCacheConfigurer. -
exceptionHandling
The answers to a request that must sign in or is denied; seeExceptionHandlingConfigurer. -
securityContext
Where who is signed in is kept; seeSecurityContextConfigurer. -
anonymous
The authentication of a request nobody signed in for; seeAnonymousConfigurer. -
with
Applies a configurer of the application's or a library's own, and letscustomizerset it up. -
getConfigurer
The configurer of this class applied to the chain, or null. -
authenticationManager
TheAuthenticationManagerthe chain's sign-in filters use, in place of what the application's beans would give. -
authenticationProvider
One more provider for this chain, asked before those found among the application's beans. -
userDetailsService
The users of this chain, in place of the application'sUserDetailsServicebean. -
addFilterBefore
public HttpSecurity addFilterBefore(SecurityFilter filter, Class<? extends SecurityFilter> beforeFilter) Addsfilterjust before the filter of classbeforeFilter. -
addFilterAfter
public HttpSecurity addFilterAfter(SecurityFilter filter, Class<? extends SecurityFilter> afterFilter) Addsfilterjust after the filter of classafterFilter. -
addFilterAt
Addsfilterat the place of the filter of classatFilter, beside it rather than instead of it: which of the two runs first is not defined. -
getConfig
The configuration of the server the chain is built for. -
build
The chain. AnHttpSecuritybuilds one chain, once. -
authenticationCodec
Keeps one more kind ofAuthenticationin the session as itself; seeAuthenticationCodec. Called before the chain is built, or from a configurer'sinit: the ways of signing in that have a kind of their own --oauth2Login(Customizer),webAuthn(Customizer)-- each call it for theirs.
-