The Security Namespace

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.

B.1. Web Application Security - the <http> Element

The <http> element encapsulates the security configuration for the web layer of your application. It creates a FilterChainProxy bean named "springSecurityFilterChain" which maintains the stack of security filters which make up the web security configuration [4]. Some core filters are always created and others will be added to the stack depending on the attributes 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 theFilterChainProxy bean. You can, of course, still do this if you need full control of the configuration.

All filters which require a reference to the AuthenticationManager will be automatically injected with the internal instance created by the namespace configuration (see the introductory chapter for more on the AuthenticationManager).

The <http> namespace block always creates an HttpSessionContextIntegrationFilter, an ExceptionTranslationFilter and a FilterSecurityInterceptor. These are fixed and cannot be replaced with alternatives.

B.1.1. <http> Attributes

The attributes on the <http> element control some of the properties on the core filters.

B.1.1.1. servlet-api-provision

Provides versions of HttpServletRequest security methods such as isUserInRole() and getPrincipal() which are implemented by adding a SecurityContextHolderAwareRequestFilter bean to the stack. Defaults to "true".

B.1.1.2. path-type

Controls whether URL patterns are interpreted as ant paths (the default) or regular expressions. In practice this sets a particular UrlMatcher instance on the FilterChainProxy.

B.1.1.3. lowercase-comparisons

Whether test URLs should be converted to lower case prior to comparing with defined path patterns. If unspecified, defaults to "true"

B.1.1.4. session-fixation-protection

Indicates whether an existing session should be invalidated when a user authenticates and a new session started. If set to "none" no change will be made. "newSession" will create a new empty session. "migrateSession" will create a new session and copy the session attributes to the new session. Defaults to "migrateSession".

If enabled this will add a SessionFixationProtectionFilter to the stack. The session fixation protection options on namespace-created instances of AbstractProcessingFilter will also be set appropriately.

B.1.1.5. realm

Sets the realm name used for basic authentication (if enabled). Corresponds to the realmName proerty on BasicProcessingFilterEntryPoint.

B.1.1.6. entry-point-ref

Normally the AuthenticationEntryPoint used will be set depending on which authentication mechanisms have been configured. This attribute allows this behaviour to be overridden by defining a customized AuthenticationEntryPoint bean which will start the authentication process.

B.1.1.7. access-decision-manager-ref

Optional attribute specifying the ID of the AccessDecisionManager implementation which should be used for authorizing HTTP requests. By default an AffirmativeBased implementation is used for with a RoleVoter and an AuthenticatedVoter.

B.1.1.8. access-denied-page

Allows the access denied page to be set (the user will be redirected here if an AccessDeniedException is raised). Corresponds to the errorPage property set on the AccessDeniedHandlerImpl which is used by the ExceptionTranslationFilter.

B.1.1.9. once-per-request

Corresponds to the observeOncePerRequest property of FilterSecurityInterceptor. Defaults to "true".

B.1.1.10. create-session

Controls the eagerness with which an HTTP session is created. If not set, defaults to "ifRequired". Other options are "always" and "never". The setting of this attribute affect the allowSessionCreation and forceEagerSessionCreation properties of HttpSessionContextIntegrationFilter. allowSessionCreation will always be true unless this attribute is set to "never". forceEagerSessionCreation is "false" unless it is set to "always". So the default configuration allows session creation but does not force it. The exception is if concurrent session control is enabled, when forceEagerSessionCreation will be set to true, regardless of what the setting is here. Using "never" would then cause an exception during the initialization of HttpSessionContextIntegrationFilter.

B.1.2. The <intercept-url> Element

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 FilterInvocationDefinitionSource used by the FilterSecurityInterceptor and to exclude particular patterns from the filter chain entirely (by setting the attribute filters="none"). It is also responsible for configuring a ChannelProcessingFilter if particular URLs need to be accessed by HTTPS, for example.

B.1.2.1. pattern

The pattern which defines the URL path. The content will depend on the path-type attribute from the containing http element, so will default to ant path syntax.

B.1.2.2. method

The HTTP Method which will be used in combination with the pattern to match an incoming request. If omitted, any method will match.

B.1.2.3. access

Lists the access attributes which will be stored in the FilterInvocationDefinitionSource for the defined URL pattern/method combination. This should be a comma-separated list of the attributes (such as role names).

B.1.2.4. 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 ChannelProcessingFilter will be added to the filter stack and its additional dependencies added to the application context. See the chapter on channel security for an example configuration using traditional beans.

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.

B.1.3. The <port-mappings> Element

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.

B.1.4. The <form-login> Element

Used to add an AuthenticationProcessingFilter to the filter stack and an AuthenticationProcessingFilterEntryPoint 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 "/spring-security-login" [5] The behaviour can be customized using the following attributes.

B.1.4.1. login-page

The URL that should be used to render the login page. Maps to the loginFormUrl property of the AuthenticationProcessingFilterEntryPoint. Defaults to "/spring-security-login".

B.1.4.2. login-processing-url

Maps to the filterProcessesUrl property of AuthenticationProcessingFilter. The default value is "/j_spring_security_check".

B.1.4.3. default-target-url

Maps to the defaultTargetUrl property of AuthenticationProcessingFilter. 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.

B.1.4.4. 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 alwaysUseDefaultTargetUrl property of AuthenticationProcessingFilter. Default value is "false".

B.1.4.5. authentication-failure-url

Maps to the authenticationFailureUrl property of AuthenticationProcessingFilter. Defines the URL the browser will be redirected to on login failure. Defaults to "/spring_security_login?login_error", which will be automatically handled by the automatic login page generator, re-rendering the login page with an error message.

B.1.5. The <http-basic> Element

Adds a BasicProcessingFilter and BasicProcessingFilterEntryPoint to the configuration. The latter will only be used as the configuration entry point if form-based login is not enabled.

B.1.6. The <remember-me> Element

Adds the RememberMeProcessingFilter 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.

B.1.6.1. data-source-ref

If this is set, PersistentTokenBasedRememberMeServices will be used and configured with a JdbcTokenRepositoryImpl instance.

B.1.6.2. token-repository-ref

Configures a PersistentTokenBasedRememberMeServices but allows the use of a custom PersistentTokenRepository bean.

B.1.6.3. services-ref

Allows complete control of the 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.

B.1.6.4. token-repository-ref

Configures a PersistentTokenBasedRememberMeServices but allows the use of a custom PersistentTokenRepository bean.

B.1.6.5. The key Attribute

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 [6].

B.1.6.6. token-validity-seconds

Maps to the 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.

B.1.6.7. 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 Id explicitly using this attribute.

B.1.7. The <concurrent-session-control> Element

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, along with a ConcurrentSessionControllerImpl and an instance of SessionRegistry (a SessionRegistryImpl instance unless the user wishes to use a custom bean). The controller is registered with the namespace's AuthenticationManager (ProviderManager). Other namespace-created beans which require a reference to the SessionRegistry will automatically have it injected.

Note that the forceEagerSessionCreation of HttpSessionContextIntegrationFilter will be set to true if concurrent session control is in use.

B.1.7.1. The max-sessions attribute

Maps to the maximumSessions property of ConcurrentSessionControllerImpl.

B.1.7.2. The expired-url attribute

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-exceeded is set. If no value is supplied, an expiry message will just be written directly back to the response.

B.1.7.3. The exception-if-maximum-exceeded attribute

If set to "true" a ConcurrentLoginException should be raised when a user attempts to exceed the maximum allowed number of sessions. The default behaviour is to expire the original session.

B.1.7.4. The session-registry-alias and session-registry-ref attributes

The user can supply their own SessionRegistry implementation using the session-registry-ref attribute. The other concurrent session control beans will be wired up to use it.

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 interal bean using the session-registry-alias attribute, giving it a name that you can use elsewhere in your configuration.

B.1.8. The <anonymous> Element

Adds an AnonymousProcessingFilter to the stack and an AnonymousAuthenticationProvider. Required if you are using the IS_AUTHENTICATED_ANONYMOUSLY attribute.

B.1.9. The <x509> Element

Adds support for X.509 authentication. An X509PreAuthenticatedProcessingFilter will be added to the stack and a PreAuthenticatedProcessingFilterEntryPoint bean will be created. The latter will only be used if no other authentication mechanisms are in use (it's 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.

B.1.9.1. The subject-principal-regex attribute

Defines a regular expression which will be used to extract the username from the certificate (for use with the UserDetailsService).

B.1.9.2. The user-service-ref attribute

Allows a specific UserDetailsService to be used with X.509 in the case where multiple instances are configured. If not set, an attempt will be made to locate a suitable instance automatically and use that.

B.1.10. The <openid-login> Element

Similar to <form-login> and has the same attributes. The default value for login-processing-url is "/j_spring_openid_security_check". An OpenIDAuthenticationProcessingFilter 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.

B.1.11. The <logout> Element

Adds a LogoutFilter to the filter stack. This is configured with a SecurityContextLogoutHandler.

B.1.11.1. The logout-url attribute

The URL which will cause a logout (i.e. which will be processed by the filter). Defaults to "/j_spring_security_logout".

B.1.11.2. The logout-success-url attribute

The destination URL which the user will be taken to after logging out. Defaults to "/".

B.1.11.3. The invalidate-session attribute

Maps to the invalidateHttpSession of the SecurityContextLogoutHandler. Defaults to "true", so the session will be invalidated on logout.

B.2. Authentication Services

If you are using the namespace, an AuthenticationManager is automatically registered and will be used by all the namespace-created beans which need to reference it. The bean is an instance of Spring Security's ProviderManager class, which needs to be configured with a list of one or moreAuthenticationProvider 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 custom-authentication-provider element.

B.2.1. The <authentication-provider> Element

This element is basically a shorthand syntax 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.

B.2.2. Using <custom-authentication-provider> to register an AuthenticationProvider

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 ProviderManager's list:

  <bean id="myAuthenticationProvider" class="com.something.MyAuthenticationProvider">
    <security:custom-authentication-provider />
  </bean>
  

B.2.3. The <authentication-manager> Element

Since the AuthenticationManager will be automatically registered in the application context, this element is entirely optional. It allows you to define an alias name for the internal instance for use in your own configuration and also to supply a link to a ConcurrentSessionController if you are configuring concurrent session control yourself rather than through the namespace (a rare requirement). Its use is described in the namespace introduction.

B.3. Method Security

B.3.1. The <global-method-security> Element

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.

Method security uses the same AccessDecisionManager configuration as web security, but this can be overridden as explained above Section B.1.1.7, “access-decision-manager-ref, using the same attribute.

B.3.1.1. The <secured-annotations> and <jsr250-annotations> Attributes

Setting these to "true" will enable support for Spring Security's own @Secured annotations and JSR-250 annotations, respectively. They are both disabled by default. Use of JSR-250 annotations also adds a 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.

B.3.1.2. Securing Methods using <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. This has two attributes:

  • expression - the pointcut expression

  • access - the security attributes which apply

You can find an example in the namespace introduction.

B.3.2. LDAP Namespace Options

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.

B.3.2.1. Defining the LDAP Server using the <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.

B.3.2.2. The <ldap-provider> Element

This element is shorthand for the creation of an LdapAuthenticationProvider instance. By default this will be configured with a BindAuthenticator instance and a DefaultAuthoritiesPopulator.

B.3.2.2.1. The user-dn-pattern Attribute

If your users are at a fixed location in the directory (i.e. you can work out the DN directly from the username without doing a directory search), you can use this attribute to map directly to the DN. It maps directly to the userDnPatterns property of AbstractLdapAuthenticator.

B.3.2.2.2. The user-search-base and user-search-filter Attributes

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.

B.3.2.2.3. group-search-filter, group-search-base, group-role-attribute and role-prefix Attributes

The value of group-search-base is mapped to the groupSearchBase constructor argument of DefaultAuthoritiesPopulator and defaults to "ou=groups". The default filter value is "(uniqueMember={0})", which assumes that the entry is of type "groupOfUniqueNames". group-role-attribute maps to the groupRoleAttribute attribute and defaults to "cn". Similarly role-prefix maps to rolePrefix and defaults to "ROLE_".

B.3.2.2.4. The <password-compare> Element

This is used as child element to <ldap-provider> and switches the authentication strategy from BindAuthenticator to PasswordComparisonAuthenticator. This can optionally be supplied with a hash attribute or with a child <password-encoder> element to hash the password before submitting it to the directory for comparison.

B.3.2.3. The <ldap-user-service> Element

This element configures an LDAP UserDetailsService. The class used is LdapUserDetailsService which is a combination of a FilterBasedLdapUserSearch and a DefaultAuthoritiesPopulator. The attributes it supports have the same usage as in <ldap-provider>.



[4] See the introductory chapter for how to set up the mapping from your web.xml

[5] 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.

[6] This doesn't affect the use of PersistentTokenBasedRememberMeServices, where the tokens are stored on the server side.