There are various database schema used by the framework and this appendix provides a single reference point to them all. You only need to provide the tables for the areas of functionality you require.
DDL statements are given for the HSQLDB database. You can use these as a guideline for defining the schema for the database you are using.
The standard JDBC implementation of the
JdbcDaoImpl) requires tables to load the password, account status (enabled or disabled) and a list of authorities (roles) for the user. You will need to adjust this schema to match the database dialect you are using.
create table users( username varchar_ignorecase(50) not null primary key, password varchar_ignorecase(50) not null, enabled boolean not null ); create table authorities ( username varchar_ignorecase(50) not null, authority varchar_ignorecase(50) not null, constraint fk_authorities_users foreign key(username) references users(username) ); create unique index ix_auth_username on authorities (username,authority);
CREATE TABLE USERS ( USERNAME NVARCHAR2(128) PRIMARY KEY, PASSWORD NVARCHAR2(128) NOT NULL, ENABLED CHAR(1) CHECK (ENABLED IN ('Y','N') ) NOT NULL ); CREATE TABLE AUTHORITIES ( USERNAME NVARCHAR2(128) NOT NULL, AUTHORITY NVARCHAR2(128) NOT NULL ); ALTER TABLE AUTHORITIES ADD CONSTRAINT AUTHORITIES_UNIQUE UNIQUE (USERNAME, AUTHORITY); ALTER TABLE AUTHORITIES ADD CONSTRAINT AUTHORITIES_FK1 FOREIGN KEY (USERNAME) REFERENCES USERS (USERNAME) ENABLE;
Spring Security 2.0 introduced support for group authorities in
JdbcDaoImpl. The table structure if groups are enabled is as follows. You will need to adjust this schema to match the database dialect you are using.
create table groups ( id bigint generated by default as identity(start with 0) primary key, group_name varchar_ignorecase(50) not null ); create table group_authorities ( group_id bigint not null, authority varchar(50) not null, constraint fk_group_authorities_group foreign key(group_id) references groups(id) ); create table group_members ( id bigint generated by default as identity(start with 0) primary key, username varchar(50) not null, group_id bigint not null, constraint fk_group_members_group foreign key(group_id) references groups(id) );
Remember that these tables are only required if you are using the provided JDBC
UserDetailsService implementation. If you write your own or choose to implement
AuthenticationProvider without a
UserDetailsService, then you have complete freedom over how you store the data, as long as the interface contract is satisfied.
This table is used to store data used by the more secure persistent token remember-me implementation. If you are using
JdbcTokenRepositoryImpl either directly or through the namespace, then you will need this table. Remember to adjust this schema to match the database dialect you are using.
create table persistent_logins ( username varchar(64) not null, series varchar(64) primary key, token varchar(64) not null, last_used timestamp not null );
There are four tables used by the Spring Security ACL implementation.
acl_sidstores the security identities recognised by the ACL system. These can be unique principals or authorities which may apply to multiple principals.
acl_classdefines the domain object types to which ACLs apply. The
classcolumn stores the Java class name of the object.
acl_object_identitystores the object identity definitions of specific domain objects.
acl_entrystores the ACL permissions which apply to a specific object identity and security identity.
It is assumed that the database will auto-generate the primary keys for each of the identities. The
JdbcMutableAclService has to be able to retrieve these when it has created a new row in the
acl_class tables. It has two properties which define the SQL needed to retrieve these values
sidIdentityQuery. Both of these default to
The ACL artifact JAR contains files for creating the ACL schema in HyperSQL (HSQLDB), PostgreSQL, MySQL/MariaDB, Microsoft SQL Server, and Oracle Database. These schemas are also demonstrated in the following sections.
The default schema works with the embedded HSQLDB database that is used in unit tests within the framework.
create table acl_sid( id bigint generated by default as identity(start with 100) not null primary key, principal boolean not null, sid varchar_ignorecase(100) not null, constraint unique_uk_1 unique(sid,principal) ); create table acl_class( id bigint generated by default as identity(start with 100) not null primary key, class varchar_ignorecase(100) not null, constraint unique_uk_2 unique(class) ); create table acl_object_identity( id bigint generated by default as identity(start with 100) not null primary key, object_id_class bigint not null, object_id_identity varchar_ignorecase(36) not null, parent_object bigint, owner_sid bigint, entries_inheriting boolean not null, constraint unique_uk_3 unique(object_id_class,object_id_identity), constraint foreign_fk_1 foreign key(parent_object)references acl_object_identity(id), constraint foreign_fk_2 foreign key(object_id_class)references acl_class(id), constraint foreign_fk_3 foreign key(owner_sid)references acl_sid(id) ); create table acl_entry( id bigint generated by default as identity(start with 100) not null primary key, acl_object_identity bigint not null, ace_order int not null, sid bigint not null, mask integer not null, granting boolean not null, audit_success boolean not null, audit_failure boolean not null, constraint unique_uk_4 unique(acl_object_identity,ace_order), constraint foreign_fk_4 foreign key(acl_object_identity) references acl_object_identity(id), constraint foreign_fk_5 foreign key(sid) references acl_sid(id) );
create table acl_sid( id bigserial not null primary key, principal boolean not null, sid varchar(100) not null, constraint unique_uk_1 unique(sid,principal) ); create table acl_class( id bigserial not null primary key, class varchar(100) not null, constraint unique_uk_2 unique(class) ); create table acl_object_identity( id bigserial primary key, object_id_class bigint not null, object_id_identity varchar(36) not null, parent_object bigint, owner_sid bigint, entries_inheriting boolean not null, constraint unique_uk_3 unique(object_id_class,object_id_identity), constraint foreign_fk_1 foreign key(parent_object)references acl_object_identity(id), constraint foreign_fk_2 foreign key(object_id_class)references acl_class(id), constraint foreign_fk_3 foreign key(owner_sid)references acl_sid(id) ); create table acl_entry( id bigserial primary key, acl_object_identity bigint not null, ace_order int not null, sid bigint not null, mask integer not null, granting boolean not null, audit_success boolean not null, audit_failure boolean not null, constraint unique_uk_4 unique(acl_object_identity,ace_order), constraint foreign_fk_4 foreign key(acl_object_identity) references acl_object_identity(id), constraint foreign_fk_5 foreign key(sid) references acl_sid(id) );
You will have to set the
sidIdentityQuery properties of
JdbcMutableAclService to the following values, respectively:
select currval(pg_get_serial_sequence('acl_class', 'id'))
select currval(pg_get_serial_sequence('acl_sid', 'id'))
CREATE TABLE acl_sid ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, principal BOOLEAN NOT NULL, sid VARCHAR(100) NOT NULL, UNIQUE KEY unique_acl_sid (sid, principal) ) ENGINE=InnoDB; CREATE TABLE acl_class ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, class VARCHAR(100) NOT NULL, UNIQUE KEY uk_acl_class (class) ) ENGINE=InnoDB; CREATE TABLE acl_object_identity ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, object_id_class BIGINT UNSIGNED NOT NULL, object_id_identity VARCHAR(36) NOT NULL, parent_object BIGINT UNSIGNED, owner_sid BIGINT UNSIGNED, entries_inheriting BOOLEAN NOT NULL, UNIQUE KEY uk_acl_object_identity (object_id_class, object_id_identity), CONSTRAINT fk_acl_object_identity_parent FOREIGN KEY (parent_object) REFERENCES acl_object_identity (id), CONSTRAINT fk_acl_object_identity_class FOREIGN KEY (object_id_class) REFERENCES acl_class (id), CONSTRAINT fk_acl_object_identity_owner FOREIGN KEY (owner_sid) REFERENCES acl_sid (id) ) ENGINE=InnoDB; CREATE TABLE acl_entry ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, acl_object_identity BIGINT UNSIGNED NOT NULL, ace_order INTEGER NOT NULL, sid BIGINT UNSIGNED NOT NULL, mask INTEGER UNSIGNED NOT NULL, granting BOOLEAN NOT NULL, audit_success BOOLEAN NOT NULL, audit_failure BOOLEAN NOT NULL, UNIQUE KEY unique_acl_entry (acl_object_identity, ace_order), CONSTRAINT fk_acl_entry_object FOREIGN KEY (acl_object_identity) REFERENCES acl_object_identity (id), CONSTRAINT fk_acl_entry_acl FOREIGN KEY (sid) REFERENCES acl_sid (id) ) ENGINE=InnoDB;
CREATE TABLE acl_sid ( id BIGINT NOT NULL IDENTITY PRIMARY KEY, principal BIT NOT NULL, sid VARCHAR(100) NOT NULL, CONSTRAINT unique_acl_sid UNIQUE (sid, principal) ); CREATE TABLE acl_class ( id BIGINT NOT NULL IDENTITY PRIMARY KEY, class VARCHAR(100) NOT NULL, CONSTRAINT uk_acl_class UNIQUE (class) ); CREATE TABLE acl_object_identity ( id BIGINT NOT NULL IDENTITY PRIMARY KEY, object_id_class BIGINT NOT NULL, object_id_identity VARCHAR(36) NOT NULL, parent_object BIGINT, owner_sid BIGINT, entries_inheriting BIT NOT NULL, CONSTRAINT uk_acl_object_identity UNIQUE (object_id_class, object_id_identity), CONSTRAINT fk_acl_object_identity_parent FOREIGN KEY (parent_object) REFERENCES acl_object_identity (id), CONSTRAINT fk_acl_object_identity_class FOREIGN KEY (object_id_class) REFERENCES acl_class (id), CONSTRAINT fk_acl_object_identity_owner FOREIGN KEY (owner_sid) REFERENCES acl_sid (id) ); CREATE TABLE acl_entry ( id BIGINT NOT NULL IDENTITY PRIMARY KEY, acl_object_identity BIGINT NOT NULL, ace_order INTEGER NOT NULL, sid BIGINT NOT NULL, mask INTEGER NOT NULL, granting BIT NOT NULL, audit_success BIT NOT NULL, audit_failure BIT NOT NULL, CONSTRAINT unique_acl_entry UNIQUE (acl_object_identity, ace_order), CONSTRAINT fk_acl_entry_object FOREIGN KEY (acl_object_identity) REFERENCES acl_object_identity (id), CONSTRAINT fk_acl_entry_acl FOREIGN KEY (sid) REFERENCES acl_sid (id) );
CREATE TABLE ACL_SID ( ID NUMBER(18) PRIMARY KEY, PRINCIPAL NUMBER(1) NOT NULL CHECK (PRINCIPAL IN (0, 1 )), SID NVARCHAR2(128) NOT NULL, CONSTRAINT ACL_SID_UNIQUE UNIQUE (SID, PRINCIPAL) ); CREATE SEQUENCE ACL_SID_SQ START WITH 1 INCREMENT BY 1 NOMAXVALUE; CREATE OR REPLACE TRIGGER ACL_SID_SQ_TR BEFORE INSERT ON ACL_SID FOR EACH ROW BEGIN SELECT ACL_SID_SQ.NEXTVAL INTO :NEW.ID FROM DUAL; END; CREATE TABLE ACL_CLASS ( ID NUMBER(18) PRIMARY KEY, CLASS NVARCHAR2(128) NOT NULL, CONSTRAINT ACL_CLASS_UNIQUE UNIQUE (CLASS) ); CREATE SEQUENCE ACL_CLASS_SQ START WITH 1 INCREMENT BY 1 NOMAXVALUE; CREATE OR REPLACE TRIGGER ACL_CLASS_ID_TR BEFORE INSERT ON ACL_CLASS FOR EACH ROW BEGIN SELECT ACL_CLASS_SQ.NEXTVAL INTO :NEW.ID FROM DUAL; END; CREATE TABLE ACL_OBJECT_IDENTITY( ID NUMBER(18) PRIMARY KEY, OBJECT_ID_CLASS NUMBER(18) NOT NULL, OBJECT_ID_IDENTITY NVARCHAR2(64) NOT NULL, PARENT_OBJECT NUMBER(18), OWNER_SID NUMBER(18), ENTRIES_INHERITING NUMBER(1) NOT NULL CHECK (ENTRIES_INHERITING IN (0, 1)), CONSTRAINT ACL_OBJECT_IDENTITY_UNIQUE UNIQUE (OBJECT_ID_CLASS, OBJECT_ID_IDENTITY), CONSTRAINT ACL_OBJECT_IDENTITY_PARENT_FK FOREIGN KEY (PARENT_OBJECT) REFERENCES ACL_OBJECT_IDENTITY(ID), CONSTRAINT ACL_OBJECT_IDENTITY_CLASS_FK FOREIGN KEY (OBJECT_ID_CLASS) REFERENCES ACL_CLASS(ID), CONSTRAINT ACL_OBJECT_IDENTITY_OWNER_FK FOREIGN KEY (OWNER_SID) REFERENCES ACL_SID(ID) ); CREATE SEQUENCE ACL_OBJECT_IDENTITY_SQ START WITH 1 INCREMENT BY 1 NOMAXVALUE; CREATE OR REPLACE TRIGGER ACL_OBJECT_IDENTITY_ID_TR BEFORE INSERT ON ACL_OBJECT_IDENTITY FOR EACH ROW BEGIN SELECT ACL_OBJECT_IDENTITY_SQ.NEXTVAL INTO :NEW.ID FROM DUAL; END; CREATE TABLE ACL_ENTRY ( ID NUMBER(18) NOT NULL PRIMARY KEY, ACL_OBJECT_IDENTITY NUMBER(18) NOT NULL, ACE_ORDER INTEGER NOT NULL, SID NUMBER(18) NOT NULL, MASK INTEGER NOT NULL, GRANTING NUMBER(1) NOT NULL CHECK (GRANTING IN (0, 1)), AUDIT_SUCCESS NUMBER(1) NOT NULL CHECK (AUDIT_SUCCESS IN (0, 1)), AUDIT_FAILURE NUMBER(1) NOT NULL CHECK (AUDIT_FAILURE IN (0, 1)), CONSTRAINT ACL_ENTRY_UNIQUE UNIQUE (ACL_OBJECT_IDENTITY, ACE_ORDER), CONSTRAINT ACL_ENTRY_OBJECT_FK FOREIGN KEY (ACL_OBJECT_IDENTITY) REFERENCES ACL_OBJECT_IDENTITY (ID), CONSTRAINT ACL_ENTRY_ACL_FK FOREIGN KEY (SID) REFERENCES ACL_SID(ID) ); CREATE SEQUENCE ACL_ENTRY_SQ START WITH 1 INCREMENT BY 1 NOMAXVALUE; CREATE OR REPLACE TRIGGER ACL_ENTRY_ID_TRIGGER BEFORE INSERT ON ACL_ENTRY FOR EACH ROW BEGIN SELECT ACL_ENTRY_SQ.NEXTVAL INTO :NEW.ID FROM DUAL; END;
This appendix provides a reference to the elements available in the security namespace and information on the underlying beans they create (a knowledge of the individual classes and how they work together is assumed - you can find more information in the project Javadoc and elsewhere in this document). If you haven’t used the namespace before, please read the introductory chapter on namespace configuration, as this is intended as a supplement to the information there. Using a good quality XML editor while editing a configuration based on the schema is recommended as this will provide contextual information on which elements and attributes are available as well as comments explaining their purpose. The namespace is written in RELAX NG Compact format and later converted into an XSD schema. If you are familiar with this format, you may wish to examine the schema file directly.
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.
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 within
FilterChainProxy. As of Spring Security 3.1, additional
http elements can be used to add extra filter chains . 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 (see the 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 the
FilterChainProxy 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 (see the introductory chapter for more on the
<http> namespace block always creates an
ExceptionTranslationFilter and a
FilterSecurityInterceptor. These are fixed and cannot be replaced with alternatives.
The attributes on the
<http> element control some of the properties on the core filters.
- access-decision-manager-ref Optional attribute specifying the ID of the
AccessDecisionManagerimplementation which should be used for authorizing HTTP requests. By default an
AffirmativeBasedimplementation is used for with a
- authentication-manager-ref A reference to the
AuthenticationManagerused for the
FilterChaincreated by this http element.
- auto-config Automatically 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-session Controls 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 Spring
true. The default is
- entry-point-ref Normally the
AuthenticationEntryPointused will be set depending on which authentication mechanisms have been configured. This attribute allows this behaviour to be overridden by defining a customized
AuthenticationEntryPointbean which will start the authentication process.
- jaas-api-provision If available, runs the request as the
Subjectacquired from the
JaasAuthenticationTokenwhich is implemented by adding a
JaasApiIntegrationFilterbean to the stack. Defaults to
- once-per-request Corresponds to the
FilterSecurityInterceptor. Defaults to
- pattern Defining 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.
- realm Sets the realm name used for basic authentication (if enabled). Corresponds to the
- request-matcher Defines the
RequestMatcherstrategy used in the
FilterChainProxyand the beans created by the
intercept-urlto match incoming requests. Options are currently
ciRegex, 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 an
AntPathRequestMatcher, regular expressions are matched using a
RegexRequestMatcherand for Spring MVC path matching the
MvcRequestMatcheris 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-ref A reference to a bean that implements
RequestMatcherthat will determine if this
FilterChainshould be used. This is a more powerful alternative to pattern.
- security A 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-ref Allows injection of a custom
- servlet-api-provision Provides versions of
HttpServletRequestsecurity methods such as
getPrincipal()which are implemented by adding a
SecurityContextHolderAwareRequestFilterbean to the stack. Defaults to
- use-expressions Enables EL-expressions in the
accessattribute, as described in the chapter on expression-based access-control. The default value is true.
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 theref attribute. This is discussed in more detail in the section on the ExceptionTranslationFilter.
This element allows for configuring a
CorsFilter. If no
CorsConfigurationSource is specified and Spring MVC is on the classpath, a
HandlerMappingIntrospector is used as the
The attributes on the
<cors> element control the headers element.
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.
Expires- 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 header can be used to prevent clickjacking attacks.
X-XSS-Protection- Can be set using the xss-protection element. The X-XSS-Protection 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 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-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-Report-Only- Can be set using the content-security-policy element. Content Security Policy (CSP) 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 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 is a mechanism that allows web developers to selectively enable, disable, and modify the behavior of certain APIs and web features in the browser.
The attributes on the
<headers> element control the headers element.
- defaults-disabled Optional attribute that specifies to disable the default Spring Security’s HTTP response headers. The default is false (the default headers are included).
Expires headers to ensure that the browser does not cache your secured pages.
When enabled adds the Strict-Transport-Security header to the response for any secure request. This allows the server to instruct browsers to automatically use HTTPS for future requests.
- max-age-seconds Specifies the maximum amount of time the host should be considered a Known HSTS Host. Default one year.
When enabled adds the Public Key Pinning Extension for HTTP header to the response for any secure request. This allows HTTPS websites to resist impersonation by attackers using mis-issued or otherwise fraudulent certificates.
- max-age-seconds Sets the value for the max-age directive of the Public-Key-Pins header. Default 60 days.
The list of pins
A pin is specified using the base64-encoded SPKI fingerprint as value and the cryptographic hash algorithm as attribute
When enabled adds the Content Security Policy (CSP) header to the response. CSP is a mechanism that web applications can leverage to mitigate content injection vulnerabilities, such as cross-site scripting (XSS).
- policy-directives The 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.
When enabled adds the Referrer Policy header to the response.
When enabled adds the Feature Policy header to the response.
DENYThe 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.
SAMEORIGINThe page can only be displayed in a frame on the same origin as the page itself
ALLOW-FROM originThe page can only be displayed in a frame on the specified origin.
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.
strategy Select the
AllowFromStrategyto use when using the ALLOW-FROM policy.
staticUse a single static ALLOW-FROM value. The value can be set through the value attribute.
regexpUse a regelur expression to validate incoming requests and if they are allowed. The regular expression can be set through the value attribute. The request parameter used to retrieve the value to validate can be specified using the from-parameter.
whitelistA comma-seperated list containing the allowed domains. The comma-seperated list can be set through the value attribute. The request parameter used to retrieve the value to validate can be specified using the from-parameter.
- ref Instead of using one of the predefined strategies it is also possible to use a custom
AllowFromStrategy. The reference to this bean can be specified through this ref attribute.
- value The value to use when ALLOW-FROM is used a strategy.
- xss-protection-disabled Do not include the header for reflected / Type-1 Cross-Site Scripting (XSS) protection.
- xss-protection-enabled Explicitly enable or disable reflected / Type-1 Cross-Site Scripting (XSS) protection.
- xss-protection-block When 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.
Add the X-Content-Type-Options header with the value of nosniff to the response. This disables MIME-sniffing for IE8+ and Chrome extensions.
Add additional headers to the response, both the name and value need to be specified.
AnonymousAuthenticationFilter to the stack and an
AnonymousAuthenticationProvider. Required if you are using the
- enabled With the default namespace setup, the anonymous "authentication" facility is automatically enabled. You can disable it using this property.
- granted-authority The 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
- key The 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.
This element will add Cross Site Request Forger (CSRF) 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.
- disabled Optional 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.
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.
- after The 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.
- position The explicit position at which the custom-filter should be placed in the chain. Use if you are replacing a standard filter.
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.
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"  The behaviour can be customized using the
- always-use-default-target If 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 the
UsernamePasswordAuthenticationFilter. Default value is
- authentication-details-source-ref Reference to an
AuthenticationDetailsSourcewhich will be used by the authentication filter
- authentication-failure-handler-ref Can 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
AuthenticationFailureHandlerbean in the application context.
- authentication-failure-url Maps to the
UsernamePasswordAuthenticationFilter. 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-ref This 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
AuthenticationSuccessHandlerbean in the application context. By default, an implementation of
SavedRequestAwareAuthenticationSuccessHandleris used and injected with the default-target-url.
- default-target-url Maps to the
UsernamePasswordAuthenticationFilter. 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-page The URL that should be used to render the login page. Maps to the
loginFormUrlproperty of the
LoginUrlAuthenticationEntryPoint. Defaults to "/login".
- login-processing-url Maps to the
UsernamePasswordAuthenticationFilter. The default value is "/login".
- password-parameter The name of the request parameter which contains the password. Defaults to "password".
- username-parameter The name of the request parameter which contains the username. Defaults to "username".
- authentication-success-forward-url Maps a
BasicAuthenticationEntryPoint to the configuration. The latter will only be used as the configuration entry point if form-based login is not enabled.
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.
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.
- access Lists the access attributes which will be stored in the
FilterInvocationSecurityMetadataSourcefor the defined URL pattern/method combination. This should be a comma-separated list of the security configuration attributes (such as role names).
- filters Can only take the value "none". This will cause any matching request to bypass the Spring Security filter chain entirely. None of the rest of the
<http>configuration will have any effect on the request and there will be no security context available for its duration. Access to secured methods during the request will fail.
- method The 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.
- pattern The pattern which defines the URL path. The content will depend on the
request-matcherattribute from the containing http element, so will default to ant path syntax.
- request-matcher-ref A reference to a
RequestMatcherthat will be used to determine if this
- requires-channel Can 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 a
ChannelProcessingFilterwill be added to the filter stack and its additional dependencies added to the application context.
<port-mappings> configuration is added, this will be used to by the
InsecureChannelProcessor beans to determine the ports used for redirecting to HTTP/HTTPS.
- servlet-path The 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 the
ServletContextthat have mappings starting with
'/'and are different; 2) The pattern starts with the same value of a registered
HttpServletpath, excluding the default (root)
Adds a J2eePreAuthenticatedProcessingFilter to the filter chain to provide integration with container authentication.
LogoutFilter to the filter stack. This is configured with a
- delete-cookies A comma-separated list of the names of cookies which should be deleted when the user logs out.
- invalidate-session Maps to the
SecurityContextLogoutHandler. Defaults to "true", so the session will be invalidated on logout.
logout-success-url The 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
SimpleRedirectInvalidSessionStrategyconfigured with the attribute value. When an invalid session ID is submitted, the strategy will be invoked, redirecting to the configured URL.
- logout-url The URL which will cause a logout (i.e. which will be processed by the filter). Defaults to "/logout".
<form-login> and has the same attributes. The default value for
login-processing-url is "/login/openid". An
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.
- always-use-default-target Whether the user should always be redirected to the default-target-url after login.
- authentication-details-source-ref Reference to an AuthenticationDetailsSource which will be used by the authentication filter
- authentication-failure-handler-ref Reference 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-url The 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-url Maps a
- authentication-failure-forward-url Maps a
- authentication-success-handler-ref Reference 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-url The 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-page The 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-url The URL that the login form is posted to. If unspecified, it defaults to /login.
- password-parameter The name of the request parameter which contains the password. Defaults to "password".
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).
Attributes used when making an OpenID AX Fetch Request
- count Specifies the number of attributes that you wish to get back. For example, return 3 emails. The default value is 1.
- required Specifies if this attribute is required to the OP, but does not error out if the OP does not return the attribute. Default is false.
- type Specifies the attribute type. For example, http://axschema.org/contact/email . See your OP’s documentation for valid attribute types.
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 the namespace introduction.
Provides a method to map http ports to https ports when forcing a redirect.
RememberMeAuthenticationFilter to the stack. This in turn will be configured with either a
PersistentTokenBasedRememberMeServices or a user-specified bean implementing
RememberMeServices depending on the attribute settings.
- authentication-success-handler-ref Sets the
authenticationSuccessHandlerproperty on the
RememberMeAuthenticationFilterif custom navigation is required. The value should be the name of a
AuthenticationSuccessHandlerbean in the application context.
- data-source-ref A reference to a
DataSourcebean. If this is set,
PersistentTokenBasedRememberMeServiceswill be used and configured with a
- remember-me-parameter The name of the request parameter which toggles remember-me authentication. Defaults to "remember-me". Maps to the "parameter" property of
- remember-me-cookie The name of cookie which store the token for remember-me authentication. Defaults to "remember-me". Maps to the "cookieName" property of
- key Maps 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 . 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-alias Exports the internally defined
RememberMeServicesas a bean alias, allowing it to be used by other beans in the application context.
- services-ref Allows complete control of the
RememberMeServicesimplementation that will be used by the filter. The value should be the
idof a bean in the application context which implements this interface. Should also implement
LogoutHandlerif a logout filter is in use.
- token-repository-ref Configures a
PersistentTokenBasedRememberMeServicesbut allows the use of a custom
- token-validity-seconds Maps to the
AbstractRememberMeServices. 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-cookie It 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 to
truewill always set the secure flag on the cookie. This attribute maps to the
- user-service-ref The 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 bean
idexplicitly using this attribute.
RequestCache instance which will be used by the
ExceptionTranslationFilter to store request information before invoking an
Session-management related functionality is implemented by the addition of a
SessionManagementFilter to the filter stack.
- invalid-session-url Setting this attribute will inject the
SimpleRedirectInvalidSessionStrategyconfigured with the attribute value. When an invalid session ID is submitted, the strategy will be invoked, redirecting to the configured URL.
- invalid-session-url Allows injection of the InvalidSessionStrategy instance used by the SessionManagementFilter. Use either this or the
invalid-session-urlattribute but not both.
- session-authentication-error-url Defines 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-ref Allows injection of the SessionAuthenticationStrategy instance used by the SessionManagementFilter
session-fixation-protection Indicates 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
SessionManagementFilteris injected with an appropriately configured
DefaultSessionAuthenticationStrategy. See the Javadoc for this class for more details.
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
SessionRegistryImpl instance unless the user wishes to use a custom bean) will be created for use by the strategy.
- error-if-maximum-exceeded If set to "true" a
SessionAuthenticationExceptionwill be raised when a user attempts to exceed the maximum allowed number of sessions. The default behaviour is to expire the original session.
- expired-url The 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-exceededis set. If no value is supplied, an expiry message will just be written directly back to the response.
- expired-url Allows injection of the ExpiredSessionStrategy instance used by the ConcurrentSessionFilter
- max-sessions Maps to the
-1as the value to support unlimited sessions.
- session-registry-alias It 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-aliasattribute, giving it a name that you can use elsewhere in your configuration.
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
- subject-principal-regex Defines a regular expression which will be used to extract the username from the certificate (for use with the
Used to explicitly configure a FilterChainProxy instance with a FilterChainMap
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.
- filters A comma separated list of references to Spring beans that implement
Filter. The value "none" means that no
Filtershould be used for this
- pattern A pattern that creates RequestMatcher in combination with the request-matcher
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.
- request-matcher Defines 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-expressions Enables 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.
Spring Security 4.0+ provides support for authorizing messages. One concrete example of where this is useful is to provide authorization in WebSocket based applications.
The websocket-message-broker element has two different modes. If the [email protected] is not specified, then it will do the following things:
- Ensure that any SimpAnnotationMethodMessageHandler has the AuthenticationPrincipalArgumentResolver registered as a custom argument resolver. This allows the use of
@AuthenticationPrincipalto resolve the principal of the current
- Ensures that the SecurityContextChannelInterceptor is automatically registered for the clientInboundChannel. This populates the SecurityContextHolder with the user that is found in the Message
- Ensures that a ChannelSecurityInterceptor is registered with the clientInboundChannel. This allows authorization rules to be specified for a message.
- Ensures that a CsrfChannelInterceptor is registered with the clientInboundChannel. This ensures that only requests from the original domain are enabled.
- Ensures that a CsrfTokenHandshakeInterceptor is registered with WebSocketHttpRequestHandler, TransportHandlingSockJsService, or DefaultSockJsService. This ensures that the expected CsrfToken from the HttpServletRequest is copied into the WebSocket Session attributes.
If additional control is necessary, the id can be specified and a ChannelSecurityInterceptor will be assigned to the specified id. All the wiring with Spring’s messaging infrastructure can then be done manually. This is more cumbersome, but provides greater control over the configuration.
- id A bean identifier, used for referring to the ChannelSecurityInterceptor bean elsewhere in the context. If specified, Spring Security requires explicit configuration within Spring Messaging. If not specified, Spring Security will automatically integrate with the messaging infrastructure as described in the section called “<websocket-message-broker>”
Defines an authorization rule for a message.
- pattern An ant based pattern that matches on the Message destination. For example, "/" matches any Message with a destination; "/admin/" matches any Message that has a destination that starts with "/admin/**".
- type The type of message to match on. Valid values are defined in SimpMessageType (i.e. CONNECT, CONNECT_ACK, HEARTBEAT, MESSAGE, SUBSCRIBE, UNSUBSCRIBE, DISCONNECT, DISCONNECT_ACK, OTHER).
Before Spring Security 3.0, an
AuthenticationManager was automatically registered internally. Now you must register one explicitly using the
<authentication-manager> element. This creates an instance of Spring Security’s
ProviderManager class, which needs to be configured with a list of one or more
AuthenticationProvider instances. These can either be created using syntax elements provided by the namespace, or they can be standard bean definitions, marked for addition to the list using the
Every Spring Security application which uses the namespace must have include this element somewhere. It is responsible for registering the
AuthenticationManager which provides authentication services to the application. All elements which create
AuthenticationProvider instances should be children of this element.
- alias This attribute allows you to define an alias name for the internal instance for use in your own configuration. Its use is described in thenamespace introduction.
- erase-credentials If set to true, the AuthenticationManager will attempt to clear any credentials data in the returned Authentication object, once the user has been authenticated. Literally it maps to the
eraseCredentialsAfterAuthenticationproperty of the
ProviderManager. This is discussed in the Core Services chapter.
Unless used with a
ref attribute, this element is shorthand for configuring a DaoAuthenticationProvider.
DaoAuthenticationProvider loads user information from a
UserDetailsService and compares the username/password combination with the values supplied at login. The
UserDetailsService instance can be defined either by using an available namespace element (
jdbc-user-service or by using the
user-service-ref attribute to point to a bean defined elsewhere in the application context). You can find examples of these variations in the namespace introduction.
If you have written your own
AuthenticationProvider implementation (or want to configure one of Spring Security’s own implementations as a traditional bean for some reason, then you can use the following syntax to add it to the internal list of
<security:authentication-manager> <security:authentication-provider ref="myAuthenticationProvider" /> </security:authentication-manager> <bean id="myAuthenticationProvider" class="com.something.MyAuthenticationProvider"/>
Causes creation of a JDBC-based UserDetailsService.
- authorities-by-username-query An SQL statement to query for a user’s granted authorities given a username.
The default is
select username, authority from authorities where username = ?
group-authorities-by-username-query An SQL statement to query user’s group authorities given a username. The default is
select g.id, g.group_name, ga.authority from groups g, group_members gm, group_authorities ga where gm.username = ? and g.id = ga.group_id and g.id = gm.group_id
- role-prefix A non-empty string prefix that will be added to role strings loaded from persistent storage (default is "ROLE_"). Use the value "none" for no prefix in cases where the default is non-empty.
Authentication providers can optionally be configured to use a password encoder as described in the namespace introduction. This will result in the bean being injected with the appropriate
Creates an in-memory UserDetailsService from a properties file or a list of "user" child elements. Usernames are converted to lower-case internally to allow for case-insensitive lookups, so this should not be used if case-sensitivity is required.
Represents a user in the application.
- authorities One of more authorities granted to the user. Separate authorities with a comma (but no space). For example, "ROLE_USER,ROLE_ADMINISTRATOR"
- password The password assigned to the user. This may be hashed if the corresponding authentication provider supports hashing (remember to set the "hash" attribute of the "user-service" element). This attribute be omitted in the case where the data will not be used for authentication, but only for accessing authorities. If omitted, the namespace will generate a random value, preventing its accidental use for authentication. Cannot be empty.
This element is the primary means of adding support for securing methods on Spring Security beans. Methods can be secured by the use of annotations (defined at the interface or class level) or by defining a set of pointcuts as child elements, using AspectJ syntax.
- access-decision-manager-ref Method security uses the same
AccessDecisionManagerconfiguration as web security, but this can be overridden using this attribute. By default an AffirmativeBased implementation is used for with a RoleVoter and an AuthenticatedVoter.
- authentication-manager-ref A reference to an
AuthenticationManagerthat should be used for method security.
- jsr250-annotations Specifies whether JSR-250 style attributes are to be used (for example "RolesAllowed"). This will require the javax.annotation.security classes on the classpath. Setting this to true also adds a
AccessDecisionManager, so you need to make sure you do this if you are using a custom implementation and want to use these annotations.