# Web Application Security
# <debug>
Enables Spring Security debugging infrastructure. This will provide human-readable (multi-line) debugging information to monitor requests coming into the security filters. This may include sensitive information, such as request parameters or headers, and should only be used in a development environment.
# <http>
If you use an <http>
element within your application, a FilterChainProxy
bean named "springSecurityFilterChain" is created and the configuration within the element is used to build a filter chain withinFilterChainProxy
.
As of Spring Security 3.1, additional http
elements can be used to add extra filter chains [1] for how to set up the mapping from your web.xml
].
Some core filters are always created in a filter chain and others will be added to the stack depending on the attributes and child elements which are present.
The positions of the standard filters are fixed (seethe filter order table in the namespace introduction), removing a common source of errors with previous versions of the framework when users had to configure the filter chain explicitly in theFilterChainProxy
bean.
You can, of course, still do this if you need full control of the configuration.
All filters which require a reference to the AuthenticationManager
will be automatically injected with the internal instance created by the namespace configuration.
Each <http>
namespace block always creates an SecurityContextPersistenceFilter
, an ExceptionTranslationFilter
and a FilterSecurityInterceptor
.
These are fixed and cannot be replaced with alternatives.
# <http> Attributes
The attributes on the <http>
element control some of the properties on the core filters.
access-decision-manager-refOptional attribute specifying the ID of the
AccessDecisionManager
implementation which should be used for authorizing HTTP requests. By default anAffirmativeBased
implementation is used for with aRoleVoter
and anAuthenticatedVoter
.authentication-manager-refA reference to the
AuthenticationManager
used for theFilterChain
created by this http element.auto-configAutomatically registers a login form, BASIC authentication, logout services. If set to "true", all of these capabilities are added (although you can still customize the configuration of each by providing the respective element). If unspecified, defaults to "false". Use of this attribute is not recommended. Use explicit configuration elements instead to avoid confusion.
create-sessionControls the eagerness with which an HTTP session is created by Spring Security classes. Options include:
always
- Spring Security will proactively create a session if one does not exist.ifRequired
- Spring Security will only create a session only if one is required (default value).never
- Spring Security will never create a session, but will make use of one if the application does.stateless
- Spring Security will not create a session and ignore the session for obtaining a SpringAuthentication
.
disable-url-rewritingPrevents session IDs from being appended to URLs in the application. Clients must use cookies if this attribute is set to
true
. The default istrue
.entry-point-refNormally the
AuthenticationEntryPoint
used will be set depending on which authentication mechanisms have been configured. This attribute allows this behaviour to be overridden by defining a customizedAuthenticationEntryPoint
bean which will start the authentication process.jaas-api-provisionIf available, runs the request as the
Subject
acquired from theJaasAuthenticationToken
which is implemented by adding aJaasApiIntegrationFilter
bean to the stack. Defaults tofalse
.nameA bean identifier, used for referring to the bean elsewhere in the context.
once-per-requestCorresponds to the
observeOncePerRequest
property ofFilterSecurityInterceptor
. Defaults totrue
.patternDefining a pattern for the http element controls the requests which will be filtered through the list of filters which it defines. The interpretation is dependent on the configured request-matcher. If no pattern is defined, all requests will be matched, so the most specific patterns should be declared first.
realmSets the realm name used for basic authentication (if enabled). Corresponds to the
realmName
property onBasicAuthenticationEntryPoint
.request-matcherDefines the
RequestMatcher
strategy used in theFilterChainProxy
and the beans created by theintercept-url
to match incoming requests. Options are currentlymvc
,ant
,regex
andciRegex
, for Spring MVC, ant, regular-expression and case-insensitive regular-expression respectively. A separate instance is created for each intercept-url element using its pattern, method and servlet-path attributes. Ant paths are matched using anAntPathRequestMatcher
, regular expressions are matched using aRegexRequestMatcher
and for Spring MVC path matching theMvcRequestMatcher
is used. See the Javadoc for these classes for more details on exactly how the matching is performed. Ant paths are the default strategy.request-matcher-refA reference to a bean that implements
RequestMatcher
that will determine if thisFilterChain
should be used. This is a more powerful alternative to pattern.securityA request pattern can be mapped to an empty filter chain, by setting this attribute to
none
. No security will be applied and none of Spring Security’s features will be available.security-context-repository-refAllows injection of a custom
SecurityContextRepository
into theSecurityContextPersistenceFilter
.servlet-api-provisionProvides versions of
HttpServletRequest
security methods such asisUserInRole()
andgetPrincipal()
which are implemented by adding aSecurityContextHolderAwareRequestFilter
bean to the stack. Defaults totrue
.use-expressionsEnables EL-expressions in the
access
attribute, as described in the chapter on expression-based access-control. The default value is true.
# Child Elements of <http>
# <access-denied-handler>
This element allows you to set the errorPage
property for the default AccessDeniedHandler
used by the ExceptionTranslationFilter
, using the error-page attribute, or to supply your own implementation using the ref attribute.
This is discussed in more detail in the section on the ExceptionTranslationFilter.
# Parent Elements of <access-denied-handler>
# <access-denied-handler> Attributes
error-pageThe access denied page that an authenticated user will be redirected to if they request a page which they don’t have the authority to access.
refDefines a reference to a Spring bean of type
AccessDeniedHandler
.
# <cors>
This element allows for configuring a CorsFilter
.
If no CorsFilter
or CorsConfigurationSource
is specified and Spring MVC is on the classpath, a HandlerMappingIntrospector
is used as the CorsConfigurationSource
.
# <cors> Attributes
The attributes on the <cors>
element control the headers element.
refOptional attribute that specifies the bean name of a
CorsFilter
.cors-configuration-source-refOptional attribute that specifies the bean name of a
CorsConfigurationSource
to be injected into aCorsFilter
created by the XML namespace.
# Parent Elements of <cors>
# <headers>
This element allows for configuring additional (security) headers to be send with the response. It enables easy configuration for several headers and also allows for setting custom headers through the header element. Additional information, can be found in the Security Headers section of the reference.
Cache-Control
,Pragma
, andExpires
- Can be set using the cache-control element. This ensures that the browser does not cache your secured pages.Strict-Transport-Security
- Can be set using the hsts element. This ensures that the browser automatically requests HTTPS for future requests.X-Frame-Options
- Can be set using the frame-options element. The X-Frame-Options (opens new window) header can be used to prevent clickjacking attacks.X-XSS-Protection
- Can be set using the xss-protection element. The X-XSS-Protection (opens new window) header can be used by browser to do basic control.X-Content-Type-Options
- Can be set using the content-type-options element. The X-Content-Type-Options (opens new window) header prevents Internet Explorer from MIME-sniffing a response away from the declared content-type. This also applies to Google Chrome, when downloading extensions.Public-Key-Pinning
orPublic-Key-Pinning-Report-Only
- Can be set using the hpkp element. This allows HTTPS websites to resist impersonation by attackers using mis-issued or otherwise fraudulent certificates.Content-Security-Policy
orContent-Security-Policy-Report-Only
- Can be set using the content-security-policy element.Content Security Policy (CSP) (opens new window) is a mechanism that web applications can leverage to mitigate content injection vulnerabilities, such as cross-site scripting (XSS).Referrer-Policy
- Can be set using the referrer-policy element, Referrer-Policy (opens new window) is a mechanism that web applications can leverage to manage the referrer field, which contains the last page the user was on.Feature-Policy
- Can be set using the feature-policy element, Feature-Policy (opens new window) is a mechanism that allows web developers to selectively enable, disable, and modify the behavior of certain APIs and web features in the browser.
# <headers> Attributes
The attributes on the <headers>
element control the headers element.
defaults-disabledOptional attribute that specifies to disable the default Spring Security’s HTTP response headers. The default is false (the default headers are included).
disabledOptional attribute that specifies to disable Spring Security’s HTTP response headers. The default is false (the headers are enabled).
# Parent Elements of <headers>
# Child Elements of <headers>
# <cache-control>
Adds Cache-Control
, Pragma
, and Expires
headers to ensure that the browser does not cache your secured pages.
# <cache-control> Attributes
- disabledSpecifies if Cache Control should be disabled. Default false.
# Parent Elements of <cache-control>
# <hsts>
When enabled adds the Strict-Transport-Security (opens new window) header to the response for any secure request. This allows the server to instruct browsers to automatically use HTTPS for future requests.
# <hsts> Attributes
disabledSpecifies if Strict-Transport-Security should be disabled. Default false.
include-sub-domainsSpecifies if subdomains should be included. Default true.
max-age-secondsSpecifies the maximum amount of time the host should be considered a Known HSTS Host. Default one year.
request-matcher-refThe RequestMatcher instance to be used to determine if the header should be set. Default is if HttpServletRequest.isSecure() is true.
preloadSpecifies if preload should be included. Default false.
# Parent Elements of <hsts>
# <hpkp>
When enabled adds the Public Key Pinning Extension for HTTP (opens new window) header to the response for any secure request. This allows HTTPS websites to resist impersonation by attackers using mis-issued or otherwise fraudulent certificates.
# <hpkp> Attributes
disabledSpecifies if HTTP Public Key Pinning (HPKP) should be disabled. Default true.
include-sub-domainsSpecifies if subdomains should be included. Default false.
max-age-secondsSets the value for the max-age directive of the Public-Key-Pins header. Default 60 days.
report-onlySpecifies if the browser should only report pin validation failures. Default true.
report-uriSpecifies the URI to which the browser should report pin validation failures.
# Parent Elements of <hpkp>
# <pins>
The list of pins
# Child Elements of <pins>
# <pin>
A pin is specified using the base64-encoded SPKI fingerprint as value and the cryptographic hash algorithm as attribute
# <pin> Attributes
- algorithmThe cryptographic hash algorithm. Default is SHA256.
# Parent Elements of <pin>
# <content-security-policy>
When enabled adds the Content Security Policy (CSP) (opens new window) header to the response. CSP is a mechanism that web applications can leverage to mitigate content injection vulnerabilities, such as cross-site scripting (XSS).
# <content-security-policy> Attributes
policy-directivesThe security policy directive(s) for the Content-Security-Policy header or if report-only is set to true, then the Content-Security-Policy-Report-Only header is used.
report-onlySet to true, to enable the Content-Security-Policy-Report-Only header for reporting policy violations only. Defaults to false.
# Parent Elements of <content-security-policy>
# <referrer-policy>
When enabled adds the Referrer Policy (opens new window) header to the response.
# <referrer-policy> Attributes
- policyThe policy for the Referrer-Policy header. Default "no-referrer".
# Parent Elements of <referrer-policy>
# <feature-policy>
When enabled adds the Feature Policy (opens new window) header to the response.
# <feature-policy> Attributes
- policy-directivesThe security policy directive(s) for the Feature-Policy header.
# Parent Elements of <feature-policy>
# <frame-options>
When enabled adds the X-Frame-Options header (opens new window) to the response, this allows newer browsers to do some security checks and prevent clickjacking (opens new window) attacks.
# <frame-options> Attributes
disabledIf disabled, the X-Frame-Options header will not be included. Default false.
policy
DENY
The page cannot be displayed in a frame, regardless of the site attempting to do so. This is the default when frame-options-policy is specified.SAMEORIGIN
The page can only be displayed in a frame on the same origin as the page itself
In other words, if you specify DENY, not only will attempts to load the page in a frame fail when loaded from other sites, attempts to do so will fail when loaded from the same site. On the other hand, if you specify SAMEORIGIN, you can still use the page in a frame as long as the site including it in a frame it is the same as the one serving the page.
# Parent Elements of <frame-options>
# <permissions-policy>
Adds the Permissions-Policy header (opens new window) to the response.
# <permissions-policy> Attributes
- policyThe policy value to write for the
Permissions-Policy
header
# Parent Elements of <permissions-policy>
# <xss-protection>
Adds the X-XSS-Protection header (opens new window) to the response to assist in protecting against reflected / Type-1 Cross-Site Scripting (XSS) (opens new window) attacks. This is in no-way a full protection to XSS attacks!
# <xss-protection> Attributes
xss-protection-disabledDo not include the header for reflected / Type-1 Cross-Site Scripting (XSS) (opens new window) protection.
xss-protection-enabledExplicitly enable or disable reflected / Type-1 Cross-Site Scripting (XSS) (opens new window) protection.
xss-protection-blockWhen true and xss-protection-enabled is true, adds mode=block to the header. This indicates to the browser that the page should not be loaded at all. When false and xss-protection-enabled is true, the page will still be rendered when an reflected attack is detected but the response will be modified to protect against the attack. Note that there are sometimes ways of bypassing this mode which can often times make blocking the page more desirable.
# Parent Elements of <xss-protection>
# <content-type-options>
Add the X-Content-Type-Options header with the value of nosniff to the response. This disables MIME-sniffing (opens new window) for IE8+ and Chrome extensions.
# <content-type-options> Attributes
- disabledSpecifies if Content Type Options should be disabled. Default false.
# Parent Elements of <content-type-options>
# <header>
Add additional headers to the response, both the name and value need to be specified.
# <header-attributes> Attributes
header-nameThe
name
of the header.valueThe
value
of the header to add.refReference to a custom implementation of the
HeaderWriter
interface.
# Parent Elements of <header>
# <anonymous>
Adds an AnonymousAuthenticationFilter
to the stack and an AnonymousAuthenticationProvider
.
Required if you are using the IS_AUTHENTICATED_ANONYMOUSLY
attribute.
# Parent Elements of <anonymous>
# <anonymous> Attributes
enabledWith the default namespace setup, the anonymous "authentication" facility is automatically enabled. You can disable it using this property.
granted-authorityThe granted authority that should be assigned to the anonymous request. Commonly this is used to assign the anonymous request particular roles, which can subsequently be used in authorization decisions. If unset, defaults to
ROLE_ANONYMOUS
.keyThe key shared between the provider and filter. This generally does not need to be set. If unset, it will default to a secure randomly generated value. This means setting this value can improve startup time when using the anonymous functionality since secure random values can take a while to be generated.
usernameThe username that should be assigned to the anonymous request. This allows the principal to be identified, which may be important for logging and auditing. if unset, defaults to
anonymousUser
.
# <csrf>
This element will add Cross Site Request Forger (CSRF) (opens new window) protection to the application. It also updates the default RequestCache to only replay "GET" requests upon successful authentication. Additional information can be found in the Cross Site Request Forgery (CSRF) section of the reference.
# Parent Elements of <csrf>
# <csrf> Attributes
disabledOptional attribute that specifies to disable Spring Security’s CSRF protection. The default is false (CSRF protection is enabled). It is highly recommended to leave CSRF protection enabled.
token-repository-refThe CsrfTokenRepository to use. The default is
HttpSessionCsrfTokenRepository
.request-matcher-refThe RequestMatcher instance to be used to determine if CSRF should be applied. Default is any HTTP method except "GET", "TRACE", "HEAD", "OPTIONS".
# <custom-filter>
This element is used to add a filter to the filter chain.
It doesn’t create any additional beans but is used to select a bean of type javax.servlet.Filter
which is already defined in the application context and add that at a particular position in the filter chain maintained by Spring Security.
Full details can be found in the namespace chapter.
# Parent Elements of <custom-filter>
# <custom-filter> Attributes
afterThe filter immediately after which the custom-filter should be placed in the chain. This feature will only be needed by advanced users who wish to mix their own filters into the security filter chain and have some knowledge of the standard Spring Security filters. The filter names map to specific Spring Security implementation filters.
beforeThe filter immediately before which the custom-filter should be placed in the chain
positionThe explicit position at which the custom-filter should be placed in the chain. Use if you are replacing a standard filter.
refDefines a reference to a Spring bean that implements
Filter
.
# <expression-handler>
Defines the SecurityExpressionHandler
instance which will be used if expression-based access-control is enabled.
A default implementation (with no ACL support) will be used if not supplied.
# Parent Elements of <expression-handler>
# <expression-handler> Attributes
- refDefines a reference to a Spring bean that implements
SecurityExpressionHandler
.
# <form-login>
Used to add an UsernamePasswordAuthenticationFilter
to the filter stack and an LoginUrlAuthenticationEntryPoint
to the application context to provide authentication on demand.
This will always take precedence over other namespace-created entry points.
If no attributes are supplied, a login page will be generated automatically at the URL "/login" [2] The behaviour can be customized using the <form-login>
Attributes.
# Parent Elements of <form-login>
# <form-login> Attributes
always-use-default-targetIf set to
true
, the user will always start at the value given by default-target-url, regardless of how they arrived at the login page. Maps to thealwaysUseDefaultTargetUrl
property ofUsernamePasswordAuthenticationFilter
. Default value isfalse
.authentication-details-source-refReference to an
AuthenticationDetailsSource
which will be used by the authentication filterauthentication-failure-handler-refCan be used as an alternative to authentication-failure-url, giving you full control over the navigation flow after an authentication failure. The value should be the name of an
AuthenticationFailureHandler
bean in the application context.authentication-failure-urlMaps to the
authenticationFailureUrl
property ofUsernamePasswordAuthenticationFilter
. Defines the URL the browser will be redirected to on login failure. Defaults to/login?error
, which will be automatically handled by the automatic login page generator, re-rendering the login page with an error message.authentication-success-handler-refThis can be used as an alternative to default-target-url and always-use-default-target, giving you full control over the navigation flow after a successful authentication. The value should be the name of an
AuthenticationSuccessHandler
bean in the application context. By default, an implementation ofSavedRequestAwareAuthenticationSuccessHandler
is used and injected with the default-target-url .default-target-urlMaps to the
defaultTargetUrl
property ofUsernamePasswordAuthenticationFilter
. If not set, the default value is "/" (the application root). A user will be taken to this URL after logging in, provided they were not asked to login while attempting to access a secured resource, when they will be taken to the originally requested URL.login-pageThe URL that should be used to render the login page. Maps to the
loginFormUrl
property of theLoginUrlAuthenticationEntryPoint
. Defaults to "/login".login-processing-urlMaps to the
filterProcessesUrl
property ofUsernamePasswordAuthenticationFilter
. The default value is "/login".password-parameterThe name of the request parameter which contains the password. Defaults to "password".
username-parameterThe name of the request parameter which contains the username. Defaults to "username".
authentication-success-forward-urlMaps a
ForwardAuthenticationSuccessHandler
toauthenticationSuccessHandler
property ofUsernamePasswordAuthenticationFilter
.authentication-failure-forward-urlMaps a
ForwardAuthenticationFailureHandler
toauthenticationFailureHandler
property ofUsernamePasswordAuthenticationFilter
.
# <oauth2-login>
The OAuth 2.0 Login feature configures authentication support using an OAuth 2.0 and/or OpenID Connect 1.0 Provider.
# Parent Elements of <oauth2-login>
# <oauth2-login> Attributes
client-registration-repository-refReference to the
ClientRegistrationRepository
.authorized-client-repository-refReference to the
OAuth2AuthorizedClientRepository
.authorized-client-service-refReference to the
OAuth2AuthorizedClientService
.authorization-request-repository-refReference to the
AuthorizationRequestRepository
.authorization-request-resolver-refReference to the
OAuth2AuthorizationRequestResolver
.access-token-response-client-refReference to the
OAuth2AccessTokenResponseClient
.user-authorities-mapper-refReference to the
GrantedAuthoritiesMapper
.user-service-refReference to the
OAuth2UserService
.oidc-user-service-refReference to the OpenID Connect
OAuth2UserService
.login-processing-urlThe URI where the filter processes authentication requests.
login-pageThe URI to send users to login.
authentication-success-handler-refReference to the
AuthenticationSuccessHandler
.authentication-failure-handler-refReference to the
AuthenticationFailureHandler
.jwt-decoder-factory-refReference to the
JwtDecoderFactory
used byOidcAuthorizationCodeAuthenticationProvider
.
# <oauth2-client>
Configures OAuth 2.0 Client support.
# Parent Elements of <oauth2-client>
# <oauth2-client> Attributes
client-registration-repository-refReference to the
ClientRegistrationRepository
.authorized-client-repository-refReference to the
OAuth2AuthorizedClientRepository
.authorized-client-service-refReference to the
OAuth2AuthorizedClientService
.
# Child Elements of <oauth2-client>
# <authorization-code-grant>
Configures OAuth 2.0 Authorization Code Grant.
# Parent Elements of <authorization-code-grant>
# <authorization-code-grant> Attributes
authorization-request-repository-refReference to the
AuthorizationRequestRepository
.authorization-request-resolver-refReference to the
OAuth2AuthorizationRequestResolver
.access-token-response-client-refReference to the
OAuth2AccessTokenResponseClient
.
# <client-registrations>
A container element for client(s) registered (ClientRegistration) with an OAuth 2.0 or OpenID Connect 1.0 Provider.
# Child Elements of <client-registrations>
# <client-registration>
Represents a client registered with an OAuth 2.0 or OpenID Connect 1.0 Provider.
# Parent Elements of <client-registration>
# <client-registration> Attributes
registration-idThe ID that uniquely identifies the
ClientRegistration
.client-idThe client identifier.
client-secretThe client secret.
client-authentication-methodThe method used to authenticate the Client with the Provider. The supported values are client_secret_basic, client_secret_post, private_key_jwt, client_secret_jwt and none (public clients) (opens new window).
authorization-grant-typeThe OAuth 2.0 Authorization Framework defines four Authorization Grant (opens new window) types. The supported values are
authorization_code
,client_credentials
,password
, as well as, extension grant typeurn:ietf:params:oauth:grant-type:jwt-bearer
.redirect-uriThe client’s registered redirect URI that the Authorization Server redirects the end-user’s user-agent to after the end-user has authenticated and authorized access to the client.
scopeThe scope(s) requested by the client during the Authorization Request flow, such as openid, email, or profile.
client-nameA descriptive name used for the client. The name may be used in certain scenarios, such as when displaying the name of the client in the auto-generated login page.
provider-idA reference to the associated provider. May reference a
<provider>
element or use one of the common providers (google, github, facebook, okta).
# <provider>
The configuration information for an OAuth 2.0 or OpenID Connect 1.0 Provider.
# Parent Elements of <provider>
# <provider> Attributes
provider-idThe ID that uniquely identifies the provider.
authorization-uriThe Authorization Endpoint URI for the Authorization Server.
token-uriThe Token Endpoint URI for the Authorization Server.
user-info-uriThe UserInfo Endpoint URI used to access the claims/attributes of the authenticated end-user.
user-info-authentication-methodThe authentication method used when sending the access token to the UserInfo Endpoint. The supported values are header, form and query.
user-info-user-name-attributeThe name of the attribute returned in the UserInfo Response that references the Name or Identifier of the end-user.
jwk-set-uriThe URI used to retrieve the JSON Web Key (JWK) (opens new window) Set from the Authorization Server, which contains the cryptographic key(s) used to verify the JSON Web Signature (JWS) (opens new window) of the ID Token and optionally the UserInfo Response.
issuer-uriThe URI used to initially configure a
ClientRegistration
using discovery of an OpenID Connect Provider’s Configuration endpoint (opens new window) or an Authorization Server’s Metadata endpoint (opens new window).
# <oauth2-resource-server>
Adds a BearerTokenAuthenticationFilter
, BearerTokenAuthenticationEntryPoint
, and BearerTokenAccessDeniedHandler
to the configuration.
In addition, either <jwt>
or <opaque-token>
must be specified.
# Parents Elements of <oauth2-resource-server>
# Child Elements of <oauth2-resource-server>
# <oauth2-resource-server> Attributes
authentication-manager-resolver-refReference to an
AuthenticationManagerResolver
which will resolve theAuthenticationManager
at request timebearer-token-resolver-refReference to a
BearerTokenResolver
which will retrieve the bearer token from the requestentry-point-refReference to a
AuthenticationEntryPoint
which will handle unauthorized requests
# <jwt>
Represents an OAuth 2.0 Resource Server that will authorize JWTs
# Parent Elements of <jwt>
# <jwt> Attributes
jwt-authentication-converter-refReference to a
Converter<Jwt, AbstractAuthenticationToken>
jwt-decoder-refReference to a
JwtDecoder
. This is a larger component that overridesjwk-set-uri
jwk-set-uriThe JWK Set Uri used to load signing verification keys from an OAuth 2.0 Authorization Server
# <opaque-token>
Represents an OAuth 2.0 Resource Server that will authorize opaque tokens
# Parent Elements of <opaque-token>
# <opaque-token> Attributes
introspector-refReference to an
OpaqueTokenIntrospector
. This is a larger component that overridesintrospection-uri
,client-id
, andclient-secret
.introspection-uriThe Introspection Uri used to introspect the details of an opaque token. Should be accompanied with a
client-id
andclient-secret
.client-idThe Client Id to use for client authentication against the provided
introspection-uri
.client-secretThe Client Secret to use for client authentication against the provided
introspection-uri
.
# <http-basic>
Adds a BasicAuthenticationFilter
and BasicAuthenticationEntryPoint
to the configuration.
The latter will only be used as the configuration entry point if form-based login is not enabled.
# Parent Elements of <http-basic>
# <http-basic> Attributes
authentication-details-source-refReference to an
AuthenticationDetailsSource
which will be used by the authentication filterentry-point-refSets the
AuthenticationEntryPoint
which is used by theBasicAuthenticationFilter
.
# <http-firewall> Element
This is a top-level element which can be used to inject a custom implementation of HttpFirewall
into the FilterChainProxy
created by the namespace.
The default implementation should be suitable for most applications.
# <http-firewall> Attributes
- refDefines a reference to a Spring bean that implements
HttpFirewall
.
# <intercept-url>
This element is used to define the set of URL patterns that the application is interested in and to configure how they should be handled.
It is used to construct the FilterInvocationSecurityMetadataSource
used by the FilterSecurityInterceptor
.
It is also responsible for configuring a ChannelProcessingFilter
if particular URLs need to be accessed by HTTPS, for example.
When matching the specified patterns against an incoming request, the matching is done in the order in which the elements are declared.
So the most specific patterns should come first and the most general should come last.
# Parent Elements of <intercept-url>
# <intercept-url> Attributes
accessLists the access attributes which will be stored in the
FilterInvocationSecurityMetadataSource
for the defined URL pattern/method combination. This should be a comma-separated list of the security configuration attributes (such as role names).methodThe HTTP Method which will be used in combination with the pattern and servlet path (optional) to match an incoming request. If omitted, any method will match. If an identical pattern is specified with and without a method, the method-specific match will take precedence.
patternThe pattern which defines the URL path. The content will depend on the
request-matcher
attribute from the containing http element, so will default to ant path syntax.request-matcher-refA reference to a
RequestMatcher
that will be used to determine if this<intercept-url>
is used.requires-channelCan be "http" or "https" depending on whether a particular URL pattern should be accessed over HTTP or HTTPS respectively. Alternatively the value "any" can be used when there is no preference. If this attribute is present on any
<intercept-url>
element, then aChannelProcessingFilter
will be added to the filter stack and its additional dependencies added to the application context.
If a <port-mappings>
configuration is added, this will be used to by the SecureChannelProcessor
and InsecureChannelProcessor
beans to determine the ports used for redirecting to HTTP/HTTPS.
This property is invalid for filter-security-metadata-source |
---|
- servlet-pathThe servlet path which will be used in combination with the pattern and HTTP method to match an incoming request.
This attribute is only applicable when request-matcher is 'mvc'.
In addition, the value is only required in the following 2 use cases: 1) There are 2 or more
HttpServlet
's registered in theServletContext
that have mappings starting with'/'
and are different; 2) The pattern starts with the same value of a registeredHttpServlet
path, excluding the default (root)HttpServlet
'/'
.
This property is invalid for filter-security-metadata-source |
---|
# <jee>
Adds a J2eePreAuthenticatedProcessingFilter to the filter chain to provide integration with container authentication.
# Parent Elements of <jee>
# <jee> Attributes
mappable-rolesA comma-separate list of roles to look for in the incoming HttpServletRequest.
user-service-refA reference to a user-service (or UserDetailsService bean) Id
# <logout>
Adds a LogoutFilter
to the filter stack.
This is configured with a SecurityContextLogoutHandler
.
# Parent Elements of <logout>
# <logout> Attributes
delete-cookiesA comma-separated list of the names of cookies which should be deleted when the user logs out.
invalidate-sessionMaps to the
invalidateHttpSession
of theSecurityContextLogoutHandler
. Defaults to "true", so the session will be invalidated on logout.logout-success-urlThe destination URL which the user will be taken to after logging out. Defaults to <form-login-login-page>/?logout (i.e. /login?logout)
Setting this attribute will inject the
SessionManagementFilter
with aSimpleRedirectInvalidSessionStrategy
configured with the attribute value. When an invalid session ID is submitted, the strategy will be invoked, redirecting to the configured URL.logout-urlThe URL which will cause a logout (i.e. which will be processed by the filter). Defaults to "/logout".
success-handler-refMay be used to supply an instance of
LogoutSuccessHandler
which will be invoked to control the navigation after logging out.
# <openid-login>
Similar to <form-login>
and has the same attributes.
The default value for login-processing-url
is "/login/openid".
An OpenIDAuthenticationFilter
and OpenIDAuthenticationProvider
will be registered.
The latter requires a reference to a UserDetailsService
.
Again, this can be specified by id
, using the user-service-ref
attribute, or will be located automatically in the application context.
# Parent Elements of <openid-login>
# <openid-login> Attributes
always-use-default-targetWhether the user should always be redirected to the default-target-url after login.
authentication-details-source-refReference to an AuthenticationDetailsSource which will be used by the authentication filter
authentication-failure-handler-refReference to an AuthenticationFailureHandler bean which should be used to handle a failed authentication request. Should not be used in combination with authentication-failure-url as the implementation should always deal with navigation to the subsequent destination
authentication-failure-urlThe URL for the login failure page. If no login failure URL is specified, Spring Security will automatically create a failure login URL at /login?login_error and a corresponding filter to render that login failure URL when requested.
authentication-success-forward-urlMaps a
ForwardAuthenticationSuccessHandler
toauthenticationSuccessHandler
property ofUsernamePasswordAuthenticationFilter
.authentication-failure-forward-urlMaps a
ForwardAuthenticationFailureHandler
toauthenticationFailureHandler
property ofUsernamePasswordAuthenticationFilter
.authentication-success-handler-refReference to an AuthenticationSuccessHandler bean which should be used to handle a successful authentication request. Should not be used in combination with default-target-url (or always-use-default-target) as the implementation should always deal with navigation to the subsequent destination
default-target-urlThe URL that will be redirected to after successful authentication, if the user’s previous action could not be resumed. This generally happens if the user visits a login page without having first requested a secured operation that triggers authentication. If unspecified, defaults to the root of the application.
login-pageThe URL for the login page. If no login URL is specified, Spring Security will automatically create a login URL at /login and a corresponding filter to render that login URL when requested.
login-processing-urlThe URL that the login form is posted to. If unspecified, it defaults to /login.
password-parameterThe name of the request parameter which contains the password. Defaults to "password".
user-service-refA reference to a user-service (or UserDetailsService bean) Id
username-parameterThe name of the request parameter which contains the username. Defaults to "username".
# Child Elements of <openid-login>
# <attribute-exchange>
The attribute-exchange
element defines the list of attributes which should be requested from the identity provider.
An example can be found in the OpenID Support section of the namespace configuration chapter.
More than one can be used, in which case each must have an identifier-match
attribute, containing a regular expression which is matched against the supplied OpenID identifier.
This allows different attribute lists to be fetched from different providers (Google, Yahoo etc).
# Parent Elements of <attribute-exchange>
# <attribute-exchange> Attributes
- identifier-matchA regular expression which will be compared against the claimed identity, when deciding which attribute-exchange configuration to use during authentication.
# Child Elements of <attribute-exchange>
# <openid-attribute>
Attributes used when making an OpenID AX Fetch Request (opens new window)
# Parent Elements of <openid-attribute>
# <openid-attribute> Attributes
countSpecifies the number of attributes that you wish to get back. For example, return 3 emails. The default value is 1.
nameSpecifies the name of the attribute that you wish to get back. For example, email.
requiredSpecifies if this attribute is required to the OP, but does not error out if the OP does not return the attribute. Default is false.
typeSpecifies the attribute type. For example, https://axschema.org/contact/email (opens new window). See your OP’s documentation for valid attribute types.
# <password-management>
This element configures password management.
# Parent Elements of <password-management>
# <password-management> Attributes
- change-password-pageThe change password page. Defaults to "/change-password".
# <port-mappings>
By default, an instance of PortMapperImpl
will be added to the configuration for use in redirecting to secure and insecure URLs.
This element can optionally be used to override the default mappings which that class defines.
Each child <port-mapping>
element defines a pair of HTTP:HTTPS ports.
The default mappings are 80:443 and 8080:8443.
An example of overriding these can be found in Redirect to HTTPS.
# Parent Elements of <port-mappings>
# Child Elements of <port-mappings>
# <port-mapping>
Provides a method to map http ports to https ports when forcing a redirect.
# Parent Elements of <port-mapping>
# <port-mapping> Attributes
httpThe http port to use.
httpsThe https port to use.
# <remember-me>
Adds the RememberMeAuthenticationFilter
to the stack.
This in turn will be configured with either a TokenBasedRememberMeServices
, a PersistentTokenBasedRememberMeServices
or a user-specified bean implementing RememberMeServices
depending on the attribute settings.
# Parent Elements of <remember-me>
# <remember-me> Attributes
authentication-success-handler-refSets the
authenticationSuccessHandler
property on theRememberMeAuthenticationFilter
if custom navigation is required. The value should be the name of aAuthenticationSuccessHandler
bean in the application context.data-source-refA reference to a
DataSource
bean. If this is set,PersistentTokenBasedRememberMeServices
will be used and configured with aJdbcTokenRepositoryImpl
instance.remember-me-parameterThe name of the request parameter which toggles remember-me authentication. Defaults to "remember-me". Maps to the "parameter" property of
AbstractRememberMeServices
.remember-me-cookieThe name of cookie which store the token for remember-me authentication. Defaults to "remember-me". Maps to the "cookieName" property of
AbstractRememberMeServices
.keyMaps to the "key" property of
AbstractRememberMeServices
. Should be set to a unique value to ensure that remember-me cookies are only valid within the one application [3]. If this is not set a secure random value will be generated. Since generating secure random values can take a while, setting this value explicitly can help improve startup times when using the remember-me functionality.services-aliasExports the internally defined
RememberMeServices
as a bean alias, allowing it to be used by other beans in the application context.services-refAllows complete control of the
RememberMeServices
implementation that will be used by the filter. The value should be theid
of a bean in the application context which implements this interface. Should also implementLogoutHandler
if a logout filter is in use.token-repository-refConfigures a
PersistentTokenBasedRememberMeServices
but allows the use of a customPersistentTokenRepository
bean.token-validity-secondsMaps to the
tokenValiditySeconds
property ofAbstractRememberMeServices
. Specifies the period in seconds for which the remember-me cookie should be valid. By default it will be valid for 14 days.use-secure-cookieIt is recommended that remember-me cookies are only submitted over HTTPS and thus should be flagged as "secure". By default, a secure cookie will be used if the connection over which the login request is made is secure (as it should be). If you set this property to
false
, secure cookies will not be used. Setting it totrue
will always set the secure flag on the cookie. This attribute maps to theuseSecureCookie
property ofAbstractRememberMeServices
.user-service-refThe remember-me services implementations require access to a
UserDetailsService
, so there has to be one defined in the application context. If there is only one, it will be selected and used automatically by the namespace configuration. If there are multiple instances, you can specify a beanid
explicitly using this attribute.
# <request-cache> Element
Sets the RequestCache
instance which will be used by the ExceptionTranslationFilter
to store request information before invoking an AuthenticationEntryPoint
.
# Parent Elements of <request-cache>
# <request-cache> Attributes
- refDefines a reference to a Spring bean that is a
RequestCache
.
# <session-management>
Session-management related functionality is implemented by the addition of a SessionManagementFilter
to the filter stack.
# Parent Elements of <session-management>
# <session-management> Attributes
invalid-session-urlSetting this attribute will inject the
SessionManagementFilter
with aSimpleRedirectInvalidSessionStrategy
configured with the attribute value. When an invalid session ID is submitted, the strategy will be invoked, redirecting to the configured URL.invalid-session-urlAllows injection of the InvalidSessionStrategy instance used by the SessionManagementFilter. Use either this or the
invalid-session-url
attribute but not both.session-authentication-error-urlDefines the URL of the error page which should be shown when the SessionAuthenticationStrategy raises an exception. If not set, an unauthorized (401) error code will be returned to the client. Note that this attribute doesn’t apply if the error occurs during a form-based login, where the URL for authentication failure will take precedence.
session-authentication-strategy-refAllows injection of the SessionAuthenticationStrategy instance used by the SessionManagementFilter
session-fixation-protectionIndicates how session fixation protection will be applied when a user authenticates. If set to "none", no protection will be applied. "newSession" will create a new empty session, with only Spring Security-related attributes migrated. "migrateSession" will create a new session and copy all session attributes to the new session. In Servlet 3.1 (Java EE 7) and newer containers, specifying "changeSessionId" will keep the existing session and use the container-supplied session fixation protection (HttpServletRequest#changeSessionId()). Defaults to "changeSessionId" in Servlet 3.1 and newer containers, "migrateSession" in older containers. Throws an exception if "changeSessionId" is used in older containers.
If session fixation protection is enabled, the
SessionManagementFilter
is injected with an appropriately configuredDefaultSessionAuthenticationStrategy
. See the Javadoc for this class for more details.
# Child Elements of <session-management>
# <concurrency-control>
Adds support for concurrent session control, allowing limits to be placed on the number of active sessions a user can have.
A ConcurrentSessionFilter
will be created, and a ConcurrentSessionControlAuthenticationStrategy
will be used with the SessionManagementFilter
.
If a form-login
element has been declared, the strategy object will also be injected into the created authentication filter.
An instance of SessionRegistry
(a SessionRegistryImpl
instance unless the user wishes to use a custom bean) will be created for use by the strategy.
# Parent Elements of <concurrency-control>
# <concurrency-control> Attributes
error-if-maximum-exceededIf set to "true" a
SessionAuthenticationException
will be raised when a user attempts to exceed the maximum allowed number of sessions. The default behaviour is to expire the original session.expired-urlThe URL a user will be redirected to if they attempt to use a session which has been "expired" by the concurrent session controller because the user has exceeded the number of allowed sessions and has logged in again elsewhere. Should be set unless
exception-if-maximum-exceeded
is set. If no value is supplied, an expiry message will just be written directly back to the response.expired-urlAllows injection of the ExpiredSessionStrategy instance used by the ConcurrentSessionFilter
max-sessionsMaps to the
maximumSessions
property ofConcurrentSessionControlAuthenticationStrategy
. Specify-1
as the value to support unlimited sessions.session-registry-aliasIt can also be useful to have a reference to the internal session registry for use in your own beans or an admin interface. You can expose the internal bean using the
session-registry-alias
attribute, giving it a name that you can use elsewhere in your configuration.session-registry-refThe user can supply their own
SessionRegistry
implementation using thesession-registry-ref
attribute. The other concurrent session control beans will be wired up to use it.
# <x509>
Adds support for X.509 authentication.
An X509AuthenticationFilter
will be added to the stack and an Http403ForbiddenEntryPoint
bean will be created.
The latter will only be used if no other authentication mechanisms are in use (its only functionality is to return an HTTP 403 error code).
A PreAuthenticatedAuthenticationProvider
will also be created which delegates the loading of user authorities to a UserDetailsService
.
# Parent Elements of <x509>
# <x509> Attributes
authentication-details-source-refA reference to an
AuthenticationDetailsSource
subject-principal-regexDefines a regular expression which will be used to extract the username from the certificate (for use with the
UserDetailsService
).user-service-refAllows a specific
UserDetailsService
to be used with X.509 in the case where multiple instances are configured. If not set, an attempt will be made to locate a suitable instance automatically and use that.
# <filter-chain-map>
Used to explicitly configure a FilterChainProxy instance with a FilterChainMap
# <filter-chain-map> Attributes
- request-matcherDefines the strategy to use for matching incoming requests. Currently the options are 'ant' (for ant path patterns), 'regex' for regular expressions and 'ciRegex' for case-insensitive regular expressions.
# Child Elements of <filter-chain-map>
# <filter-chain>
Used within to define a specific URL pattern and the list of filters which apply to the URLs matching that pattern. When multiple filter-chain elements are assembled in a list in order to configure a FilterChainProxy, the most specific patterns must be placed at the top of the list, with most general ones at the bottom.
# Parent Elements of <filter-chain>
# <filter-chain> Attributes
filtersA comma separated list of references to Spring beans that implement
Filter
. The value "none" means that noFilter
should be used for thisFilterChain
.patternA pattern that creates RequestMatcher in combination with the request-matcher
request-matcher-refA reference to a
RequestMatcher
that will be used to determine if anyFilter
from thefilters
attribute should be invoked.
# <filter-security-metadata-source>
Used to explicitly configure a FilterSecurityMetadataSource bean for use with a FilterSecurityInterceptor. Usually only needed if you are configuring a FilterChainProxy explicitly, rather than using the<http> element. The intercept-url elements used should only contain pattern, method and access attributes. Any others will result in a configuration error.
# <filter-security-metadata-source> Attributes
idA bean identifier, used for referring to the bean elsewhere in the context.
request-matcherDefines the strategy use for matching incoming requests. Currently the options are 'ant' (for ant path patterns), 'regex' for regular expressions and 'ciRegex' for case-insensitive regular expressions.
use-expressionsEnables the use of expressions in the 'access' attributes in <intercept-url> elements rather than the traditional list of configuration attributes. Defaults to 'true'. If enabled, each attribute should contain a single Boolean expression. If the expression evaluates to 'true', access will be granted.
# Child Elements of <filter-security-metadata-source>
1. See the xref:servlet/configuration/xml-namespace.adoc#ns-web-xml[introductory chapter
2. This feature is really just provided for convenience and is not intended for production (where a view technology will have been chosen and can be used to render a customized login page). The class DefaultLoginPageGeneratingFilter
is responsible for rendering the login page and will provide login forms for both normal form login and/or OpenID if required.
3. This doesn’t affect the use of PersistentTokenBasedRememberMeServices
, where the tokens are stored on the server side.