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 UserDetailsService
(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_sid
stores the security identities recognised by the ACL system.
These can be unique principals or authorities which may apply to multiple principals.
acl_class
defines the domain object types to which ACLs apply.
The class
column stores the Java class name of the object.
acl_object_identity
stores the object identity definitions of specific domain objects.
acl_entry
stores 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_sid
or acl_class
tables.
It has two properties which define the SQL needed to retrieve these values classIdentityQuery
and sidIdentityQuery
.
Both of these default to call identity()
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 classIdentityQuery
and 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 [22].
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 AuthenticationManager
).
Each <http>
namespace block always creates an SecurityContextPersistenceFilter
, 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.
AccessDecisionManager
implementation which should be used for authorizing HTTP requests.
By default an AffirmativeBased
implementation is used for with a RoleVoter
and an AuthenticatedVoter
.
AuthenticationManager
used for the FilterChain
created by this http element.
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 Authentication
.
true
.
The default is true
.
AuthenticationEntryPoint
used will be set depending on which authentication mechanisms have been configured.
This attribute allows this behaviour to be overridden by defining a customized AuthenticationEntryPoint
bean which will start the authentication process.
Subject
acquired from the JaasAuthenticationToken
which is implemented by adding a JaasApiIntegrationFilter
bean to the stack.
Defaults to false
.
observeOncePerRequest
property of FilterSecurityInterceptor
.
Defaults to true
.
realmName
property on BasicAuthenticationEntryPoint
.
RequestMatcher
strategy used in the FilterChainProxy
and the beans created by the intercept-url
to match incoming requests.
Options are currently mvc
, ant
, regex
and 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 RegexRequestMatcher
and for Spring MVC path matching the MvcRequestMatcher
is used.
See the Javadoc for these classes for more details on exactly how the matching is performed.
Ant paths are the default strategy.
RequestMatcher
that will determine if this FilterChain
should be used.
This is a more powerful alternative to pattern.
none
.
No security will be applied and none of Spring Security’s features will be available.
SecurityContextRepository
into the SecurityContextPersistenceFilter
.
HttpServletRequest
security methods such as isUserInRole()
and getPrincipal()
which are implemented by adding a SecurityContextHolderAwareRequestFilter
bean to the stack.
Defaults to true
.
access
attribute, 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 CorsFilter
or CorsConfigurationSource
is specified and Spring MVC is on the classpath, a HandlerMappingIntrospector
is used as the CorsConfigurationSource
.
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.
Cache-Control
, Pragma
, and 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
or 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
or 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.
Adds Cache-Control
, Pragma
, and 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.
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.
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).
When enabled adds the X-Frame-Options header to the response, this allows newer browsers to do some security checks and prevent clickjacking attacks.
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
ALLOW-FROM origin
The 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 AllowFromStrategy
to use when using the ALLOW-FROM policy.
static
Use a single static ALLOW-FROM value.
The value can be set through the value attribute.
regexp
Use 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.
whitelist
A 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.
AllowFromStrategy
.
The reference to this bean can be specified through this ref attribute.
Adds the X-XSS-Protection header to the response to assist in protecting against reflected / Type-1 Cross-Site Scripting (XSS) attacks. This is in no-way a full protection to XSS attacks!
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.
Adds an AnonymousAuthenticationFilter
to the stack and an AnonymousAuthenticationProvider
.
Required if you are using the IS_AUTHENTICATED_ANONYMOUSLY
attribute.
ROLE_ANONYMOUS
.
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.
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.
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.
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" [23] The behaviour can be customized using the <form-login>
Attributes.
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 alwaysUseDefaultTargetUrl
property of UsernamePasswordAuthenticationFilter
.
Default value is false
.
AuthenticationDetailsSource
which will be used by the authentication filter
AuthenticationFailureHandler
bean in the application context.
authenticationFailureUrl
property of 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.
AuthenticationSuccessHandler
bean in the application context.
By default, an implementation of SavedRequestAwareAuthenticationSuccessHandler
is used and injected with the default-target-url.
defaultTargetUrl
property of 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.
loginFormUrl
property of the LoginUrlAuthenticationEntryPoint
.
Defaults to "/login".
filterProcessesUrl
property of UsernamePasswordAuthenticationFilter
.
The default value is "/login".
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.
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.
FilterInvocationSecurityMetadataSource
for the defined URL pattern/method combination.
This should be a comma-separated list of the security configuration attributes (such as role names).
<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.
Note | |
---|---|
This property is invalid for filter-security-metadata-source |
request-matcher
attribute from the containing http element, so will default to ant path syntax.
RequestMatcher
that will be used to determine if this <intercept-url>
is used.
<intercept-url>
element, then a ChannelProcessingFilter
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.
Note | |
---|---|
This property is invalid for filter-security-metadata-source |
HttpServlet
's registered in the ServletContext
that have mappings starting with '/'
and are different; 2) The pattern starts with the same value of a registered HttpServlet
path, excluding the default (root) HttpServlet
'/'
.
Note | |
---|---|
This property is invalid for filter-security-metadata-source |
Adds a J2eePreAuthenticatedProcessingFilter to the filter chain to provide integration with container authentication.
Adds a LogoutFilter
to the filter stack.
This is configured with a SecurityContextLogoutHandler
.
invalidateHttpSession
of 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 SessionManagementFilter
with a SimpleRedirectInvalidSessionStrategy
configured with the attribute value.
When an invalid session ID is submitted, the strategy will be invoked, redirecting to the configured URL.
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.
ForwardAuthenticationSuccessHandler
to authenticationSuccessHandler
property of UsernamePasswordAuthenticationFilter
.
ForwardAuthenticationFailureHandler
to authenticationFailureHandler
property of UsernamePasswordAuthenticationFilter
.
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).
Attributes used when making an OpenID AX Fetch Request
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.
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.
authenticationSuccessHandler
property on the RememberMeAuthenticationFilter
if custom navigation is required.
The value should be the name of a AuthenticationSuccessHandler
bean in the application context.
DataSource
bean.
If this is set, PersistentTokenBasedRememberMeServices
will be used and configured with a JdbcTokenRepositoryImpl
instance.
AbstractRememberMeServices
.
AbstractRememberMeServices
.
AbstractRememberMeServices
.
Should be set to a unique value to ensure that remember-me cookies are only valid within the one application [24].
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.
RememberMeServices
as a bean alias, allowing it to be used by other beans in the application context.
RememberMeServices
implementation that will be used by the filter.
The value should be the id
of a bean in the application context which implements this interface.
Should also implement LogoutHandler
if a logout filter is in use.
PersistentTokenBasedRememberMeServices
but allows the use of a custom PersistentTokenRepository
bean.
tokenValiditySeconds
property of AbstractRememberMeServices
.
Specifies the period in seconds for which the remember-me cookie should be valid.
By default it will be valid for 14 days.
false
, secure cookies will not be used.
Setting it to true
will always set the secure flag on the cookie.
This attribute maps to the useSecureCookie
property of AbstractRememberMeServices
.
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 id
explicitly using this attribute.
Sets the RequestCache
instance which will be used by the ExceptionTranslationFilter
to store request information before invoking an AuthenticationEntryPoint
.
Session-management related functionality is implemented by the addition of a SessionManagementFilter
to the filter stack.
SessionManagementFilter
with a SimpleRedirectInvalidSessionStrategy
configured with the attribute value.
When an invalid session ID is submitted, the strategy will be invoked, redirecting to the configured URL.
invalid-session-url
attribute but not both.
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 SessionManagementFilter
is 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 SessionRegistry
(a SessionRegistryImpl
instance unless the user wishes to use a custom bean) will be created for use by the strategy.
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.
exception-if-maximum-exceeded
is set.
If no value is supplied, an expiry message will just be written directly back to the response.
maximumSessions
property of ConcurrentSessionControlAuthenticationStrategy
.
Specify -1
as the value to support unlimited sessions.
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
.
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.
Filter
.
The value "none" means that no Filter
should be used for this FilterChain
.
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.
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 websocket-message-broker@id is not specified, then it will do the following things:
@AuthenticationPrincipal
to resolve the principal of the current Authentication
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.
Defines an authorization rule for a message.
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 authentication-provider
element.
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.
eraseCredentialsAfterAuthentication
property 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 ProviderManager
:
<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.
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
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 PasswordEncoder
instance.
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.
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.
AccessDecisionManager
configuration 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.
AuthenticationManager
that should be used for method security.
Jsr250Voter
to the AccessDecisionManager
, so you need to make sure you do this if you are using a custom implementation and want to use these annotations.
MethodSecurityMetadataSource
instance can be supplied which will take priority over other sources (such as the default annotations).
AnnotationSecurityAspect
from the spring-security-aspects
module.
It is important to note that AspectJ follows Java’s rule that annotations on interfaces are not inherited. This means that methods that define the Security annotations on the interface will not be secured. Instead, you must place the Security annotation on the class when using AspectJ.
This element can be used to decorate an AfterInvocationProvider
for use by the security interceptor maintained by the <global-method-security>
namespace.
You can define zero or more of these within the global-method-security
element, each with a ref
attribute pointing to an AfterInvocationProvider
bean instance within your application context.
Allows the default expression-based mechanism for handling Spring Security’s pre and post invocation annotations (@PreFilter, @PreAuthorize, @PostFilter, @PostAuthorize) to be replaced entirely. Only applies if these annotations are enabled.
Defines the PrePostInvocationAttributeFactory instance which is used to generate pre and post invocation metadata from the annotated methods.
Customizes the PostInvocationAdviceProvider
with the ref as the PostInvocationAuthorizationAdvice
for the <pre-post-annotation-handling> element.
Customizes the PreInvocationAuthorizationAdviceVoter
with the ref as the PreInvocationAuthorizationAdviceVoter
for the <pre-post-annotation-handling> element.
<protect-pointcut>
Rather than defining security attributes on an individual method or class basis using the @Secured
annotation, you can define cross-cutting security constraints across whole sets of methods and interfaces in your service layer using the <protect-pointcut>
element.
You can find an example in the namespace introduction.
Can be used inside a bean definition to add a security interceptor to the bean and set up access configuration attributes for the bean’s methods
Creates a MethodSecurityMetadataSource instance
Defines a protected method and the access control configuration attributes that apply to it. We strongly advise you NOT to mix "protect" declarations with any services provided "global-method-security".
LDAP is covered in some details in its own chapter. We will expand on that here with some explanation of how the namespace options map to Spring beans. The LDAP implementation uses Spring LDAP extensively, so some familiarity with that project’s API may be useful.
<ldap-server>
Element
This element sets up a Spring LDAP ContextSource
for use by the other LDAP beans, defining the location of the LDAP server and other information (such as a username and password, if it doesn’t allow anonymous access) for connecting to it.
It can also be used to create an embedded server for testing.
Details of the syntax for both options are covered in the LDAP chapter.
The actual ContextSource
implementation is DefaultSpringSecurityContextSource
which extends Spring LDAP’s LdapContextSource
class.
The manager-dn
and manager-password
attributes map to the latter’s userDn
and password
properties respectively.
If you only have one server defined in your application context, the other LDAP namespace-defined beans will use it automatically.
Otherwise, you can give the element an "id" attribute and refer to it from other namespace beans using the server-ref
attribute.
This is actually the bean id
of the ContextSource
instance, if you want to use it in other traditional Spring beans.
This element is shorthand for the creation of an LdapAuthenticationProvider
instance.
By default this will be configured with a BindAuthenticator
instance and a DefaultAuthoritiesPopulator
.
As with all namespace authentication providers, it must be included as a child of the authentication-provider
element.
DefaultLdapAuthoritiesPopulator
's groupRoleAttribute
property.
Defaults to "cn".
DefaultLdapAuthoritiesPopulator
's groupSearchBase
constructor argument.
Defaults to "" (searching from the root).
DefaultLdapAuthoritiesPopulator
's groupSearchFilter
property.
Defaults to (uniqueMember={0}).
The substituted parameter is the DN of the user.
DefaultLdapAuthoritiesPopulator
's rolePrefix
property.
Defaults to "ROLE_".
Use the value "none" for no prefix in cases where the default is non-empty.
userDnPatterns
property of AbstractLdapAuthenticator
.
The value is a specific pattern used to build the user’s DN, for example "uid={0},ou=people".
The key "{0}" must be present and will be substituted with the username.
user-search-base Search base for user searches. Defaults to "". Only used with a 'user-search-filter'.
If you need to perform a search to locate the user in the directory, then you can set these attributes to control the search.
The BindAuthenticator
will be configured with a FilterBasedLdapUserSearch
and the attribute values map directly to the first two arguments of that bean’s constructor.
If these attributes aren’t set and no user-dn-pattern
has been supplied as an alternative, then the default search values of user-search-filter="(uid={0})"
and user-search-base=""
will be used.
user-search-filter The LDAP filter used to search for users (optional). For example "(uid={0})". The substituted parameter is the user’s login name.
If you need to perform a search to locate the user in the directory, then you can set these attributes to control the search.
The BindAuthenticator
will be configured with a FilterBasedLdapUserSearch
and the attribute values map directly to the first two arguments of that bean’s constructor.
If these attributes aren’t set and no user-dn-pattern
has been supplied as an alternative, then the default search values of user-search-filter="(uid={0})"
and user-search-base=""
will be used.
This is used as child element to <ldap-provider>
and switches the authentication strategy from BindAuthenticator
to PasswordComparisonAuthenticator
.
This element configures an LDAP UserDetailsService
.
The class used is LdapUserDetailsService
which is a combination of a FilterBasedLdapUserSearch
and a DefaultLdapAuthoritiesPopulator
.
The attributes it supports have the same usage as in <ldap-provider>
.
This appendix provides a reference of the modules in Spring Security and the additional dependencies that they require in order to function in a running application. We don’t include dependencies that are only used when building or testing Spring Security itself. Nor do we include transitive dependencies which are required by external dependencies.
The version of Spring required is listed on the project website, so the specific versions are omitted for Spring dependencies below. Note that some of the dependencies listed as "optional" below may still be required for other non-security functionality in a Spring application. Also dependencies listed as "optional" may not actually be marked as such in the project’s Maven POM files if they are used in most applications. They are "optional" only in the sense that you don’t need them unless you are using the specified functionality.
Where a module depends on another Spring Security module, the non-optional dependencies of the module it depends on are also assumed to be required and are not listed separately.
The core module must be included in any project using Spring Security.
Table 15.1. Core Dependencies
Dependency | Version | Description |
---|---|---|
ehcache | 1.6.2 | Required if the Ehcache-based user cache implementation is used (optional). |
spring-aop | Method security is based on Spring AOP | |
spring-beans | Required for Spring configuration | |
spring-expression | Required for expression-based method security (optional) | |
spring-jdbc | Required if using a database to store user data (optional). | |
spring-tx | Required if using a database to store user data (optional). | |
aspectjrt | 1.6.10 | Required if using AspectJ support (optional). |
jsr250-api | 1.0 | Required if you are using JSR-250 method-security annotations (optional). |
This module is typically required in web applications which use the Servlet API.
Table 15.2. Remoting Dependencies
Dependency | Version | Description |
---|---|---|
spring-security-core | ||
spring-web | Required for clients which use HTTP remoting support. |
This module is typically required in web applications which use the Servlet API.
Table 15.3. Web Dependencies
Dependency | Version | Description |
---|---|---|
spring-security-core | ||
spring-web | Spring web support classes are used extensively. | |
spring-jdbc | Required for JDBC-based persistent remember-me token repository (optional). | |
spring-tx | Required by remember-me persistent token repository implementations (optional). |
This module is only required if you are using LDAP authentication.
Table 15.4. LDAP Dependencies
Dependency | Version | Description |
---|---|---|
spring-security-core | ||
spring-ldap-core | 1.3.0 | LDAP support is based on Spring LDAP. |
spring-tx | Data exception classes are required. | |
apache-ds [1] | 1.5.5 | Required if you are using an embedded LDAP server (optional). |
shared-ldap | 0.9.15 | Required if you are using an embedded LDAP server (optional). |
ldapsdk | 4.1 | Mozilla LdapSDK. Used for decoding LDAP password policy controls if you are using password-policy functionality with OpenLDAP, for example. |
[1] The modules |
This module is required if you are using Spring Security namespace configuration.
Table 15.5. Config Dependencies
Dependency | Version | Description |
---|---|---|
spring-security-core | ||
spring-security-web | Required if you are using any web-related namespace configuration (optional). | |
spring-security-ldap | Required if you are using the LDAP namespace options (optional). | |
spring-security-openid | Required if you are using OpenID authentication (optional). | |
aspectjweaver | 1.6.10 | Required if using the protect-pointcut namespace syntax (optional). |
The ACL module.
Table 15.6. ACL Dependencies
Dependency | Version | Description |
---|---|---|
spring-security-core | ||
ehcache | 1.6.2 | Required if the Ehcache-based ACL cache implementation is used (optional if you are using your own implementation). |
spring-jdbc | Required if you are using the default JDBC-based AclService (optional if you implement your own). | |
spring-tx | Required if you are using the default JDBC-based AclService (optional if you implement your own). |
The CAS module provides integration with JA-SIG CAS.
Table 15.7. CAS Dependencies
Dependency | Version | Description |
---|---|---|
spring-security-core | ||
spring-security-web | ||
cas-client-core | 3.1.12 | The JA-SIG CAS Client. This is the basis of the Spring Security integration. |
ehcache | 1.6.2 | Required if you are using the Ehcache-based ticket cache (optional). |
The OpenID module.
Table 15.8. OpenID Dependencies
Dependency | Version | Description |
---|---|---|
spring-security-core | ||
spring-security-web | ||
openid4java-nodeps | 0.9.6 | Spring Security’s OpenID integration uses OpenID4Java. |
httpclient | 4.1.1 | openid4java-nodeps depends on HttpClient 4. |
guice | 2.0 | openid4java-nodeps depends on Guice 2. |
Provides Spring Security’s JSP tag implementations.
Table 15.9. Taglib Dependencies
Dependency | Version | Description |
---|---|---|
spring-security-core | ||
spring-security-web | ||
spring-security-acl | Required if you are using the | |
spring-expression | Required if you are using SPEL expressions in your tag access constraints. |
When using a proxy server it is important to ensure that you have configured your application properly. For example, many applications will have a load balancer that responds to request for https://example.com/ by forwarding the request to an application server at http://192.168.1:8080 Without proper configuration, the application server will not know that the load balancer exists and treat the request as though http://192.168.1:8080 was requested by the client.
To fix this you can use RFC 7239 to specify that a load balancer is being used. To make the application aware of this, you need to either configure your application server aware of the X-Forwarded headers. For example Tomcat uses the RemoteIpValve and Jetty uses ForwardedRequestCustomizer. Alternatively, Spring 4.3+ users can leverage ForwardedHeaderFilter.
Spring Security provides you with a very flexible framework for your authentication and authorization requirements, but there are many other considerations for building a secure application that are outside its scope. Web applications are vulnerable to all kinds of attacks which you should be familiar with, preferably before you start development so you can design and code with them in mind from the beginning. Check out thehttp://www.owasp.org/[OWASP web site] for information on the major issues facing web application developers and the countermeasures you can use against them.
Let’s assume you’re developing an enterprise application based on Spring. There are four security concerns you typically need to address: authentication, web request security, service layer security (i.e. your methods that implement business logic), and domain object instance security (i.e. different domain objects have different permissions). With these typical requirements in mind:
Service layer and domain object security: The absence of support in the servlet specification for services layer security or domain object instance security represent serious limitations for multi-tiered applications. Typically developers either ignore these requirements, or implement security logic within their MVC controller code (or even worse, inside the views). There are serious disadvantages with this approach:
For simple applications, servlet specification security may just be enough. Although when considered within the context of web container portability, configuration requirements, limited web request security flexibility, and non-existent services layer and domain object instance security, it becomes clear why developers often look to alternative solutions.
Spring Security 3.0 and 3.1 require at least JDK 1.5 and also require Spring 3.0.3 as a minimum. Ideally you should be using the latest release versions to avoid problems.
Spring Security 2.0.x requires a minimum JDK version of 1.4 and is built against Spring 2.0.x. It should also be compatible with applications using Spring 2.5.x.
What could be wrong?
Or subsititute an alternative complex scenario…
Realistically, you need an understanding of the technolgies you are intending to use before you can successfully build applications with them. Security is complicated. Setting up a simple configuration using a login form and some hard-coded users using Spring Security’s namespace is reasonably straightforward. Moving to using a backed JDBC database is also easy enough. But if you try and jump straight to a complicated deployment scenario like this you will almost certainly be frustrated. There is a big jump in the learning curve required to set up systems like CAS, configure LDAP servers and install SSL certificates properly. So you need to take things one step at a time.
From a Spring Security perspective, the first thing you should do is follow the "Getting Started" guide on the web site. This will take you through a series of steps to get up and running and get some idea of how the framework operates. If you are using other technologies which you aren’t familiar with then you should do some research and try to make sure you can use them in isolation before combining them in a complex system.
Authentication
Session Management
Miscellaneous
This means that authentication has failed. It doesn’t say why, as it is good practice to avoid giving details which might help an attacker guess account names or passwords.
This also means that if you ask this question in the forum, you will not get an answer unless you provide additional information.
As with any issue you should check the output from the debug log, note any exception stacktraces and related messages.
Step through the code in a debugger to see where the authentication fails and why.
Write a test case which exercises your authentication configuration outside of the application.
More often than not, the failure is due to a difference in the password data stored in a database and that entered by the user.
If you are using hashed passwords, make sure the value stored in your database is exactly the same as the value produced by the PasswordEncoder
configured in your application.
A common user problem with infinite loop and redirecting to the login page is caused by accidently configuring the login page as a "secured" resource. Make sure your configuration allows anonymous access to the login page, either by excluding it from the security filter chain or marking it as requiring ROLE_ANONYMOUS.
If your AccessDecisionManager includes an AuthenticatedVoter, you can use the attribute "IS_AUTHENTICATED_ANONYMOUSLY". This is automatically available if you are using the standard namespace configuration setup.
From Spring Security 2.0.1 onwards, when you are using namespace-based configuration, a check will be made on loading the application context and a warning message logged if your login page appears to be protected.
This is a debug level message which occurs the first time an anonymous user attempts to access a protected resource.
DEBUG [ExceptionTranslationFilter] - Access is denied (user is anonymous); redirecting to authentication entry point org.springframework.security.AccessDeniedException: Access is denied at org.springframework.security.vote.AffirmativeBased.decide(AffirmativeBased.java:68) at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:262)
It is normal and shouldn’t be anything to worry about.
The most common reason for this is that your browser has cached the page and you are seeing a copy which is being retrieved from the browsers cache.
Verify this by checking whether the browser is actually sending the request (check your server access logs, the debug log or use a suitable browser debugging plugin such as "Tamper Data" for Firefox). This has nothing to do with Spring Security and you should configure your application or server to set the appropriate Cache-Control
response headers.
Note that SSL requests are never cached.
This is a another debug level message which occurs the first time an anonymous user attempts to access a protected resource, but when you do not have an AnonymousAuthenticationFilter
in your filter chain configuration.
DEBUG [ExceptionTranslationFilter] - Authentication exception occurred; redirecting to authentication entry point org.springframework.security.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext at org.springframework.security.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:342) at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:254)
It is normal and shouldn’t be anything to worry about.
What’s wrong with my configuration?
Note that the permissions for an LDAP directory often do not allow you to read the password for a user. Hence it is often not possible to use the the section called “What is a UserDetailsService and do I need one?” where Spring Security compares the stored password with the one submitted by the user. The most common approach is to use LDAP "bind", which is one of the operations supported by the LDAP protocol. With this approach, Spring Security validates the password by attempting to authenticate to the directory as the user.
The most common problem with LDAP authentication is a lack of knowledge of the directory server tree structure and configuration. This will be different in different companies, so you have to find it out yourself. Before adding a Spring Security LDAP configuration to an application, it’s a good idea to write a simple test using standard Java LDAP code (without Spring Security involved), and make sure you can get that to work first. For example, to authenticate a user, you could use the following code:
@Test public void ldapAuthenticationIsSuccessful() throws Exception { Hashtable<String,String> env = new Hashtable<String,String>(); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, "cn=joe,ou=users,dc=mycompany,dc=com"); env.put(Context.PROVIDER_URL, "ldap://mycompany.com:389/dc=mycompany,dc=com"); env.put(Context.SECURITY_CREDENTIALS, "joespassword"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); InitialLdapContext ctx = new InitialLdapContext(env, null); }
Session management issues are a common source of forum questions. If you are developing Java web applications, you should understand how the session is maintained between the servlet container and the user’s browser. You should also understand the difference between secure and non-secure cookies and the implications of using HTTP/HTTPS and switching between the two. Spring Security has nothing to do with maintaining the session or providing session identifiers. This is entirely handled by the servlet container.
When I open another browser window after logging in, it doesn’t stop me from logging in again. Why can I log in more than once?
Browsers generally maintain a single session per browser instance. You cannot have two separate sessions at once. So if you log in again in another window or tab you are just reauthenticating in the same session. The server doesn’t know anything about tabs, windows or browser instances. All it sees are HTTP requests and it ties those to a particular session according to the value of the JSESSIONID cookie that they contain. When a user authenticates during a session, Spring Security’s concurrent session control checks the number ofother authenticated sessions that they have. If they are already authenticated with the same session, then re-authenticating will have no effect.
With the default configuration, Spring Security changes the session ID when the user authenticates. If you’re using a Servlet 3.1 or newer container, the session ID is simply changed. If you’re using an older container, Spring Security invalidates the existing session, creates a new session, and transfers the session data to the new session. Changing the session identifier in this manner prevents"session-fixation" attacks. You can find more about this online and in the reference manual.
It doesn’t work - I just end up back at the login page after authenticating.
This happens because sessions created under HTTPS, for which the session cookie is marked as "secure", cannot subsequently be used under HTTP. The browser will not send the cookie back to the server and any session state will be lost (including the security context information). Starting a session in HTTP first should work as the session cookie won’t be marked as secure. However, Spring Security’s Session Fixation Protection can interfere with this because it results in a new session ID cookie being sent back to the user’s browser, usually with the secure flag. To get around this, you can disable session fixation protection, but in newer Servlet containers you can also configure session cookies to never use the secure flag. Note that switching between HTTP and HTTPS is not a good idea in general, as any application which uses HTTP at all is vulnerable to man-in-the-middle attacks. To be truly secure, the user should begin accessing your site in HTTPS and continue using it until they log out. Even clicking on an HTTPS link from a page accessed over HTTP is potentially risky. If you need more convincing, check out a tool like sslstrip.
Sessions are maintained either by exchanging a session cookie or by adding a jsessionid
parameter to URLs (this happens automatically if you are using JSTL to output URLs, or if you call HttpServletResponse.encodeUrl
on URLs (before a redirect, for example). If clients have cookies disabled, and you are not rewriting URLs to include the jsessionid
, then the session will be lost.
Note that the use of cookies is preferred for security reasons, as it does not expose the session information in the URL.
Make sure you have added the listener to your web.xml file. It is essential to make sure that the Spring Security session registry is notified when a session is destroyed. Without it, the session information will not be removed from the registry.
<listener> <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class> </listener>
This usually means that the user’s application is creating a session somewhere, but that they aren’t aware of it.
The most common culprit is a JSP. Many people aren’t aware that JSPs create sessions by default.
To prevent a JSP from creating a session, add the directive <%@ page session="false" %>
to the top of the page.
If you are having trouble working out where a session is being created, you can add some debugging code to track down the location(s). One way to do this would be to add a javax.servlet.http.HttpSessionListener
to your application, which calls Thread.dumpStack()
in the sessionCreated
method.
If an HTTP 403 Forbidden is returned for HTTP POST, but works for HTTP GET then the issue is most likely related to CSRF. Either provide the CSRF Token or disable CSRF protection (not recommended).
Filters are not applied by default to forwards or includes. If you really want the security filters to be applied to forwards and/or includes, then you have to configure these explicitly in your web.xml using the <dispatcher> element, a child element of <filter-mapping>.
In a Spring web application, the application context which holds the Spring MVC beans for the dispatcher servlet is often separate from the main application context.
It is often defined in a file called myapp-servlet.xml
, where "myapp" is the name assigned to the Spring DispatcherServlet
in web.xml
. An application can have multiple DispatcherServlet
s, each with its own isolated application context.
The beans in these "child" contexts are not visible to the rest of the application.
The"parent" application context is loaded by the ContextLoaderListener
you define in your web.xml
and is visible to all the child contexts.
This parent context is usually where you define your security configuration, including the <global-method-security>
element). As a result any security constraints applied to methods in these web beans will not be enforced, since the beans cannot be seen from the DispatcherServlet
context.
You need to either move the <global-method-security>
declaration to the web context or moved the beans you want secured into the main application context.
Generally we would recommend applying method security at the service layer rather than on individual web controllers.
Why can’t I see the user information?
If you have excluded the request from the security filter chain using the attribute filters='none'
in the <intercept-url>
element that matches the URL pattern, then the SecurityContextHolder
will not be populated for that request.
Check the debug log to see whether the request is passing through the filter chain.
(You are reading the debug log, right?).
Method security will not hide links when using the url
attribute in <sec:authorize>
because we cannot readily reverse engineer what URL is mapped to what controller endpoint as controllers can rely on headers, current user, etc to determine what method to invoke.
The best way of locating classes is by installing the Spring Security source in your IDE. The distribution includes source jars for each of the modules the project is divided up into.
Add these to your project source path and you can navigate directly to Spring Security classes (Ctrl-Shift-T
in Eclipse). This also makes debugging easier and allows you to troubleshoot exceptions by looking directly at the code where they occur to see what’s going on there.
There is a general overview of what beans are created by the namespace in the namespace appendix of the reference guide.
There is also a detailed blog article called "Behind the Spring Security Namespace" on blog.springsource.com. If want to know the full details then the code is in the spring-security-config
module within the Spring Security 3.0 distribution.
You should probably read the chapters on namespace parsing in the standard Spring Framework reference documentation first.
Spring Security has a voter-based architecture which means that an access decision is made by a series of AccessDecisionVoter
s.
The voters act on the "configuration attributes" which are specified for a secured resource (such as a method invocation). With this approach, not all attributes may be relevant to all voters and a voter needs to know when it should ignore an attribute (abstain) and when it should vote to grant or deny access based on the attribute value.
The most common voter is the RoleVoter
which by default votes whenever it finds an attribute with the "ROLE_" prefix.
It makes a simple comparison of the attribute (such as "ROLE_USER") with the names of the authorities which the current user has been assigned.
If it finds a match (they have an authority called "ROLE_USER"), it votes to grant access, otherwise it votes to deny access.
The prefix can be changed by setting the rolePrefix
property of RoleVoter
. If you only need to use roles in your application and have no need for other custom voters, then you can set the prefix to a blank string, in which case the RoleVoter
will treat all attributes as roles.
It will depend on what features you are using and what type of application you are developing.
With Spring Security 3.0, the project jars are divided into clearly distinct areas of functionality, so it is straightforward to work out which Spring Security jars you need from your application requirements.
All applications will need the spring-security-core
jar.
If you’re developing a web application, you need the spring-security-web
jar.
If you’re using security namespace configuration you need the spring-security-config
jar, for LDAP support you need the spring-security-ldap
jar and so on.
For third-party jars the situation isn’t always quite so obvious. A good starting point is to copy those from one of the pre-built sample applications WEB-INF/lib directories. For a basic application, you can start with the tutorial sample. If you want to use LDAP, with an embedded test server, then use the LDAP sample as a starting point. The reference manual also includeshttp://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#appendix-dependencies[an appendix] listing the first-level dependencies for each Spring Security module with some information on whether they are optional and what they are required for.
If you are building your project with maven, then adding the appropriate Spring Security modules as dependencies to your pom.xml will automatically pull in the core jars that the framework requires. Any which are marked as "optional" in the Spring Security POM files will have to be added to your own pom.xml file if you need them.
If you are using Maven, you need to add the folowing to your pom dependencies:
<dependency> <groupId>org.apache.directory.server</groupId> <artifactId>apacheds-core</artifactId> <version>1.5.5</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.apache.directory.server</groupId> <artifactId>apacheds-server-jndi</artifactId> <version>1.5.5</version> <scope>runtime</scope> </dependency>
The other required jars should be pulled in transitively.
UserDetailsService
is a DAO interface for loading data that is specific to a user account.
It has no other function other to load that data for use by other components within the framework.
It is not responsible for authenticating the user.
Authenticating a user with a username/password combination is most commonly performed by the DaoAuthenticationProvider
, which is injected with a UserDetailsService
to allow it to load the password (and other data) for a user in order to compare it with the submitted value.
Note that if you are using LDAP, this approach may not work.
If you want to customize the authentication process then you should implement AuthenticationProvider
yourself.
See this blog article for an example integrating Spring Security authentication with Google App Engine.
How do I add support for extra login fields (e.g. a company name)?
This question comes up repeatedly in the Spring Security forum so you will find more information there by searching the archives (or through google).
The submitted login information is processed by an instance of UsernamePasswordAuthenticationFilter
. You will need to customize this class to handle the extra data field(s). One option is to use your own customized authentication token class (rather than the standard UsernamePasswordAuthenticationToken
), another is simply to concatenate the extra fields with the username (for example, using a ":" as the separator) and pass them in the username property of UsernamePasswordAuthenticationToken
.
You will also need to customize the actual authentication process.
If you are using a custom authentication token class, for example, you will have to write an AuthenticationProvider
to handle it (or extend the standard DaoAuthenticationProvider
). If you have concatenated the fields, you can implement your own UserDetailsService
which splits them up and loads the appropriate user data for authentication.
You can’t do this, since the fragment is not transmitted from the browser to the server. The URLs above are identical from the server’s perspective. This is a common question from GWT users.
Obviously you can’t (without resorting to something like thread-local variables) since the only information supplied to the interface is the username.
Instead of implementing UserDetailsService
, you should implement AuthenticationProvider
directly and extract the information from the supplied Authentication
token.
In a standard web setup, the getDetails()
method on the Authentication
object will return an instance of WebAuthenticationDetails
. If you need additional information, you can inject a custom AuthenticationDetailsSource
into the authentication filter you are using.
If you are using the namespace, for example with the <form-login>
element, then you should remove this element and replace it with a <custom-filter>
declaration pointing to an explicitly configured UsernamePasswordAuthenticationFilter
.
You can’t, since the UserDetailsService
has no awareness of the servlet API. If you want to store custom user data, then you should customize the UserDetails
object which is returned.
This can then be accessed at any point, via the thread-local SecurityContextHolder
. A call to SecurityContextHolder.getContext().getAuthentication().getPrincipal()
will return this custom object.
If you really need to access the session, then it must be done by customizing the web tier.
You can’t (and shouldn’t). You are probably misunderstanding its purpose. See "What is a UserDetailsService?" above.
People often ask about how to store the mapping between secured URLs and security metadata attributes in a database, rather than in the application context.
The first thing you should ask yourself is if you really need to do this. If an application requires securing, then it also requires that the security be tested thoroughly based on a defined policy. It may require auditing and acceptance testing before being rolled out into a production environment. A security-conscious organization should be aware that the benefits of their diligent testing process could be wiped out instantly by allowing the security settings to be modified at runtime by changing a row or two in a configuration database. If you have taken this into account (perhaps using multiple layers of security within your application) then Spring Security allows you to fully customize the source of security metadata. You can make it fully dynamic if you choose.
Both method and web security are protected by subclasses of AbstractSecurityInterceptor
which is configured with a SecurityMetadataSource
from which it obtains the metadata for a particular method or filter invocation.
For web security, the interceptor class is FilterSecurityInterceptor
and it uses the marker interface FilterInvocationSecurityMetadataSource
. The "secured object" type it operates on is a FilterInvocation
. The default implementation which is used (both in the namespace <http>
and when configuring the interceptor explicitly, stores the list of URL patterns and their corresponding list of "configuration attributes" (instances of ConfigAttribute
) in an in-memory map.
To load the data from an alternative source, you must be using an explicitly declared security filter chain (typically Spring Security’s FilterChainProxy
) in order to customize the FilterSecurityInterceptor
bean.
You can’t use the namespace.
You would then implement FilterInvocationSecurityMetadataSource
to load the data as you please for a particular FilterInvocation
[25]. A very basic outline would look something like this:
public class MyFilterSecurityMetadataSource implements FilterInvocationSecurityMetadataSource { public List<ConfigAttribute> getAttributes(Object object) { FilterInvocation fi = (FilterInvocation) object; String url = fi.getRequestUrl(); String httpMethod = fi.getRequest().getMethod(); List<ConfigAttribute> attributes = new ArrayList<ConfigAttribute>(); // Lookup your database (or other source) using this information and populate the // list of attributes return attributes; } public Collection<ConfigAttribute> getAllConfigAttributes() { return null; } public boolean supports(Class<?> clazz) { return FilterInvocation.class.isAssignableFrom(clazz); } }
For more information, look at the code for DefaultFilterInvocationSecurityMetadataSource
.
The LdapAuthenticationProvider
bean (which handles normal LDAP authentication in Spring Security) is configured with two separate strategy interfaces, one which performs the authentication and one which loads the user authorities, called LdapAuthenticator
and LdapAuthoritiesPopulator
respectively.
The DefaultLdapAuthoritiesPopulator
loads the user authorities from the LDAP directory and has various configuration parameters to allow you to specify how these should be retrieved.
To use JDBC instead, you can implement the interface yourself, using whatever SQL is appropriate for your schema:
public class MyAuthoritiesPopulator implements LdapAuthoritiesPopulator { @Autowired JdbcTemplate template; List<GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) { List<GrantedAuthority> = template.query("select role from roles where username = ?", new String[] {username}, new RowMapper<GrantedAuthority>() { /** * We're assuming here that you're using the standard convention of using the role * prefix "ROLE_" to mark attributes which are supported by Spring Security's RoleVoter. */ public GrantedAuthority mapRow(ResultSet rs, int rowNum) throws SQLException { return new SimpleGrantedAuthority("ROLE_" + rs.getString(1); } } } }
You would then add a bean of this type to your application context and inject it into the LdapAuthenticationProvider
. This is covered in the section on configuring LDAP using explicit Spring beans in the LDAP chapter of the reference manual.
Note that you can’t use the namespace for configuration in this case.
You should also consult the Javadoc for the relevant classes and interfaces.
What can I do short of abandoning namespace use?
The namespace functionality is intentionally limited, so it doesn’t cover everything that you can do with plain beans.
If you want to do something simple, like modify a bean, or inject a different dependency, you can do this by adding a BeanPostProcessor
to your configuration.
More information can be found in the Spring Reference Manual. In order to do this, you need to know a bit about which beans are created, so you should also read the blog article in the above question on how the namespace maps to Spring beans.
Normally, you would add the functionality you require to the postProcessBeforeInitialization
method of BeanPostProcessor
. Let’s say that you want to customize the AuthenticationDetailsSource
used by the UsernamePasswordAuthenticationFilter
, (created by the form-login
element). You want to extract a particular header called CUSTOM_HEADER
from the request and make use of it while authenticating the user.
The processor class would look like this:
public class BeanPostProcessor implements BeanPostProcessor { public Object postProcessAfterInitialization(Object bean, String name) { if (bean instanceof UsernamePasswordAuthenticationFilter) { System.out.println("********* Post-processing " + name); ((UsernamePasswordAuthenticationFilter)bean).setAuthenticationDetailsSource( new AuthenticationDetailsSource() { public Object buildDetails(Object context) { return ((HttpServletRequest)context).getHeader("CUSTOM_HEADER"); } }); } return bean; } public Object postProcessBeforeInitialization(Object bean, String name) { return bean; } }
You would then register this bean in your application context. Spring will automatically invoke it on the beans defined in the application context.
[22] See the introductory chapter for how to set up the mapping from your web.xml
[23] 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.
[24] This doesn’t affect the use of PersistentTokenBasedRememberMeServices
, where the tokens are stored on the server side.
[25] The FilterInvocation
object contains the HttpServletRequest
, so you can obtain the URL or any other relevant information on which to base your decision on what the list of returned attributes will contain.