Security Namespace ConfigurationIntroduction Namespace configuration has been available since version 2.0 of the Spring framework. It
allows you to supplement the traditional Spring beans application context syntax with elements
from additional XML schema. You can find more information in the Spring Reference Documentation. A namespace element can be used simply to allow a more
concise way of configuring an individual bean or, more powerfully, to define an alternative
configuration syntax which more closely matches the problem domain and hides the underlying
complexity from the user. A simple element may conceal the fact that multiple beans and
processing steps are being added to the application context. For example, adding the following
element from the security namespace to an application context will start up an embedded LDAP
server for testing use within the application:
]]> This is much simpler than wiring up the equivalent Apache Directory Server
beans. The most common alternative configuration requirements are supported by attributes on
the ldap-server element and the user is isolated from worrying about which
beans they need to create and what the bean property names are. You can find
out more about the use of the ldap-server element in the chapter on
LDAP.. Use of a good XML editor while
editing the application context file should provide information on the attributes and elements
that are available. We would recommend that you try out the SpringSource Tool Suite as it
has special features for working with standard Spring namespaces. To start using the security namespace in your application context, you first need to make
sure that the spring-security-config jar is on your classpath. Then all you need to do is
add the schema declaration to your application context file:
...
]]> In many of the examples you will see (and in the sample) applications, we
will often use "security" as the default namespace rather than "beans", which means we can
omit the prefix on all the security namespace elements, making the content easier to read. You
may also want to do this if you have your application context divided up into separate files
and have most of your security configuration in one of them. Your security application context
file would then start like this
...
]]> We'll assume this syntax is being used from now on in this chapter. Design of the Namespace The namespace is designed to capture the most common uses of the framework and provide
a simplified and concise syntax for enabling them within an application. The design is based
around the large-scale dependencies within the framework, and can be divided up into the
following areas: Web/HTTP Security - the most complex part. Sets up the filters
and related service beans used to apply the framework authentication mechanisms, to
secure URLs, render login and error pages and much
more.Business Object (Method) Security - options for securing the
service layer.AuthenticationManager - handles authentication requests from
other parts of the framework.AccessDecisionManager - provides access decisions for web and
method security. A default one will be registered, but you can also choose to use a
custom one, declared using normal Spring bean
syntax.AuthenticationProviders - mechanisms against which the
authentication manager authenticates users. The namespace provides supports for
several standard options and also a means of adding custom beans declared using a
traditional syntax. UserDetailsService - closely related to authentication providers,
but often also required by other beans.We'll see how to configure these in the following sections.Getting Started with Security Namespace Configuration In this section, we'll look at how you can build up a namespace configuration to use some
of the main features of the framework. Let's assume you initially want to get up and running
as quickly as possible and add authentication support and access control to an existing web
application, with a few test logins. Then we'll look at how to change over to authenticating
against a database or other security repository. In later sections we'll introduce more
advanced namespace configuration options. web.xml Configuration The first thing you need to do is add the following filter declaration to your
web.xml file: springSecurityFilterChainorg.springframework.web.filter.DelegatingFilterProxyspringSecurityFilterChain/*]]>
This provides a hook into the Spring Security web
infrastructure. DelegatingFilterProxy is a Spring Framework class
which delegates to a filter implementation which is defined as a Spring bean in your
application context. In this case, the bean is named
springSecurityFilterChain, which is an internal infrastructure bean created
by the namespace to handle web security. Note that you should not use this bean name
yourself. Once you've added this to your web.xml, you're ready to start
editing your application context file. Web security services are configured using the
<http> element. A Minimal <http> Configuration All you need to enable web security to begin with is
]]>
Which says that we want all URLs within our application to be secured,
requiring the role ROLE_USER to access them. The
<http> element is the parent for all web-related namespace
functionality. The <intercept-url> element defines a
pattern which is matched against the URLs of incoming requests using an
ant path style syntaxSee the section on Request
Matching in the Web Application Infrastructure chapter for more details
on how matches are actually performed.. The access attribute defines the access
requirements for requests matching the given pattern. With the default configuration, this
is typically a comma-separated list of roles, one of which a user must have to be allowed to
make the request. The prefix ROLE_ is a marker which indicates that a simple
comparison with the user's authorities should be made. In other words, a normal role-based
check should be used. Access-control in Spring Security is not limited to the use of simple
roles (hence the use of the prefix to differentiate between different types of security
attributes). We'll see later how the interpretation can varyThe
interpretation of the comma-separated values in the access attribute
depends on the implementation of the AccessDecisionManager which is used. In Spring Security 3.0, the attribute can
also be populated with an EL
expression..You can use multiple <intercept-url> elements to define
different access requirements for different sets of URLs, but they will be evaluated in
the order listed and the first match will be used. So you must put the most specific
matches at the top. You can also add a method attribute to limit the
match to a particular HTTP method (GET, POST,
PUT etc.). If a request matches multiple patterns, the
method-specific match will take precedence regardless of ordering. To add some users, you can define a set of test data directly in the namespace:
]]>
If you are familiar with pre-namespace versions of the framework, you can probably
already guess roughly what's going on here. The <http> element is
responsible for creating a FilterChainProxy and the filter beans
which it uses. Common problems like incorrect filter ordering are no longer an issue as
the filter positions are predefined.The <authentication-provider> element creates a
DaoAuthenticationProvider bean and the
<user-service> element creates an
InMemoryDaoImpl. All authentication-provider
elements must be children of the <authentication-manager> element,
which creates a ProviderManager and registers the authentication
providers with it. You can find more detailed information on the beans that are created in
the namespace appendix. It's worth
cross-checking this if you want to start understanding what the important classes in the
framework are and how they are used, particularly if you want to customise things
later. The configuration above defines two users, their passwords and their roles within the
application (which will be used for access control). It is also possible to load user
information from a standard properties file using the properties
attribute on user-service. See the section on in-memory authentication for more
details on the file format. Using the <authentication-provider>
element means that the user information will be used by the authentication manager to
process authentication requests. You can have multiple
<authentication-provider> elements to define different
authentication sources and each will be consulted in turn. At this point you should be able to start up your application and you will be required
to log in to proceed. Try it out, or try experimenting with the tutorial
sample application that comes with the project. The above configuration actually adds quite
a few services to the application because we have used the auto-config
attribute. For example, form-based login processing is automatically enabled. What does auto-config Include? The auto-config attribute, as we have used it above, is just a
shorthand syntax for:
]]> These other elements are responsible for setting up form-login, basic
authentication and logout handling services respectively In versions prior
to 3.0, this list also included remember-me functionality. This could cause some
confusing errors with some configurations and was removed in 3.0. In 3.0, the addition
of an AnonymousAuthenticationFilter is part of the default
<http> configuration, so the <anonymous
/> element is added regardless of whether auto-config
is enabled. . They each have attributes which can be used to alter
their behaviour. Form and Basic Login Options You might be wondering where the login form came from when you were prompted to log
in, since we made no mention of any HTML files or JSPs. In fact, since we didn't
explicitly set a URL for the login page, Spring Security generates one automatically,
based on the features that are enabled and using standard values for the URL which
processes the submitted login, the default target URL the user will be sent to after
loggin in and so on. However, the namespace offers plenty of support to allow you to
customize these options. For example, if you want to supply your own login page, you could
use:
]]>
Note that you can still use auto-config. The
form-login element just overrides the default settings. Also note
that we've added an extra intercept-url element to say that any
requests for the login page should be available to anonymous users See the
chapter on anonymous authentication and also the
AuthenticatedVoter class for
more details on how the value IS_AUTHENTICATED_ANONYMOUSLY is
processed.. Otherwise the request would be matched by the pattern
/** and it wouldn't be possible to access the login page itself! This
is a common configuration error and will result in an infinite loop in the application.
Spring Security will emit a warning in the log if your login page appears to be secured.
It is also possible to have all requests matching a particular pattern bypass the security
filter chain completely:
]]>
It's important to realise that these requests will be completely
oblivious to any further Spring Security web-related configuration or additional
attributes such as requires-channel, so you will not be able to access
information on the current user or call secured methods during the request. Use
access='IS_AUTHENTICATED_ANONYMOUSLY' as an alternative if you still
want the security filter chain to be applied.
Using filters="none" operates by creating an empty filter
chain in Spring Security's FilterChainProxy, whereas
the access attributes are used to configure the
FilterSecurityInterceptor in the single filter chain
which is created by the namespace configuration. The two are applied
independently, so if you have an access contraint for a sub-pattern of a
pattern which has a filters="none" attribute, the access
constraint will be ignored, even if it is listed first. It isn't possible to
apply a filters="none" attribute to the pattern
/** since this is used by the namespace filter chain. In
version 3.1 things are more flexible. You can define multiple filter chains
and the filters attribute is no longer supported.If you want to use basic authentication instead of form login, then change the
configuration to
]]>
Basic authentication will then take precedence and will be used to
prompt for a login when a user attempts to access a protected resource. Form login is
still available in this configuration if you wish to use it, for example through a login
form embedded in another web page. Setting a Default Post-Login Destination If a form login isn't prompted by an attempt to access a protected resource, the
default-target-url option comes into play. This is the URL the user
will be taken to after logging in, and defaults to "/". You can also configure things so
that they user always ends up at this page (regardless of whether
the login was "on-demand" or they explicitly chose to log in) by setting the
always-use-default-target attribute to "true". This is useful if
your application always requires that the user starts at a "home" page, for example:
]]>
Using other Authentication Providers In practice you will need a more scalable source of user information than a few names
added to the application context file. Most likely you will want to store your user
information in something like a database or an LDAP server. LDAP namespace configuration is
dealt with in the LDAP chapter, so we won't cover it here.
If you have a custom implementation of Spring Security's
UserDetailsService, called "myUserDetailsService" in your
application context, then you can authenticate against this using
]]>
If you want to use a database, then you can use
]]>
Where securityDataSource is the name of a
DataSource bean in the application context, pointing at a database
containing the standard Spring Security user
data tables. Alternatively, you could configure a Spring Security
JdbcDaoImpl bean and point at that using the
user-service-ref attribute:
]]>
You can also use standard
AuthenticationProvider beans as follows
]]>
where myAuthenticationProvider is the name of a
bean in your application context which implements
AuthenticationProvider. You can use multiple
authentication-provider elements, in which case they will be checked
in the order they are declared when attempting to authenticated a user. See for more on information on how the Spring Security
AuthenticationManager is configured using the namespace. Adding a Password Encoder Often your password data will be encoded using a hashing algorithm. This is supported
by the <password-encoder> element. With SHA encoded passwords,
the original authentication provider configuration would look like this:
]]>
When using hashed passwords, it's also a good idea to use a salt value to protect
against dictionary attacks and Spring Security supports this too. Ideally you would want
to use a randomly generated salt value for each user, but you can use any property of the
UserDetails object which is loaded by your
UserDetailsService. For example, to use the
username property, you would use
]]> You can use a custom password encoder bean by using the
ref attribute of password-encoder. This should
contain the name of a bean in the application context which is an instance of Spring
Security's PasswordEncoder interface. Advanced Web FeaturesRemember-Me AuthenticationSee the separate Remember-Me chapter for
information on remember-me namespace configuration.Adding HTTP/HTTPS Channel SecurityIf your application supports both HTTP and HTTPS, and you require that particular URLs
can only be accessed over HTTPS, then this is directly supported using the
requires-channel attribute on <intercept-url>:
...
]]>
With this configuration in place, if a user attempts to access
anything matching the "/secure/**" pattern using HTTP, they will first be redirected to an
HTTPS URL. The available options are "http", "https" or "any". Using the value "any" means
that either HTTP or HTTPS can be used. If your application uses non-standard ports for HTTP and/or HTTPS, you can specify a
list of port mappings as follows:
...
]]>
Session ManagementDetecting Timeouts You can configure Spring Security to detect the submission of an invalid session ID
and redirect the user to an appropriate URL. This is achieved through the
session-management element:
...
]]>Concurrent Session ControlIf you wish to place constraints on a single user's ability to log in to your
application, Spring Security supports this out of the box with the following simple
additions. First you need to add the following listener to your
web.xml file to keep Spring Security updated about session
lifecycle events:
org.springframework.security.web.session.HttpSessionEventPublisher
]]> Then add the following lines to your application context:
...
]]>
This will prevent a user from logging in multiple times - a
second login will cause the first to be invalidated. Often you would prefer to prevent a
second login, in which case you can use
...
]]>
The second login will then be rejected. By
rejected, we mean that the user will be sent to the
authentication-failure-url if form-based login is being used. If the
second authentication takes place through another non-interactive mechanism, such as
remember-me, an unauthorized (402) error will be sent to
the client. If instead you want to use an error page, you can add the attribute
session-authentication-error-url to the
session-management element. If you are using a customized authentication filter for form-based login, then you
have to configure concurrent session control support explicitly. More details can be found
in the Session Management chapter. Session Fixation Attack Protection
Session fixation
attacks are a potential risk where it is possible for a malicious attacker to create a
session by accessing a site, then persuade another user to log in with the same session
(by sending them a link containing the session identifier as a parameter, for example).
Spring Security protects against this automatically by creating a new session when a user
logs in. If you don't require this protection, or it conflicts with some other
requirement, you can control the behaviour using the
session-fixation-protection attribute on
<session-management>, which has three options
migrateSession - creates a new
session and copies the existing session attributes to the new session. This is the
default.none - Don't do
anything. The original session will be
retained.newSession - Create
a new "clean" session, without copying the existing session
data.OpenID SupportThe namespace supports OpenID login either
instead of, or in addition to normal form-based login, with a simple change:
]]>You should then register yourself with an OpenID provider (such as
myopenid.com), and add the user information to your in-memory
<user-service> :
]]> You should be able to login using the myopenid.com site to
authenticate. It is also possible to select a specific
UserDetailsService bean for use OpenID by setting the
user-service-ref attribute on the openid-login
element. See the previous section on authentication
providers for more information. Note that we have omitted the password attribute
from the above user configuration, since this set of user data is only being used to load
the authorities for the user. A random password will be generate internally, preventing you
from accidentally using this user data as an authentication source elsewhere in your
configuration.Attribute ExchangeSupport for OpenID attribute
exchange. As an example, the following configuration would attempt to retrieve
the email and full name from the OpenID provider, for use by the application:
]]>The type of each OpenID attribute is a URI,
determined by a particular schema, in this case http://axschema.org/. If an attribute must be retrieved for successful
authentication, the required attribute can be set. The exact schema and
attributes supported will depend on your OpenID provider. The attribute values are
returned as part of the authentication process and can be accessed afterwards using the
following
code:OpenIDAuthenticationToken token = (OpenIDAuthenticationToken)SecurityContextHolder.getContext().getAuthentication();
List<OpenIDAttribute> attributes = token.getAttributes();The
OpenIDAttribute contains the attribute type and the retrieved
value (or values in the case of multi-valued attributes). We'll see more about how the
SecurityContextHolder class is used when we look at core Spring
Security components in the technical overview
chapter.Adding in Your Own FiltersIf you've used Spring Security before, you'll know that the framework maintains a chain
of filters in order to apply its services. You may want to add your own filters to the stack
at particular locations or use a Spring Security filter for which there isn't currently a
namespace configuration option (CAS, for example). Or you might want to use a customized
version of a standard namespace filter, such as the
UsernamePasswordAuthenticationFilter which is created by the
<form-login> element, taking advantage of some of the extra
configuration options which are available by using the bean explicitly. How can you do this
with namespace configuration, since the filter chain is not directly exposed? The order of the filters is always strictly enforced when using the namespace. When the
application context is being created, the filter beans are sorted by the namespace handling
code and the standard Spring Security filters each have an alias in the namespace and a
well-known position.In previous versions, the sorting took place after the
filter instances had been created, during post-processing of the application context. In
version 3.0+ the sorting is now done at the bean metadata level, before the classes have
been instantiated. This has implications for how you add your own filters to the stack
as the entire filter list must be known during the parsing of the
<http> element, so the syntax has changed slightly in
3.0.The filters, aliases and namespace elements/attributes which create
the filters are shown in . The filters are listed in the order
in which they occur in the filter chain.
Standard Filter
Aliases and OrderingAliasFilter ClassNamespace Element or
Attribute
CHANNEL_FILTERChannelProcessingFilterhttp/intercept-url@requires-channel
CONCURRENT_SESSION_FILTERConcurrentSessionFiltersession-management/concurrency-control
SECURITY_CONTEXT_FILTERSecurityContextPersistenceFilterhttp
LOGOUT_FILTER
LogoutFilterhttp/logout
X509_FILTER
X509AuthenticationFilterhttp/x509
PRE_AUTH_FILTER
AstractPreAuthenticatedProcessingFilter
SubclassesN/A CAS_FILTER
CasAuthenticationFilterN/A
FORM_LOGIN_FILTER
UsernamePasswordAuthenticationFilterhttp/form-login
BASIC_AUTH_FILTER
BasicAuthenticationFilterhttp/http-basic
SERVLET_API_SUPPORT_FILTERSecurityContextHolderAwareFilterhttp/@servlet-api-provision
REMEMBER_ME_FILTER
RememberMeAuthenticationFilterhttp/remember-me
ANONYMOUS_FILTER
AnonymousAuthenticationFilterhttp/anonymous
SESSION_MANAGEMENT_FILTERSessionManagementFiltersession-managementEXCEPTION_TRANSLATION_FILTER
ExceptionTranslationFilterhttp
FILTER_SECURITY_INTERCEPTOR
FilterSecurityInterceptorhttp
SWITCH_USER_FILTER
SwitchUserFilterN/A
You can add your own filter to the stack, using the custom-filter element
and one of these names to specify the position your filter should appear at:
]]>
You can also use the after or before
attributes if you want your filter to be inserted before or after another filter in the
stack. The names "FIRST" and "LAST" can be used with the position
attribute to indicate that you want your filter to appear before or after the entire stack,
respectively. Avoiding filter position conflicts If you are inserting a custom filter which may occupy the same position as one of the
standard filters created by the namespace then it's important that you don't include the
namespace versions by mistake. Avoid using the auto-config attribute
and remove any elements which create filters whose functionality you want to replace. Note that you can't replace filters which are created by the use of the
<http> element itself -
SecurityContextPersistenceFilter,
ExceptionTranslationFilter or
FilterSecurityInterceptor. If you're replacing a namespace filter which requires an authentication entry point
(i.e. where the authentication process is triggered by an attempt by an unauthenticated user
to access to a secured resource), you will need to add a custom entry point bean too. Setting a Custom AuthenticationEntryPoint If you aren't using form login, OpenID or basic authentication through the namespace,
you may want to define an authentication filter and entry point using a traditional bean
syntax and link them into the namespace, as we've just seen. The corresponding
AuthenticationEntryPoint can be set using the
entry-point-ref attribute on the <http>
element. The CAS sample application is a good example of the use of custom beans with the
namespace, including this syntax. If you aren't familiar with authentication entry points,
they are discussed in the technical
overview chapter. Method SecurityFrom version 2.0 onwards Spring Security has improved support substantially for adding
security to your service layer methods. It provides support for JSR-250 annotation security as
well as the framework's original @Secured annotation. From 3.0 you can also
make use of new expression-based annotations. You can
apply security to a single bean, using the intercept-methods element to
decorate the bean declaration, or you can secure multiple beans across the entire service
layer using the AspectJ style pointcuts. The <global-method-security> Element This element is used to enable annotation-based security in your application (by
setting the appropriate attributes on the element), and also to group together security
pointcut declarations which will be applied across your entire application context. You
should only declare one <global-method-security> element. The
following declaration would enable support for Spring Security's
@Secured:
]]>
Adding an annotation to a method (on an class or interface) would then limit
the access to that method accordingly. Spring Security's native annotation support defines a
set of attributes for the method. These will be passed to the
AccessDecisionManager for it to make the actual decision:
public interface BankService {
@Secured("IS_AUTHENTICATED_ANONYMOUSLY")
public Account readAccount(Long id);
@Secured("IS_AUTHENTICATED_ANONYMOUSLY")
public Account[] findAccounts();
@Secured("ROLE_TELLER")
public Account post(Account account, double amount);
}
Support
for JSR-250 annotations can be enabled using
]]>
These are standards-based and allow simple role-based constraints to be
applied but do not have the power Spring Security's native annotations.
To use the new expression-based syntax, you would use
]]>and the equivalent Java code would
be
public interface BankService {
@PreAuthorize("isAnonymous()")
public Account readAccount(Long id);
@PreAuthorize("isAnonymous()")
public Account[] findAccounts();
@PreAuthorize("hasAuthority('ROLE_TELLER')")
public Account post(Account account, double amount);
}
Expression-based
annotations are a good choice if you need to define simple rules that go beyond checking the
role names against the user's list of authorities. You can enable more than one type of
annotation in the same application, but you should avoid mixing annotations types in the
same interface or class to avoid confusion.Adding Security Pointcuts using protect-pointcut The use of protect-pointcut is particularly powerful, as it allows
you to apply security to many beans with only a simple declaration. Consider the following
example:
]]>
This will protect all methods on beans declared in the application
context whose classes are in the com.mycompany package and whose class
names end in "Service". Only users with the ROLE_USER role will be able
to invoke these methods. As with URL matching, the most specific matches must come first
in the list of pointcuts, as the first matching expression will be used. The Default AccessDecisionManager This section assumes you have some knowledge of the underlying architecture for
access-control within Spring Security. If you don't you can skip it and come back to it later,
as this section is only really relevant for people who need to do some customization in order
to use more than simple role-based security. When you use a namespace configuration, a default instance of
AccessDecisionManager is automatically registered for you and
will be used for making access decisions for method invocations and web URL access, based on
the access attributes you specify in your intercept-url and
protect-pointcut declarations (and in annotations if you are using
annotation secured methods). The default strategy is to use an AffirmativeBasedAccessDecisionManager with a RoleVoter
and an AuthenticatedVoter. You can find out more about these in the
chapter on authorization.Customizing the AccessDecisionManager If you need to use a more complicated access control strategy then it is easy to set an
alternative for both method and web security. For method security, you do this by setting the
access-decision-manager-ref attribute on
global-method-security to the Id of the appropriate
AccessDecisionManager bean in the application context:
...
]]> The syntax for web security is the same, but on the http element:
...
]]>The Authentication Manager and the Namespace The main interface which provides authentication services in Spring Security is the
AuthenticationManager. This is usually an instance of Spring
Security's ProviderManager class, which you may already be familiar
with if you've used the framework before. If not, it will be covered later, in the technical overview chapter. The bean instance
is registered using the authentication-manager namespace element. You can't
use a custom AuthenticationManager if you are using either HTTP or
method security through the namespace, but this should not be a problem as you have full
control over the AuthenticationProviders that are used. You may want to register additional AuthenticationProvider beans
with the ProviderManager and you can do this using the
<authentication-provider> element with the ref
attribute, where the value of the attribute is the name of the provider bean you want to add.
For example:
...
]]> Another common requirement is that another bean in the context may require a reference to
the AuthenticationManager. You can easily register an alias for
the AuthenticationManager and use this name elsewhere in your
application context.
...
...
]]>