Table of Contents
Acegi Security provides a comprehensive security solution for J2EE-based enterprise software applications. As you will discover as you venture through this reference guide, we have tried to provide you a useful and highly configurable security system.
Security is an ever-moving target, and it's important to pursue a comprehensive, system-wide approach. In security circles we encourage you to adopt "layers of security", so that each layer tries to be as secure as possible in its own right, with successive layers providing additional security. The "tighter" the security of each layer, the more robust and safe your application will be. At the bottom level you'll need to deal with issues such as transport security and system identification, in order to mitigate man-in-the-middle attacks. Next you'll generally utilise firewalls, perhaps with VPNs or IP security to ensure only authorised systems can attempt to connect. In corporate environments you may deploy a DMZ to separate public-facing servers from backend database and application servers. Your operating system will also play a critical part, addressing issues such as running processes as non-privileged users and maximising file system security. An operating system will usually also be configured with its own firewall. Hopefully somewhere along the way you'll be trying to prevent denial of service and brute force attacks against the system. An intrusion detection system will also be especially useful for monitoring and responding to attacks, with such systems able to take protective action such as blocking offending TCP/IP addresses in real-time. Moving to the higher layers, your Java Virtual Machine will hopefully be configured to minimize the permissions granted to different Java types, and then your application will add its own problem domain-specific security configuration. Acegi Security makes this latter area - application security - much easier.
Of course, you will need to properly address all security layers mentioned above, together with managerial factors that encompass every layer. A non-exhaustive list of such managerial factors would include security bulletin monitoring, patching, personnel vetting, audits, change control, engineering management systems, data backup, disaster recovery, performance benchmarking, load monitoring, centralised logging, incident response procedures etc.
With Acegi Security being focused on helping you with the enterprise application security layer, you will find that there are as many different requirements as there are business problem domains. A banking application has different needs from an ecommerce application. An ecommerce application has different needs from a corporate sales force automation tool. These custom requirements make application security interesting, challenging and rewarding.
This reference guide has been largely restructured for the 1.0.0 release of Acegi Security. Please read Part I, Overall Architecture, in its entirety. The remaining parts of the reference guide are structured in a more traditional reference style, designed to be read on an as-required basis.
We hope that you find this reference guide useful, and we welcome your feedback and suggestions.
Finally, welcome to the Acegi Security community.
Like most software, Acegi Security has certain central interfaces, classes and conceptual abstractions that are commonly used throughout the framework. In this part of the reference guide we will introduce Acegi Security, before examining these central elements that are necessary to successfully planning and executing an Acegi Security integration.
Table of Contents
Table of Contents
Acegi Security provides comprehensive security services for J2EE-based enterprise software applications. There is a particular emphasis on supporting projects built using The Spring Framework, which is the leading J2EE solution for enterprise software development. If you're not using Spring for developing enterprise applications, we warmly encourage you to take a closer look at it. Some familiarity with Spring - and in particular dependency injection principles - will help you get up to speed with Acegi Security more easily.
People use Acegi Security for many reasons, but most are drawn to the project after finding the security features of J2EE's Servlet Specification or EJB Specification lack the depth required for typical enterprise application scenarios. Whilst mentioning these standards, it's important to recognise that they are not portable at a WAR or EAR level. Therefore, if you switch server environments, it is typically a lot of work to reconfigure your application's security in the new target environment. Using Acegi Security overcomes these problems, and also brings you dozens of other useful, entirely customisable security features.
As you probably know, security comprises two major operations. The first is known as "authentication", which is the process of establishing a principal is who they claim to be. A "principal" generally means a user, device or some other system which can perform an action in your application. "Authorization" refers to the process of deciding whether a principal is allowed to perform an action in your application. To arrive at the point where an authorization decision is needed, the identity of the principal has already been established by the authentication process. These concepts are common, and not at all specific to Acegi Security.
At an authentication level, Acegi Security supports a wide range of authentication models. Most of these authentication models are either provided by third parties, or are developed by relevant standards bodies such as the Internet Engineering Task Force. In addition, Acegi Security provides its own set of authentication features. Specifically, Acegi Security currently supports authentication with all of these technologies:
HTTP BASIC authentication headers (an IEFT RFC-based standard)
HTTP Digest authentication headers (an IEFT RFC-based standard)
HTTP X.509 client certificate exchange (an IEFT RFC-based standard)
LDAP (a very common approach to cross-platform authentication needs, especially in large environments)
Form-based authentication (for simple user interface needs)
Computer Associates Siteminder
JA-SIG Central Authentication Service (otherwise known as CAS, which is a popular open source single sign on system)
Transparent authentication context propagation for Remote Method Invocation (RMI) and HttpInvoker (a Spring remoting protocol)
Automatic "remember-me" authentication (so you can tick a box to avoid re-authentication for a predetermined period of time)
Anonymous authentication (allowing every call to automatically assume a particular security identity)
Run-as authentication (which is useful if one call should proceed with a different security identity)
Java Authentication and Authorization Service (JAAS)
Container integration with JBoss, Jetty, Resin and Tomcat (so you can still use Container Manager Authentication if desired)
Your own authentication systems (see below)
Many independent software vendors (ISVs) adopt Acegi Security because of this rich choice of authentication models. Doing so allows them to quickly integrate their solutions with whatever their end clients need, without undertaking a lot of engineering or requiring the client to change their environment. If none of the above authentication mechanisms suit your needs, Acegi Security is an open platform and it is quite simple to write your own authentication mechanism. Many corporate users of Acegi Security need to integrate with "legacy" systems that don't follow any particular security standards, and Acegi Security is happy to "play nicely" with such systems.
Sometimes the mere process of authentication isn't enough. Sometimes you need to also differentiate security based on the way a principal is interacting with your application. For example, you might want to ensure requests only arrive over HTTPS, in order to protect passwords from eavesdropping or end users from man-in-the-middle attacks. Or, you might want to ensure that an actual human being is making the requests and not some robot or other automated process. This is especially helpful to protect password recovery processes from brute force attacks, or simply to make it harder for people to duplicate your application's key content. To help you achieve these goals, Acegi Security fully supports automatic "channel security", together with JCaptcha integration for human user detection.
Irrespective of how authentication was undertaken, Acegi Security provides a deep set of authorization capabilities. There are three main areas of interest in respect of authorization, these being authorizing web requests, authorizing methods can be invoked, and authorizing access to individual domain object instances. To help you understand the differences, consider the authorization capabilities found in the Servlet Specification web pattern security, EJB Container Managed Security and file system security respectively. Acegi Security provides deep capabilities in all of these important areas, which we'll explore later in this reference guide.
Acegi Security began in late 2003, when a question was posed on the Spring Developers' mailing list asking whether there had been any consideration given to a Spring-based security implementation. At the time the Spring community was relatively small (especially by today's size!), and indeed Spring itself had only existed as a SourceForge project from early 2003. The response to the question was that it was a worthwhile area, although a lack of time currently prevented its exploration.
With that in mind, a simple security implementation was built and not released. A few weeks later another member of the Spring community inquired about security, and at the time this code was offered to them. Several other requests followed, and by January 2004 around twenty people were using the code. These pioneering users were joined by others who suggested a SourceForge project was in order, which was duly established in March 2004.
In those early days, the project didn't have any of its own authentication modules. Container Managed Security was relied upon for the authentication process, with Acegi Security instead focusing on authorization. This was suitable at first, but as more and more users requested additional container support, the fundamental limitation of container-specific authentication realm interfaces was experienced. There was also a related issue of adding new JARs to the container's classpath, which was a common source of end user confusion and misconfiguration.
Acegi Security-specific authentication services were subsequently introduced. Around a year later, the Acegi Security became an official Spring Framework subproject. The 1.0.0 final release was published in May 2006 - after more than two and a half years of active use in numerous production software projects and many hundreds of improvements and community contributions.
Today Acegi Security enjoys a strong and active open source community. There are thousands of messages about Acegi Security on the support forums. Fourteen developers work on the code itself, with an active community who also regularly share patches and support their peers.
It is useful to understand how Acegi Security release numbers
work, as it will help you identify the effort (or lack thereof)
involved in migrating to future releases of the project. Officially,
we use the Apache Portable Runtime Project versioning guidelines,
which can be viewed at
http://apr.apache.org/versioning.html. We quote the
introduction contained on that page for your convenience:
“Versions are denoted using a standard triplet of integers: MAJOR.MINOR.PATCH. The basic intent is that MAJOR versions are incompatible, large-scale upgrades of the API. MINOR versions retain source and binary compatibility with older minor versions, and changes in the PATCH level are perfectly compatible, forwards and backwards.”
Acegi Security is written to execute within a standard Java 1.3 Runtime Environment. It also supports Java 5.0, although the Java types which are specific to this release are packaged in a separate package with the suffix "tiger" in their JAR filename. As Acegi Security aims to operate in a self-contained manner, there is no need to place any special configuration files into your Java Runtime Environment. In particular, there is no need to configure a special Java Authentication and Authorization Service (JAAS) policy file or place Acegi Security into common classpath locations.
Similarly, if you are using an EJB Container or Servlet Container there is no need to put any special configuration files anywhere, nor include Acegi Security in a server classloader.
This above design offers maximum deployment time flexibility, as you can simply copy your target artifact (be it a JAR, WAR or EAR) from one system to another and it will immediately work.
Let's explore some of the most important shared components in Acegi Security. Components are considered "shared" if they are central to the framework and the framework cannot operate without them. These Java types represent the building blocks of the remaining system, so it's important to understand that they're there, even if you don't need to directly interact with them.
The most fundamental object is
SecurityContextHolder. This is where we store
details of the present security context of the application, which
includes details of the principal currently using the application. By
default the SecurityContextHolder uses a
ThreadLocal to store these details, which means
that the security context is always available to methods in the same
thread of execution, even if the security context is not explicitly
passed around as an argument to those methods. Using a
ThreadLocal in this way is quite safe if care is
taken to clear the thread after the present principal's request is
processed. Of course, Acegi Security takes care of this for you
automatically so there is no need to worry about it.
Some applications aren't entirely suitable for using a
ThreadLocal, because of the specific way they work
with threads. For example, a Swing client might want all threads in a
Java Virtual Machine to use the same security context. For this
situation you would use the
SecurityContextHolder.MODE_GLOBAL. Other
applications might want to have threads spawned by the secure thread
also assume the same security identity. This is achieved by using
SecurityContextHolder.MODE_INHERITABLETHREADLOCAL.
You can change the mode from the default
SecurityContextHolder.MODE_THREADLOCAL in two ways.
The first is to set a system property. Alternatively, call a static
method on SecurityContextHolder. Most applications
won't need to change from the default, but if you do, take a look at
the JavaDocs for SecurityContextHolder to learn
more.
Inside the SecurityContextHolder we store
details of the principal currently interacting with the application.
Acegi Security uses an Authentication object to
represent this information. Whilst you won't normally need to create
an Authentication object yourself, it is fairly
common for users to query the Authentication
object. You can use the following code block - from anywhere in your
application - to do this:
Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (obj instanceof UserDetails) {
String username = ((UserDetails)obj).getUsername();
} else {
String username = obj.toString();
}The above code introduces a number of interesting relationships
and key objects. First, you will notice that there is an intermediate
object between SecurityContextHolder and
Authentication. The
SecurityContextHolder.getContext() method is
actually returning a SecurityContext. Acegi
Security uses a few different SecurityContext
implementations, such as if we need to store special information
related to a request that is not principal-specific. A good example of
this is our JCaptcha integration, which needs to know whether the
current request came from a human user or not. Because such a decision
has nothing at all to do with the principal the request may or may not
be authenticated as, we store it in the
SecurityContext.
Another item to note from the above code fragment is that you
can obtain a principal from the Authentication
object. The principal is just an Object. Most of
the time this can be cast into a UserDetails
object. UserDetails is a central interface in Acegi
Security. It represents a principal, but in an extensible and
application-specific way. Think of UserDetails as
the adapter between your own user database and what Acegi Security
needs inside the SecurityContextHolder. Being a
representation of something from your own user database, quite often
you will cast the UserDetails to the original
object that your application provided, so you can call
business-specific methods (like getEmail(),
getEmployeeNumber() and so on).
By now you're probably wondering, so when do I provide a
UserDetails object? How do I do that? I thought you
said this thing was declarative and I didn't need to write any Java
code - what gives? The short answer is that there is a special
interface called UserDetailsService. The only
method on this interface accepts a String-based
username argument and returns a UserDetails. Most
authentication providers that ship with Acegi Security delegate to a
UserDetailsService as part of the authentication
process. The UserDetailsService is used to build
the Authentication object that is stored in the
SecurityContextHolder. The good news is that we
provide a number of UserDetailsService
implementations, including one that uses an in-memory map and another
that uses JDBC. Most users tend to write their own, though, with such
implementations often simply sitting on top of an existing Data Access
Object (DAO) that represents their employees, customers, or other
users of the enterprise application. Remember the advantage that
whatever your UserDetailsService returns can always be obtained from
the SecurityContextHolder, as per the above code
fragment.
Besides the principal, another important method provided by
Authentication is
getAuthorities(). This method provides an array of
GrantedAuthority objects. A
GrantedAuthority is, not surprisingly, an authority
that is granted to the principal. Such authorities are usually
"roles", such as ROLE_ADMINISTRATOR or
ROLE_HR_SUPERVISOR. These roles are later on
configured for web authorization, method authorization and domain
object authorization. Other parts of Acegi Security are capable of
interpreting these authorities, and expect them to be present.
GrantedAuthority objects are usually loaded by
the UserDetailsService.
Usually the GrantedAuthority objects are
application-wide permissions. They are not specific to a given domain
object. Thus, you wouldn't likely have a
GrantedAuthority to represent a permission to
Employee object number 54, because if there are
thousands of such authorities you would quickly run out of memory (or,
at the very least, cause the application to take a long time to
authenticate a user). Of course, Acegi Security is expressly designed
to handle this common requirement, but you'd instead use the project's
domain object security capabilities for this purpose.
Last but not least, sometimes you will need to store the
SecurityContext between HTTP requests. Other times
the principal will re-authenticate on every request, although most of
the time it will be stored. The
HttpSessionContextIntegrationFilter is responsible
for storing a SecurityContext between HTTP
requests. As suggested by the name of the class, the
HttpSession is used to store this information. You
should never interact directly with the HttpSession
for security purposes. There is simply no justification for doing so -
always use the SecurityContextHolder
instead.
Just to recap, the major building blocks of Acegi Security are:
SecurityContextHolder, to provide any
type access to the SecurityContext.
SecurityContext, to hold the
Authentication and possibly request-specific
security information.
HttpSessionContextIntegrationFilter, to
store the SecurityContext in the
HttpSession between web requests.
Authentication, to represent the
principal in an Acegi Security-specific manner.
GrantedAuthority, to reflect the
application-wide permissions granted to a principal.
UserDetails, to provide the necessary
information to build an Authentication object from your
application's DAOs.
UserDetailsService, to create a
UserDetails when passed in a
String-based username (or certificate ID or
alike).
Now that you've gained an understanding of these repeatedly-used components, let's take a closer look at the process of authentication.
As mentioned in the beginning of this reference guide, Acegi Security can participate in many different authentication environments. Whilst we recommend people use Acegi Security for authentication and not integrate with existing Container Managed Authentication, it is nevertheless supported - as is integrating with your own proprietary authentication system. Let's first explore authentication from the perspective of Acegi Security managing web security entirely on its own, which is illustrative of the most complex and most common situation.
Consider a typical web application's authentication process:
You visit the home page, and click on a link.
A request goes to the server, and the server decides that you've asked for a protected resource.
As you're not presently authenticated, the server sends back a response indicating that you must authenticate. The response will either be an HTTP response code, or a redirect to a particular web page.
Depending on the authentication mechanism, your browser will either redirect to the specific web page so that you can fill out the form, or the browser will somehow retrieve your identity (eg a BASIC authentication dialogue box, a cookie, a X509 certificate etc).
The browser will send back a response to the server. This will either be an HTTP POST containing the contents of the form that you filled out, or an HTTP header containing your authentication details.
Next the server will decide whether or not the presented credentials are valid. If they're valid, the next step will happen. If they're invalid, usually your browser will be asked to try again (so you return to step two above).
The original request that you made to cause the authentication process will be retried. Hopefully you've authenticated with sufficient granted authorities to access the protected resource. If you have sufficient access, the request will be successful. Otherwise, you'll receive back an HTTP error code 403, which means "forbidden".
Acegi Security has distinct classes responsible for most of the
steps described above. The main participants (in the order that they
are used) are the ExceptionTranslationFilter, an
AuthenticationEntryPoint, an authentication
mechanism, and an AuthenticationProvider.
ExceptionTranslationFilter is an Acegi
Security filter that has responsibility for detecting any Acegi
Security exceptions that are thrown. Such exceptions will generally be
thrown by an AbstractSecurityInterceptor, which is
the main provider of authorization services. We will discuss
AbstractSecurityInterceptor in the next section,
but for now we just need to know that it produces Java exceptions and
knows nothing about HTTP or how to go about authenticating a
principal. Instead the ExceptionTranslationFilter
offers this service, with specific responsibility for either returning
error code 403 (if the principal has been authenticated and therefore
simply lacks sufficient access - as per step seven above), or
launching an AuthenticationEntryPoint (if the
principal has not been authenticated and therefore we need to go
commence step three).
The AuthenticationEntryPoint is responsible
for step three in the above list. As you can imagine, each web
application will have a default authentication strategy (well, this
can be configured like nearly everything else in Acegi Security, but
let's keep it simple for now). Each major authentication system will
have its own AuthenticationEntryPoint
implementation, which takes actions such as described in step
three.
After your browser decides to submit your authentication
credentials (either as an HTTP form post or HTTP header) there needs to
be something on the server that "collects" these authentication
details. By now we're at step six in the above list. In Acegi Security
we have a special name for the function of collecting authentication
details from a user agent (usually a web browser), and that name is
"authentication mechanism". After the authentication details are
collected from the user agent, an "Authentication
request" object is built and then presented to an
AuthenticationProvider.
The last played in the Acegi Security authentication process is
an AuthenticationProvider. Quite simply, it is
responsible for taking an Authentication request
object and deciding whether or not it is valid. The provider will
either throw an exception or return a fully populated
Authentication object. Remember our good friends,
UserDetails and
UserDetailsService? If not, head back to the
previous section and refresh your memory. Most
AuthenticationProviders will ask a
UserDetailsService to provide a
UserDetails object. As mentioned earlier, most
application will provide their own
UserDetailsService, although some will be able to
use the JDBC or in-memory implementation that ships with Acegi
Security. The resultant UserDetails object - and
particularly the GrantedAuthority[]s contained
within the UserDetails object - will be used when
building the fully populated Authentication
object.
After the authentication mechanism receives back the
fully-populated Authentication object, it will deem
the request valid, put the Authentication into the
SecurityContextHolder, and cause the original
request to be retried (step seven above). If, on the other hand, the
AuthenticationProvider rejected the request, the
authentication mechanism will ask the user agent to retry (step two
above).
Whilst this describes the typical authentication workflow, the
good news is that Acegi Security doesn't mind how you put an
Authentication inside the
SecurityContextHolder. The only critical
requirement is that the SecurityContextHolder
contains an Authentication that represents a
principal before the AbstractSecurityInterceptor
needs to authorize a request.
You can (and many users do) write their own filters or MVC controllers to provide interoperability with authentication systems that are not based on Acegi Security. For example, you might be using Container Managed Authentication which makes the current user available from a ThreadLocal or JNDI location. Or you might work for a company that has a legacy proprietary authentication system, which is a corporate "standard" over which you have little control. In such situations it's quite easy to get Acegi Security to work, and still provide authorization capabilities. All you need to do is write a filter (or equivalent) that reads the third-party user information from a location, build an Acegi Security-specific Authentication object, and put it onto the SecurityContextHolder. It's quite easy to do this, and it is a fully-supported integration approach.
If you're familiar with AOP, you'd be aware there are different types of advice available: before, after, throws and around. An around advice is very useful, because an advisor can elect whether or not to proceed with a method invocation, whether or not to modify the response, and whether or not to throw an exception. Acegi Security provides an around advice for method invocations as well as web requests. We achieve an around advice for method invocations using AOP Alliance, and we achieve an around advice for web requests using a standard Filter.
For those not familiar with AOP, the key point to understand is that Acegi Security can help you protect method invocations as well as web requests. Most people are interested in securing method invocations on their services layer. This is because the services layer is where most business logic resides in current-generation J2EE applications (for clarification, the author disapproves of this design and instead advocates properly encapsulated domain objects together with the DTO, assembly, facade and transparent persistence patterns, but as anemic domain objects is the present mainstream approach, we'll talk about it here). If you just need to secure method invocations to the services layer, using the Spring's standard AOP platform (otherwise known as AOP Alliance) will be adequate. If you need to secure domain objects directly, you will likely find that AspectJ is worth considering.
You can elect to perform method authorization using AspectJ or AOP Alliance, or you can elect to perform web request authorization using filters. You can use zero, one, two or three of these approaches together. The mainstream usage is to perform some web request authorization, coupled with some AOP Alliance method invocation authorization on the services layer.
Acegi Security uses the term "secure object" to refer to any
object that can have security applied to it. Each secure object
supported by Acegi Security has its own class, which is a subclass of
AbstractSecurityInterceptor. Importantly, by the
time the AbstractSecurityInterceptor is run, the
SecurityContextHolder will contain a valid
Authentication if the principal has been
authenticated.
The AbstractSecurityInterceptor provides a
consistent workflow for handling secure object requests. This workflow
includes looking up the "configuration attributes" associated with the
present request. A "configuration attribute" can be thought of as a
String that has special meaning to the classes used by
AbstractSecurityInterceptor. They're normally
configured against your AbstractSecurityInterceptor
using XML. Anyway, the AbstractSecurityInterceptor will ask an
AccessDecisionManager "here's the configuration
attributes, here's the current Authentication
object, and here's details of the current request - is this particular
principal allowed to perform this particular operation?".
Assuming AccessDecisionManager decides to
allow the request, the AbstractSecurityInterceptor
will normally just proceed with the request. Having said that, on rare
occasions users may want to replace the
Authentication inside the
SecurityContext with a different
Authentication, which is handled by the
AccessDecisionManager calling a
RunAsManager. This might be useful in reasonably
unusual situations, such as if a services layer method needs to call a
remote system and present a different identity. Because Acegi Security
automatically propagates security identity from one server to another
(assuming you're using a properly-configured RMI or HttpInvoker
remoting protocol client), this may be useful.
Following the secure object proceeding and then returning -
which may mean a method invocation completing or a filter chain
proceeding - the AbstractSecurityInterceptor gets
one final chance to handle the invocation. At this stage the
AbstractSecurityInterceptor is interested in
possibly modifying the return object. We might want this to happen
because an authorization decision couldn't be made "on the way in" to
a secure object invocation. Being highly pluggable,
AbstractSecurityInterceptor will pass control to an
AfterInvocationManager to actually modify the
object if needed. This class even can entirely replace the object, or
throw an exception, or not change it in any way.
Because AbstractSecurityInterceptor is the
central template class, it seems fitting that the first figure should
be devoted to it.

Figure 1: The key "secure object" model
Only developers contemplating an entirely new way of
intercepting and authorizing requests would need to use secure objects
directly. For example, it would be possible to build a new secure
object to secure calls to a messaging system. Anything that requires
security and also provides a way of intercepting a call (like the AOP
around advice semantics) is capable of being made into a secure
object. Having said that, most Spring applications will simply use the
three currently supported secure object types (AOP Alliance
MethodInvocation, AspectJ
JoinPoint and web request
FilterInterceptor) with complete
transparency.
Congratulations! You have enough of a high-level picture of Acegi Security to embark on your project. We've explored the shared components, how authentication works, and reviewed the common authorization concept of a "secure object". Everything that follows in this reference guide may or may not apply to your particular needs, and can be read in any order.
Table of Contents
This chapter introduces some of the supplementary and supporting infrastructure used by Acegi Security. If a capability is not directly related to security, yet included in the Acegi Security project, we will discuss it in this chapter.
Acegi Security supports localization of exception messages that end users are likely to see. If your application is designed for English users, you don't need to do anything as by default all Acegi Security messages are in English. If you need to support other locales, everything you need to know is contained in this section.
All exception messages can be localized, including messages related to authentication failures and access being denied (authorization failures). Exceptions and logging that is focused on developers or system deployers (including incorrect attributes, interface contract violations, using incorrect constructors, startup time validation, debug-level logging) etc are not localized and instead are hard-coded in English within Acegi Security's code.
Shipping in the acegi-security-xx.jar you
will find an org.acegisecurity package that in turn
contains a messages.properties file. This should be
referred to by your ApplicationContext, as Acegi
Security classes implement Spring's
MessageSourceAware interface and expect the message
resolver to be dependency injected at application context startup
time. Usually all you need to do is register a bean inside your
application context to refer to the messages. An example is shown
below:
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename"><value>org/acegisecurity/messages</value></property> </bean>
The messages.properties is named in
accordance with standard resource bundles and represents the default
language supported by Acegi Securtiy messages. This default file is in
English. If you do not register a message source, Acegi Security will
still work correctly and fallback to hard-coded English versions of
the messages.
If you wish to customize the
messages.properties file, or support other
languages, you should copy the file, rename it accordingly, and
register it inside the above bean definition. There are not a large
number of message keys inside this file, so localization should not be
considered a major initiative. If you do perform localization of this
file, please consider sharing your work with the community by logging
a JIRA task and attaching your appropriately-named localized version
of messages.properties.
Rounding out the discussion on localization is the Spring
ThreadLocal known as
org.springframework.context.i18n.LocaleContextHolder.
You should set the LocaleContextHolder to represent
the preferred Locale of each user. Acegi Security
will attempt to locate a message from the message source using the
Locale obtained from this
ThreadLocal. Please refer to Spring documentation
for further details on using LocaleContextHolder
and the helper classes that can automatically set it for you (eg
AcceptHeaderLocaleResolver,
CookieLocaleResolver,
FixedLocaleResolver,
SessionLocaleResolver etc)
Acegi Security uses many filters, as referred to throughout the
remainder of this reference guide. You have a choice in how these
filters are added to your web application, in that you can use either
FilterToBeanProxy or
FilterChainProxy. We'll look at both below.
Most filters are configured using the
FilterToBeanProxy. An example configuration from
web.xml follows:
<filter>
<filter-name>Acegi HTTP Request Security Filter</filter-name>
<filter-class>org.acegisecurity.util.FilterToBeanProxy</filter-class>
<init-param>
<param-name>targetClass</param-name>
<param-value>org.acegisecurity.ClassThatImplementsFilter</param-value>
</init-param>
</filter>Notice that the filter in web.xml is actually
a FilterToBeanProxy, and not the filter that will
actually implement the logic of the filter. What
FilterToBeanProxy does is delegate the
Filter's methods through to a bean which is
obtained from the Spring application context. This enables the bean to
benefit from the Spring application context lifecycle support and
configuration flexibility. The bean must implement
javax.servlet.Filter.
The FilterToBeanProxy only requires a single
initialization parameter, targetClass or
targetBean. The targetClass
parameter locates the first object in the application context of the
specified class, whilst targetBean locates the
object by bean name. Like standard Spring web applications, the
FilterToBeanProxy accesses the application context
via
WebApplicationContextUtils.getWebApplicationContext(ServletContext),
so you should configure a ContextLoaderListener in
web.xml.
There is a lifecycle issue to consider when hosting
Filters in an IoC container instead of a servlet
container. Specifically, which container should be responsible for
calling the Filter's "startup" and "shutdown"
methods? It is noted that the order of initialization and destruction
of a Filter can vary by servlet container, and this
can cause problems if one Filter depends on
configuration settings established by an earlier initialized
Filter. The Spring IoC container on the other hand
has more comprehensive lifecycle/IoC interfaces (such as
InitializingBean,
DisposableBean, BeanNameAware,
ApplicationContextAware and many others) as well as
a well-understood interface contract, predictable method invocation
ordering, autowiring support, and even options to avoid implementing
Spring interfaces (eg the destroy-method attribute
in Spring XML). For this reason we recommend the use of Spring
lifecycle services instead of servlet container lifecycle services
wherever possible. By default FilterToBeanProxy
will not delegate init(FilterConfig) and
destroy() methods through to the proxied bean. If
you do require such invocations to be delegated, set the
lifecycle initialization parameter to
servlet-container-managed.
Rather than using FilterToBeanProxy, we
strongly recommend to use FilterChainProxy instead.
Whilst FilterToBeanProxy is a very useful class,
the problem is that the lines of code required for
<filter> and
<filter-mapping> entries in
web.xml explodes when using more than a few
filters. To overcome this issue, Acegi Security provides a
FilterChainProxy class. It is wired using a
FilterToBeanProxy (just like in the example above),
but the target class is
org.acegisecurity.util.FilterChainProxy. The filter
chain is then declared in the application context, using code such as
this:
<bean id="filterChainProxy" class="org.acegisecurity.util.FilterChainProxy">
<property name="filterInvocationDefinitionSource">
<value>
CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
PATTERN_TYPE_APACHE_ANT
/webServices/**=httpSessionContextIntegrationFilterWithASCFalse,basicProcessingFilter,exceptionTranslationFilter,filterSecurityInterceptor
/**=httpSessionContextIntegrationFilterWithASCTrue,authenticationProcessingFilter,exceptionTranslationFilter,filterSecurityInterceptor
</value>
</property>
</bean> You may notice similarities with the way
FilterSecurityInterceptor is declared. Both regular
expressions and Ant Paths are supported, and the most specific URIs
appear first. At runtime the FilterChainProxy will
locate the first URI pattern that matches the current web request.
Each of the corresponding configuration attributes represent the name
of a bean defined in the application context. The filters will then be
invoked in the order they are specified, with standard
FilterChain behaviour being respected (a
Filter can elect not to proceed with the chain if
it wishes to end processing).
As you can see, FilterChainProxy requires the
duplication of filter names for different request patterns (in the
above example, exceptionTranslationFilter and
filterSecurityInterceptor are duplicated). This
design decision was made to enable FilterChainProxy
to specify different Filter invocation orders for
different URI patterns, and also to improve both the expressiveness
(in terms of regular expressions, Ant Paths, and any custom
FilterInvocationDefinitionSource implementations)
and clarity of which Filters should be
invoked.
You may have noticed we have declared two
HttpSessionContextIntegrationFilters in the filter
chain (ASC is short for
allowSessionCreation, a property of
HttpSessionContextIntegrationFilter). As web
services will never present a jsessionid on future
requests, creating HttpSessions for such user
agents would be wasteful. If you had a high-volume application which
required maximum scalability, we recommend you use the approach shown
above. For smaller applications, using a single
HttpSessionContextIntegrationFilter (with its
default allowSessionCreation as
true) would likely be sufficient.
In relation to lifecycle issues, the
FilterChainProxy will always delegate
init(FilterConfig) and destroy()
methods through to the underlaying Filters if such
methods are called against FilterChainProxy itself.
In this case, FilterChainProxy guarantees to only
initialize and destroy each Filter once,
irrespective of how many times it is declared by the
FilterInvocationDefinitionSource. You control the
overall choice as to whether these methods are called or not via the
lifecycle initialization parameter of the
FilterToBeanProxy that proxies
FilterChainProxy. As discussed above, by default
any servlet container lifecycle invocations are not delegated through
to FilterChainProxy.
You can also omit a URI pattern from the filter chain by using
the token #NONE# on the right-hand side of the
<URI Pattern> = <Filter Chain> expression. For example, using
the example above, if you wanted to exclude the /webservices
location completely, you would modify the corresponding line in the bean declaration to be
/webServices/**=#NONE#
Note that anything matching this path will then have no authentication or authorization services applied and will be freely accessible.
The order that filters are defined in web.xml
is very important. Irrespective of which filters you are actually
using, the order of the <filter-mapping>s
should be as follows:
ChannelProcessingFilter, because it might
need to redirect to a different protocol
ConcurrentSessionFilter, because it
doesn't use any SecurityContextHolder
functionality but needs to update the
SessionRegistry to reflect ongoing requests
from the principal
HttpSessionContextIntegrationFilter, so a
SecurityContext can be setup in the
SecurityContextHolder at the beginning of a web
request, and any changes to the SecurityContext
can be copied to the HttpSession when the web
request ends (ready for use with the next web request)
Authentication processing mechanisms -
AuthenticationProcessingFilter,
CasProcessingFilter,
BasicProcessingFilter, HttpRequestIntegrationFilter,
JbossIntegrationFilter etc - so that the
SecurityContextHolder can be modified to
contain a valid Authentication request
token
The
SecurityContextHolderAwareRequestFilter, if you
are using it to install an Acegi Security aware
HttpServletRequestWrapper into your servlet
container
RememberMeProcessingFilter, so that if no
earlier authentication processing mechanism updated the
SecurityContextHolder, and the request presents
a cookie that enables remember-me services to take place, a
suitable remembered
object will
be put thereAuthentication
AnonymousProcessingFilter, so that if no
earlier authentication processing mechanism updated the
SecurityContextHolder, an anonymous
Authentication object will be put there
ExceptionTranslationFilter, to catch any
Acegi Security exceptions so that either an HTTP error response can
be returned or an appropriate
AuthenticationEntryPoint can be launched
FilterSecurityInterceptor, to protect web
URIs
All of the above filters use
FilterToBeanProxy or
FilterChainProxy. It is recommended that a single
FilterToBeanProxy proxy through to a single
FilterChainProxy for each application, with that
FilterChainProxy defining all of Acegi Security
Filters.
If you're using SiteMesh, ensure Acegi Security filters execute
before the SiteMesh filters are called. This enables the
SecurityContextHolder to be populated in time for
use by SiteMesh decorators
Table of Contents
In addition to coordinating the authentication and authorization
requirements of your application, Acegi Security is also able to
ensure unauthenticated web requests have certain properties. These
properties may include being of a particular transport type, having a
particular HttpSession attribute set and so on. The
most common requirement is for your web requests to be received using
a particular transport protocol, such as HTTPS.
An important issue in considering transport security is that of
session hijacking. Your web container manages a
HttpSession by reference to a
jsessionid that is sent to user agents either via a
cookie or URL rewriting. If the jsessionid is ever
sent over HTTP, there is a possibility that session identifier can be
intercepted and used to impersonate the user after they complete the
authentication process. This is because most web containers maintain
the same session identifier for a given user, even after they switch
from HTTP to HTTPS pages.
If session hijacking is considered too significant a risk for
your particular application, the only option is to use HTTPS for every
request. This means the jsessionid is never sent
across an insecure channel. You will need to ensure your
web.xml-defined
<welcome-file> points to an HTTPS location,
and the application never directs the user to an HTTP location. Acegi
Security provides a solution to assist with the latter.
To utilise Acegi Security's channel security services, add the
following lines to web.xml:
<filter>
<filter-name>Acegi Channel Processing Filter</filter-name>
<filter-class>org.acegisecurity.util.FilterToBeanProxy</filter-class>
<init-param>
<param-name>targetClass</param-name>
<param-value>org.acegisecurity.securechannel.ChannelProcessingFilter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Acegi Channel Processing Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
As usual when running FilterToBeanProxy, you
will also need to configure the filter in your application
context:
<bean id="channelProcessingFilter" class="org.acegisecurity.securechannel.ChannelProcessingFilter">
<property name="channelDecisionManager"><ref bean="channelDecisionManager"/></property>
<property name="filterInvocationDefinitionSource">
<value>
CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
\A/secure/.*\Z=REQUIRES_SECURE_CHANNEL
\A/acegilogin.jsp.*\Z=REQUIRES_SECURE_CHANNEL
\A/j_acegi_security_check.*\Z=REQUIRES_SECURE_CHANNEL
\A.*\Z=REQUIRES_INSECURE_CHANNEL
</value>
</property>
</bean>
<bean id="channelDecisionManager" class="org.acegisecurity.securechannel.ChannelDecisionManagerImpl">
<property name="channelProcessors">
<list>
<ref bean="secureChannelProcessor"/>
<ref bean="insecureChannelProcessor"/>
</list>
</property>
</bean>
<bean id="secureChannelProcessor" class="org.acegisecurity.securechannel.SecureChannelProcessor"/>
<bean id="insecureChannelProcessor" class="org.acegisecurity.securechannel.InsecureChannelProcessor"/>
Like FilterSecurityInterceptor, Apache Ant
style paths are also supported by the
ChannelProcessingFilter.
The ChannelProcessingFilter operates by
filtering all web requests and determining the configuration
attributes that apply. It then delegates to the
ChannelDecisionManager. The default implementation,
ChannelDecisionManagerImpl, should suffice in most
cases. It simply delegates through the list of configured
ChannelProcessor instances. A
ChannelProcessor will review the request, and if it
is unhappy with the request (eg it was received across the incorrect
transport protocol), it will perform a redirect, throw an exception or
take whatever other action is appropriate.
Included with Acegi Security are two concrete
ChannelProcessor implementations:
SecureChannelProcessor ensures requests with a
configuration attribute of REQUIRES_SECURE_CHANNEL
are received over HTTPS, whilst
InsecureChannelProcessor ensures requests with a
configuration attribute of
REQUIRES_INSECURE_CHANNEL are received over HTTP.
Both implementations delegate to a
ChannelEntryPoint if the required transport
protocol is not used. The two ChannelEntryPoint
implementations included with Acegi Security simply redirect the
request to HTTP and HTTPS as appropriate. Appropriate defaults are
assigned to the ChannelProcessor implementations
for the configuration attribute keywords they respond to and the
ChannelEntryPoint they delegate to, although you
have the ability to override these using the application
context.
Note that the redirections are absolute (eg
http://www.company.com:8080/app/page), not relative
(eg /app/page). During testing it was discovered
that Internet Explorer 6 Service Pack 1 has a bug whereby it does not
respond correctly to a redirection instruction which also changes the
port to use. Accordingly, absolute URLs are used in conjunction with
bug detection logic in the PortResolverImpl that is
wired up by default to many Acegi Security beans. Please refer to the
JavaDocs for PortResolverImpl for further
details.
You should note that using a secure channel is recommended if
usernames and passwords are to be kept secure during the login
process. If you do decide to use
ChannelProcessingFilter with form-based login,
please ensure that your login page is set to
REQUIRES_SECURE_CHANNEL, and that the
AuthenticationProcessingFilterEntryPoint.forceHttps
property is true.
Once configured, using the channel security filter is very easy.
Simply request pages without regard to the protocol (ie HTTP or HTTPS)
or port (eg 80, 8080, 443, 8443 etc). Obviously you'll still need a
way of making the initial request (probably via the
web.xml <welcome-file> or
a well-known home page URL), but once this is done the filter will
perform redirects as defined by your application context.
You can also add your own ChannelProcessor
implementations to the ChannelDecisionManagerImpl.
For example, you might set a HttpSession attribute
when a human user is detected via a "enter the contents of this
graphic" procedure. Your ChannelProcessor would
respond to say REQUIRES_HUMAN_USER configuration
attributes and redirect to an appropriate entry point to start the
human user validation process if the HttpSession
attribute is not currently set.
To decide whether a security check belongs in a
ChannelProcessor or an
AccessDecisionVoter, remember that the former is
designed to handle unauthenticated requests, whilst the latter is
designed to handle authenticated requests. The latter therefore has
access to the granted authorities of the authenticated principal. In
addition, problems detected by a ChannelProcessor
will generally cause an HTTP/HTTPS redirection so its requirements can
be met, whilst problems detected by an
AccessDecisionVoter will ultimately result in an
AccessDeniedException (depending on the governing
AccessDecisionManager).
Table of Contents
Acegi Security comes bundled with several JSP tag libraries that
eases JSP writing. The tag libraries are known as
authz and provide a range of different
services.
All taglib classes are included in the core
acegi-security-xx.jar file, with the
authz.tld located in the JAR's
META-INF directory. This means for JSP 1.2+ web
containers you can simply include the JAR in the WAR's
WEB-INF/lib directory and it will be available. If
you're using a JSP 1.1 container, you'll need to declare the JSP
taglib in your web.xml file, and include
authz.tld in the WEB-INF/lib
directory. The following fragment is added to
web.xml:
<taglib> <taglib-uri>http://acegisecurity.org/authz</taglib-uri> <taglib-location>/WEB-INF/authz.tld</taglib-location> </taglib>
In this part of the reference guide we will examine individual
authentication mechanisms and their corresponding
AuthenticationProviders. We'll also look at how to
configure authentication more generally, including if you have several
authentication approaches that need to be chained together.
Table of Contents
Table of Contents
If you're using Acegi Security-provided authentication
approaches, you'll usually need to configure a web filter, together
with an AuthenticationProvider and
AuthenticationEntryPoint. In this section we are
going to explore an example application that needs to support both
form-based authentication (ie so a nice HTML page is presented to a
user for them to login) plus BASIC authentication (ie so a web service
or similar can access protected resources).
In the web.xml, this application will need a single Acegi Security filter in order to use the FilterChainProxy. Nearly every Acegi Security application will have such an entry, and it looks like this:
<filter>
<filter-name>Acegi Filter Chain Proxy</filter-name>
<filter-class>org.acegisecurity.util.FilterToBeanProxy</filter-class>
<init-param>
<param-name>targetClass</param-name>
<param-value>org.acegisecurity.util.FilterChainProxy</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Acegi Filter Chain Proxy</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>The above declarations will cause every web request to be passed
through to Acegi Security's FilterChainProxy. As explained in the
filters section of this reference guide, the FilterChainProxy is a
generally-useful class that enables web requests to be passed to
different filters based on the URL patterns. Those delegated filters
are managed inside the application context, so they can benefit from
dependency injection. Let's have a look at what the FilterChainProxy
bean definition would look like inside your application
context:
<bean id="filterChainProxy" class="org.acegisecurity.util.FilterChainProxy">
<property name="filterInvocationDefinitionSource">
<value>
CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
PATTERN_TYPE_APACHE_ANT
/**=httpSessionContextIntegrationFilter,logoutFilter,authenticationProcessingFilter,basicProcessingFilter,securityContextHolderAwareRequestFilter,rememberMeProcessingFilter,anonymousProcessingFilter,exceptionTranslationFilter,filterInvocationInterceptor,switchUserProcessingFilter
</value>
</property>
</bean>Internally Acegi Security will use a
PropertyEditor to convert the string presented in
the above XML fragment into a
FilterInvocationDefinitionSource object. What's
important to note at this stage is that a series of filters will be
run - in the order specified by the declaration - and each of those
filters are actually the <bean id> of another
bean inside the application context. So, in our case some extra beans
will also appear in the application context, and they'll be named
httpSessionContextIntegrationFilter,
logoutFilter and so on. The order that the filters
should appear is discussed in the filters section of the reference
guide - although they are correct in the above example.
In our example we have the
AuthenticationProcessingFilter and
BasicProcessingFilter being used. These are the
"authentication mechanisms" that respond to form-based authentication
and BASIC HTTP header-based authentication respectively (we discussed
the role of authentication mechanisms earlier in this reference
guide). If you weren't using form or BASIC authentication, neither of
these beans would be defined. You'd instead define filters applicable
to your desired authentication environment, such as
DigestProcessingFilter or
CasProcessingFilter. Refer to the individual
chapters of this part of the reference guide to learn how to configure
each of these authentication mechanisms.
Recall that
HttpSessionContextIntegrationFilter keeps the
contents of the SecurityContext between invocations
inside an HTTP session. This means the authentication mechanisms are
only used once, being when the principal initially tries to
authenticate. The rest of the time the authentication mechanisms sit
there and silently pass the request through to the next filter in the
chain. That is a practical requirement due to the fact that few
authentication approaches present credentials on each and every call
(BASIC authentication being a notable exception), but what happens if
a principal's account gets cancelled or disabled or otherwise changed
(eg an increase or decrease in GrantedAuthority[]s)
after the initial authentication step? Let's look at how that is
handled now.
The major authorization provider for secure objects has
previously been introduced as
AbstractSecurityInterceptor. This class needs to
have access to an AuthenticationManager. It also
has configurable settings to indicate whether an
Authentication object should be re-authenticated on
each secure object invocation. By default it just accepts any
Authentication inside the
SecurityContextHolder is authenticated if
Authentication.isAuthenticated() returns true. This
is great for performance, but not ideal if you want to ensure
up-to-the-moment authentication validity. For such cases you'll
probably want to set the
AbstractSecurityInterceptor.alwaysReauthenticate
property to true.
You might be asking yourself, "what's this
AuthenticationManager?". We haven't explored it
before, but we have discussed the concept of an
AuthenticationProvider. Quite simply, an
AuthenticationManager is responsible for passing requests through a
chain of AuthenticationProviders. It's a little like the filter chain
we discussed earlier, although there are some differences. There is
only one AuthenticationManager implementation shipped with Acegi
Security, so let's look at how it's configured for the example we're
using in this chapter:
<bean id="authenticationManager" class="org.acegisecurity.providers.ProviderManager">
<property name="providers">
<list>
<ref local="daoAuthenticationProvider"/>
<ref local="anonymousAuthenticationProvider"/>
<ref local="rememberMeAuthenticationProvider"/>
</list>
</property>
</bean>It's probably worth mentioning at this point that your
authentication mechanisms (which are usually filters) are also
injected with a reference to the
AuthenticationManager. So both
AbstractSecurityInterceptor as well as the
authentication mechanisms will use the above
ProviderManager to poll a list of
AuthenticationProviders.
In our example we have three providers. They are tried in the
order shown (which is implied by the use of a List
instead of a Set), with each provider able to
attempt authentication, or skip authentication by simply returning
null. If all implementations return null, the
ProviderManager will throw a suitable exception. If
you're interested in learning more about chaining providers, please
refer to the ProviderManager JavaDocs.
The providers to use will sometimes be interchangeable with the
authentication mechanisms, whilst at other times they will depend on a
specific authentication mechanism. For example, the
DaoAuthenticationProvider just needs a string-based
username and password. Various authentication mechanisms result in the
collection of a string-based username and password, including (but not
limited to) BASIC and form authentication. Equally, some
authentication mechanisms create an authentication request object
which can only be interpreted by a single type of
AuthenticationProvider. An example of this
one-to-one mapping would be JA-SIG CAS, which uses the notion of a
service ticket which can therefore only be authenticated by
CasAuthenticationProvider. A further example of a
one-to-one mapping would be the LDAP authentication mechanism, which
can only be processed an the
LdapAuthenticationProvider. The specifics of such
relationships are detailed in the JavaDocs for each class, plus the
authentication approach-specific chapters of this reference guide. You
need not be terribly concerned about this implementation detail,
because if you forget to register a suitable provider, you'll simply
receive a ProviderNotFoundException when an attempt
to authenticate is made.
After configuring the correct authentication mechanisms in the
FilterChainProxy, and ensuring that a corresponding
AuthenticationProvider is registered in the
ProviderManager, your last step is to configure an
AuthenticationEntryPoint. Recall that earlier we
discussed the role of ExceptionTranslationFilter,
which is used when HTTP-based requests should receive back an HTTP
header or HTTP redirect in order to start authentication. Continuing
on with our earlier example:
<bean id="exceptionTranslationFilter" class="org.acegisecurity.ui.ExceptionTranslationFilter">
<property name="authenticationEntryPoint"><ref local="authenticationProcessingFilterEntryPoint"/></property>
<property name="accessDeniedHandler">
<bean class="org.acegisecurity.ui.AccessDeniedHandlerImpl">
<property name="errorPage" value="/accessDenied.jsp"/>
</bean>
</property>
</bean>
<bean id="authenticationProcessingFilterEntryPoint" class="org.acegisecurity.ui.webapp.AuthenticationProcessingFilterEntryPoint">
<property name="loginFormUrl"><value>/acegilogin.jsp</value></property>
<property name="forceHttps"><value>false</value></property>
</bean>Notice that the ExceptionTranslationFilter
requires two collaborators. The first,
AccessDeniedHandlerImpl, uses a
RequestDispatcher forward to display the specified
access denied error page. We use a forward so that the
SecurityContextHolder still contains details of the
principal, which may be useful for display to the user (in old
releases of Acegi Security we relied upon the servlet container to
handle a 403 error message, which lacked this useful contextual
information). AccessDeniedHandlerImpl will also set
the HTTP header to 403, which is the official error code to indicate
access denied. In the case of the
AuthentionEntryPoint, here we're setting what
action we would like taken when an unauthenticated principal attempts
to perform a protected operation. Because in our example we're going
to be using form-based authentication, we specify
AuthenticationProcessinFilterEntryPoint and the URL
of the login page. Your application will usually only have one entry
point, and most authentication approaches define their own specific
AuthenticationEntryPoint. Details of which entry
point to use for each authentication approach is discussed in the
authentication approach-specific chapters of this reference
guide.
As mentioned in the first part of the reference guide, most
authentication providers take advantage of the
UserDetails and
UserDetailsService interfaces. The contract for
this latter interface consists of a single method:
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException;
The returned UserDetails is an interface that
provides getters that guarantee non-null provision of basic
authentication information such as the username, password, granted
authorities and whether the user is enabled or disabled. Most
authentication providers will use a
UserDetailsService, even if the username and
password are not actually used as part of the authentication decision.
Generally such provider will be using the returned
UserDetails object just for its
GrantedAuthority[] information, because some other
system (like LDAP or X509 or CAS etc) has undertaken the
responsibility of actually validating the credentials.
A single concrete implementation of
UserDetails is provided with Acegi Security, being
the User class. Acegi Security users will need to
decide when writing their UserDetailsService what
concrete UserDetails class to return. In most cases
User will be used directly or subclassed, although
special circumstances (such as object relational mappers) may require
users to write their own UserDetails implementation
from scratch. This is not such an unusual situation, and users should
not hesitate to simply return their normal domain object that
represents a user of the system. This is especially common given that
UserDetails is often used to store additional
principal-related properties (such as their telephone number and email
address), so that they can be easily used by web views.
Given UserDetailsService is so simple to
implement, it should be easy for users to retrieve authentication
information using a persistence strategy of their choice. Having said
that, Acegi Security does include a couple of useful base
implementations, which we'll look at below.
Whilst it is easy to use create a custom
UserDetailsService implementation that extracts
information from a persistence engine of choice, many applications
do not require such complexity. This is particularly true if you're
undertaking a rapid prototype or just starting integrating Acegi
Security, when you don't really want to spend time configuring
databases or writing UserDetailsService
implementations. For this sort of situation, a simple option is to
configure the InMemoryDaoImpl
implementation:
<bean id="inMemoryDaoImpl" class="org.acegisecurity.userdetails.memory.InMemoryDaoImpl">
<property name="userMap">
<value>
marissa=koala,ROLE_TELLER,ROLE_SUPERVISOR
dianne=emu,ROLE_TELLER
scott=wombat,ROLE_TELLER
peter=opal,disabled,ROLE_TELLER
</value>
</property>
</bean> In the above example, the userMap property
contains each of the usernames, passwords, a list of granted
authorities and an optional enabled/disabled keyword. Commas are
used to delimit each token. The username must appear to the left of
the equals sign, and the password must be the first token to the
right of the equals sign. The enabled and
disabled keywords (case insensitive) may appear
in the second or any subsequent token. Any remaining tokens are
treated as granted authorities, which are created as
GrantedAuthorityImpl objects (this is just for
your reference - most applications don't need custom
GrantedAuthority implementations, so using the
default implementation in this manner is just fine). Note that if a
user has no password and/or no granted authorities, the user will
not be created in the in-memory authentication repository.
InMemoryDaoImpl also offers a
setUserProperties(Properties) method, which
allows you to externalise the
java.util.Properties in another Spring configured
bean or an external properties file. You might like to use Spring's
PropertiesFactoryBean, which is useful for
loading such external properties files. This setter might prove
useful for simple applications that have a larger number of users,
or deployment-time configuration changes, but do not wish to use a
full database for handling authentication details.
Acegi Security also includes a
UserDetailsService that can obtain authentication
information from a JDBC data source. Internally Spring JDBC is used,
so it avoids the complexity of a fully-featured object relational
mapper (ORM) just to store user details. If your application does
use an ORM tool, you might prefer to write a custom
UserDetailsService to reuse the mapping files
you've probably already created. Returning to
JdbcDaoImpl, an example configuration is shown
below:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"><value>org.hsqldb.jdbcDriver</value></property> <property name="url"><value>jdbc:hsqldb:hsql://localhost:9001</value></property> <property name="username"><value>sa</value></property> <property name="password"><value></value></property> </bean> <bean id="jdbcDaoImpl" class="org.acegisecurity.userdetails.jdbc.JdbcDaoImpl"> <property name="dataSource"><ref bean="dataSource"/></property> </bean>
You can use different relational database management systems
by modifying the DriverManagerDataSource shown
above. You can also use a global data source obtained from JNDI, as
per normal Spring options. Irrespective of the database used and how
a DataSource is obtained, a standard schema must
be used as indicated in dbinit.txt. You can
download this file from the Acegi Security web site.
If your default schema is unsuitable for your needs,
JdbcDaoImpl provides two properties that allow
customisation of the SQL statements. You may also subclass the
JdbcDaoImpl if further customisation is
necessary. Please refer to the JavaDocs for details, although please
note that the class is not intended for complex custom subclasses.
If you have complex needs (such as a special schema or would like a
certain UserDetails implementation returned),
you'd be better off writing your own
UserDetailsService. The base implementation
provided with Acegi Security is intended for typical situations, and
does not offer infinite configuration flexibility.
Acegi Security is able to prevent a principal from concurrently authenticating to the same application more than a specified number of times. Many ISVs take advantage of this to enforce licensing, whilst network administrators like this feature because it helps prevent people from sharing login names. You can, for example, stop user "Batman" from logging onto the web application from two different sessions.
To use concurrent session support, you'll need to add the
following to web.xml:
<listener> <listener-class>org.acegisecurity.ui.session.HttpSessionEventPublisher</listener-class> </listener>
In addition, you will need to add the
org.acegisecurity.concurrent.ConcurrentSessionFilter
to your FilterChainProxy. The
ConcurrentSessionFilter requires two properties,
sessionRegistry, which generally points to an
instance of SessionRegistryImpl, and
expiredUrl, which points to the page to display
when a session has expired.
The web.xml
HttpSessionEventPublisher causes an
ApplicationEvent to be published to the Spring
ApplicationContext every time a
HttpSession commences or terminates. This is
critical, as it allows the SessionRegistryImpl to
be notified when a session ends.
You will also need to wire up the
ConcurrentSessionControllerImpl and refer to it
from your ProviderManager bean:
<bean id="authenticationManager" class="org.acegisecurity.providers.ProviderManager">
<property name="providers">
<!-- your providers go here -->
</property>
<property name="sessionController"><ref bean="concurrentSessionController"/></property>
</bean>
<bean id="concurrentSessionController" class="org.acegisecurity.concurrent.ConcurrentSessionControllerImpl">
<property name="maximumSessions"><value>1</value></property>
<property name="sessionRegistry"><ref local="sessionRegistry"/></property>
</bean>
<bean id="sessionRegistry" class="org.acegisecurity.concurrent.SessionRegistryImpl"/>AuthenticationTag is used to simply output a
property of the current principal's
Authentication.getPrincipal() object to the web
page.
The following JSP fragment illustrates how to use the
AuthenticationTag:
<authz:authentication operation="username"/>
This tag would cause the principal's name to be output. Here we
are assuming the Authentication.getPrincipal() is a
UserDetails object, which is generally the case
when using the typical
DaoAuthenticationProvider.
Table of Contents
Acegi Security includes a production-quality
AuthenticationProvider implementation called
DaoAuthenticationProvider. This authentication
provider is compatible with all of the authentication mechanisms that
generate a UsernamePasswordAuthenticationToken, and
is probably the most commonly used provider in the framework. Like
most of the other authentication providers, the
DaoAuthenticationProvider leverages a UserDetailsService in order to
lookup the username, password and GrantedAuthority[]s. Unlike most of
the other authentication providers that leverage UserDetailsService,
this authentication provider actually requires the password to be
presented, and the provider will actually evaluate the validity or
otherwise of the password presented in an authentication request
object.
Aside from adding DaoAuthenticationProvider to your ProviderManager list (as discussed at the start of this part of the reference guide), and ensuring a suitable authentication mechanism is configured to present a UsernamePasswordAuthenticationToken, the configuration of the provider itself is rather simple:
<bean id="daoAuthenticationProvider" class="org.acegisecurity.providers.dao.DaoAuthenticationProvider"> <property name="userDetailsService"><ref bean="inMemoryDaoImpl"/></property> <property name="saltSource"><ref bean="saltSource"/></property> <property name="passwordEncoder"><ref bean="passwordEncoder"/></property> </bean>
The PasswordEncoder and
SaltSource are optional. A
PasswordEncoder provides encoding and decoding of
passwords presented in the UserDetails object that
is returned from the configured UserDetailsService.
A SaltSource enables the passwords to be populated
with a "salt", which enhances the security of the passwords in the
authentication repository. PasswordEncoder
implementations are provided with Acegi Security covering MD5, SHA and
cleartext encodings. Two SaltSource implementations
are also provided: SystemWideSaltSource which
encodes all passwords with the same salt, and
ReflectionSaltSource, which inspects a given
property of the returned UserDetails object to
obtain the salt. Please refer to the JavaDocs for further details on
these optional features.
In addition to the properties above, the
DaoAuthenticationProvider supports optional caching
of UserDetails objects. The
UserCache interface enables the
DaoAuthenticationProvider to place a
UserDetails object into the cache, and retrieve it
from the cache upon subsequent authentication attempts for the same
username. By default the DaoAuthenticationProvider
uses the NullUserCache, which performs no caching.
A usable caching implementation is also provided,
EhCacheBasedUserCache, which is configured as
follows:
<bean id="daoAuthenticationProvider" class="org.acegisecurity.providers.dao.DaoAuthenticationProvider">
<property name="userDetailsService"><ref bean="userDetailsService"/></property>
<property name="userCache"><ref bean="userCache"/></property>
</bean>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation">
<value>classpath:/ehcache-failsafe.xml</value>
</property>
</bean>
<bean id="userCacheBackend" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager">
<ref local="cacheManager"/>
</property>
<property name="cacheName">
<value>userCache</value>
</property>
</bean>
<bean id="userCache" class="org.acegisecurity.providers.dao.cache.EhCacheBasedUserCache">
<property name="cache"><ref local="userCacheBackend"/></property>
</bean> All Acegi Security EH-CACHE implementations (including
EhCacheBasedUserCache) require an EH-CACHE
Cache object. The Cache object
can be obtained from wherever you like, although we recommend you use
Spring's factory classes as shown in the above configuration. If using
Spring's factory classes, please refer to the Spring documentation for
further details on how to optimise the cache storage location, memory
usage, eviction policies, timeouts etc.
A design decision was made not to support account locking in the
DaoAuthenticationProvider, as doing so would have
increased the complexity of the UserDetailsService
interface. For instance, a method would be required to increase the
count of unsuccessful authentication attempts. Such functionality
could be easily provided by leveraging the application event
publishing features discussed below.
DaoAuthenticationProvider returns an
Authentication object which in turn has its
principal property set. The principal will be
either a String