diff --git a/docs/manual/src/asciidoc/index.adoc b/docs/manual/src/asciidoc/index.adoc index 64b646d195..714374a9d5 100644 --- a/docs/manual/src/asciidoc/index.adoc +++ b/docs/manual/src/asciidoc/index.adoc @@ -4,8 +4,8 @@ Ben Alex; Luke Taylor; Rob Winch Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications. [[preface]] -== Preface -Spring 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. += Preface +Spring Security provides a comprehensive security solution for Java EE-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. Spring Security makes this latter area - application security - much easier. @@ -21,21 +21,21 @@ Finally, welcome to the Spring Security <>. [[getting-started]] -== Getting Started += Getting Started The later parts of this guide provide an in-depth discussion of the framework architecture and implementation classes, which you need to understand if you want to do any serious customization. In this part, we'll introduce Spring Security 3.0, give a brief overview of the project's history and take a slightly gentler look at how to get started using the framework. In particular, we'll look at namespace configuration which provides a much simpler way of securing your application compared to the traditional Spring bean approach where you have to wire up all the implementation classes individually. We'll also take a look at the sample applications that are available. It's worth trying to run these and experimenting with them a bit even before you read the later sections - you can dip back into them as your understanding of the framework increases. Please also check out the http://static.springsource.org/spring-security/site/index.html[project website] as it has useful information on building the project, plus links to articles, videos and tutorials. [[introduction]] -=== Introduction +== Introduction [[what-is-acegi-security]] -==== What is Spring Security? -Spring 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 Spring Security more easily. +=== What is Spring Security? +Spring Security provides comprehensive security services for Java EE-based enterprise software applications. There is a particular emphasis on supporting projects built using The Spring Framework, which is the leading Java EE 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 Spring Security more easily. -People use Spring 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 Spring Security overcomes these problems, and also brings you dozens of other useful, customisable security features. +People use Spring Security for many reasons, but most are drawn to the project after finding the security features of Java EE'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 Spring Security overcomes these problems, and also brings you dozens of other useful, customisable security features. As you probably know two major areas of application security are "authentication" and "authorization" (or "access-control"). These are the two main areas that Spring Security targets. "Authentication" 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 within 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 Spring Security. @@ -110,7 +110,7 @@ Irrespective of the authentication mechanism, Spring Security provides a deep se [[history]] -==== History +=== History Spring Security began in late 2003 as "The Acegi Security System for Spring". 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 compared with the size today!), 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. @@ -125,7 +125,7 @@ Today Spring Security enjoys a strong and active open source community. There ar [[release-numbering]] -==== Release Numbering +=== Release Numbering It is useful to understand how Spring Security release numbers work, as it will help you identify the effort (or lack thereof) involved in migrating to future releases of the project. Each release uses a standard triplet of integers: MAJOR.MINOR.PATCH. The intent is that MAJOR versions are incompatible, large-scale upgrades of the API. MINOR versions should largely retain source and binary compatibility with older minor versions, thought there may be some design changes and incompatible udates. PATCH level should be perfectly compatible, forwards and backwards, with the possible exception of changes which are to fix bugs and defects. The extent to which you are affected by changes will depend on how tightly integrated your code is. If you are doing a lot of customization you are more likely to be affected than if you are using a simple namespace configuration. @@ -134,17 +134,17 @@ You should always test your application thoroughly before rolling out a new vers [[get-spring-security]] -==== Getting Spring Security +=== Getting Spring Security You can get hold of Spring Security in several ways. You can download a packaged distribution from the main Spring http://www.springsource.com/download/community?project=Spring%20Security[download page], download individual jars (and sample WAR files) from the Maven Central repository (or a SpringSource Maven repository for snapshot and milestone releases) or, alternatively, you can build the project from source yourself. See the project web site for more details. [[modules]] -===== Project Modules +==== Project Modules In Spring Security 3.0, the codebase has been sub-divided into separate jars which more clearly separate different functionaltiy areas and third-party dependencies. If you are using Maven to build your project, then these are the modules you will add to your `pom.xml`. Even if you're not using Maven, we'd recommend that you consult the `pom.xml` files to get an idea of third-party dependencies and versions. Alternatively, a good idea is to examine the libraries that are included in the sample applications. [[spring-security-core]] -====== Core - spring-security-core.jar +===== Core - spring-security-core.jar Contains core authentication and access-contol classes and interfaces, remoting support and basic provisioning APIs. Required by any application which uses Spring Security. Supports standalone applications, remote clients, method (service layer) security and JDBC user provisioning. Contains the top-level packages: * `org.springframework.security.core` @@ -160,42 +160,42 @@ Contains core authentication and access-contol classes and interfaces, remoting [[spring-security-remoting]] -====== Remoting - spring-security-remoting.jar +===== Remoting - spring-security-remoting.jar Provides intergration with Spring Remoting. You don't need this unless you are writing a remote client which uses Spring Remoting. The main package is `org.springframework.security.remoting`. [[spring-security-web]] -====== Web - spring-security-web.jar +===== Web - spring-security-web.jar Contains filters and related web-security infrastructure code. Anything with a servlet API dependency. You'll need it if you require Spring Security web authentication services and URL-based access-control. The main package is `org.springframework.security.web`. [[spring-security-config]] -====== Config - spring-security-config.jar +===== Config - spring-security-config.jar Contains the security namespace parsing code. You need it if you are using the Spring Security XML namespace for configuration. The main package is `org.springframework.security.config`. None of the classes are intended for direct use in an application. [[spring-security-ldap]] -====== LDAP - spring-security-ldap.jar +===== LDAP - spring-security-ldap.jar LDAP authentication and provisioning code. Required if you need to use LDAP authentication or manage LDAP user entries. The top-level package is `org.springframework.security.ldap`. [[spring-security-acl]] -====== ACL - spring-security-acl.jar +===== ACL - spring-security-acl.jar Specialized domain object ACL implementation. Used to apply security to specific domain object instances within your application. The top-level package is `org.springframework.security.acls`. [[spring-security-cas]] -====== CAS - spring-security-cas.jar +===== CAS - spring-security-cas.jar Spring Security's CAS client integration. If you want to use Spring Security web authentication with a CAS single sign-on server. The top-level package is `org.springframework.security.cas`. [[spring-security-openid]] -====== OpenID - spring-security-openid.jar +===== OpenID - spring-security-openid.jar OpenID web authentication support. Used to authenticate users against an external OpenID server. `org.springframework.security.openid`. Requires OpenID4Java. [[get-source]] -===== Checking out the Source +==== Checking out the Source Since Spring Security is an Open Source project, we'd strongly encourage you to check out the source code using git. This will give you full access to all the sample applications and you can build the most up to date version of the project easily. Having the source for a project is also a huge help in debugging. Exception stack traces are no longer obscure black-box issues but you can get straight to the line that's causing the problem and work out what's happening. The source is the ultimate documentation for a project and often the simplest place to find out how something actually works. To obtain the source for the project, use the following git command: @@ -208,13 +208,7 @@ git clone https://github.com/spring-projects/spring-security.git This will give you access to the entire project history (including all releases and branches) on your local machine. [[new]] -=== What's new in Spring Security - -* <> -* <> - -[[new-3.2]] -==== What's new in Spring Security 3.2 +== What's new in Spring Security 3.2 There are https://jira.springsource.org/issues/?jql=project%20%3D%20SEC%20AND%20fixVersion%20in%20(%223.2.0.RC2%22%2C%20%223.2.0%22%2C%20%223.2.0.RC1%22%2C%20%223.2.0.M2%22%2C%20%223.2.0.M1%22)%20ORDER%20BY%20priority%20DESC%2C%20issuetype%20ASC%2C%20key%20DESC[150+ tickets resolved] with the Spring Security 3.2 release. Below are the highlights of the new features found in Spring Security 3.2. @@ -245,63 +239,8 @@ There are https://jira.springsource.org/issues/?jql=project%20%3D%20SEC%20AND%20 ** Converted all documentation to http://asciidoctor.org/[Asciidoctor] * Sonar integration for the build -[[new-3.1]] -==== What's new in Spring Security 3.1 -This section contains summary of the updates found in Spring Security 3.1. A detailed list of changes can be found in the project's https://jira.springsource.org/secure/IssueNavigator!executeAdvanced.jspa?jqlQuery=project+%3D+SEC+AND+fixVersion+in+%2812315%2C+11892%2C+11634%2C+11633%2C+11632%2C+11174%29+order+by+priority%2C+type&runQuery=true&clear=true[JIRA] - - -[[new-3.1-highlevel]] -===== High level updates found Spring Security 3.1 -Below you can find a high level summary of updates to Spring Security 3.1. - - -* Support for multiple http elements -* Support for stateless authentication -* DebugFilter provides additional debugging information -* Improved Active Directory LDAP support (i.e. ActiveDirectoryLdapAuthenticationProvider) -* Added Basic Crypto Module. -* The namespace is fully documented in the reference appendix. -* Added dependencies section to the reference appendix -* Support HttpOnly Flag for Cookies in Servlet 3.0 environments -* InMemoryUserDetailsManager provides in memory implementation of UserDetailsManager -* Support for hasPermission expression on the authorize JSP tag -* Support for disabling UI security (for testing purposes) -* Support erasing credentials after successful authentication -* Support clearing cookies on logout -* Spring Security Google App Engine example application -* Support for CAS proxy tickets -* Support for arbitrary implementations of JAAS Configuration -* Support nested switching of users for SwitchUserFilter - - - -[[new-3.1-ns]] -===== Spring Security 3.1 namespace updates -Below you can find a summary of updates to the Spring Security 3.1 namespace. - - -* Added support for multiple <>> elements and support for determining which one to use with <>, <>, and <>. Further information can be found in <> section of the reference. -* Added stateless option for <> -* Added support for <> and <>. -* Added <> -* Added <> and <> -* Added <>> -* Added Support for setting the AuthenticationDetailsSource using the namespace. See <>, <>, <>, and <>. -* Added support for http/expression-handler. This allows <>> to be used for web access expressions. -* Added <> -* Added <> -* Added <> -* Added <> -* Added <>> -* Added <> -* Added <> -* Added <>> -* Added <> -* Added <> -* Added <> and <> - [[jc]] -=== Java Configuration +== Java Configuration General support for http://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-java[Java Configuration] was added to Spring framework in Spring 3.1. Since Spring Security 3.2 there has been Spring Security Java Configuration support which enables users to easily configure Spring Security without the use of any XML. @@ -309,7 +248,7 @@ If you are familiar with the <> then you should find quite a few simi NOTE: Spring Security provides https://github.com/spring-projects/spring-security/tree/master/samples[lots of sample applications] that end in `-jc` which demonstrate the use of Spring Security Java Configuration. -==== Hello Web Security Java Configuration +=== Hello Web Security Java Configuration The first step is to create our Spring Security Java Configuration. The configuration creates a Servlet Filter known as the `springSecurityFilterChain` which is responsible for all the security (protecting the application URLs, validating submitted username and passwords, redirecting to the log in form, etc) within your application. You can find the most basic example of a Spring Security Java configuration below: @@ -356,14 +295,14 @@ There really isn't much to this configuration, but it does a lot. You can find a ** http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#login(java.lang.String,%20java.lang.String)[HttpServletRequest.html#login(java.lang.String, java.lang.String)] ** http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#logout()[HttpServletRequest.html#logout()] -===== AbstractSecurityWebApplicationInitializer +==== AbstractSecurityWebApplicationInitializer The next step is to register the `springSecurityFilterChain` with the war. This can be done in Java Configuration with http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-container-config[Spring's WebApplicationInitializer support] in a Servlet 3.0+ environment. Not suprisingly, Spring Security provides a base class `AbstractSecurityWebApplicationInitializer` that will ensure the `springSecurityFilterChain` gets registered for you. The way in which we use `AbstractSecurityWebApplicationInitializer` differs depending on if we are already using Spring or if Spring Security is the only Spring component in our application. * <> - Use these instructions if you are not using Spring already * <> - Use these instructions if you are already using Spring -===== AbstractSecurityWebApplicationInitializer without Existing Spring +==== AbstractSecurityWebApplicationInitializer without Existing Spring If you are not using Spring or Spring MVC, you will need to pass in the `SecurityConfig` into the superclass to ensure the configuration is picked up. You can find an example below: @@ -385,7 +324,7 @@ The `SecurityWebApplicationInitializer` will do the following things: * Automatically register the springSecurityFilterChain Filter for every URL in your application * Add a ContextLoaderListener that loads the <>. -===== AbstractSecurityWebApplicationInitializer with Spring MVC +==== AbstractSecurityWebApplicationInitializer with Spring MVC If we were using Spring elsewhere in our application we probably already had a `WebApplicationInitializer` that is loading our Spring Configuration. If we use the previous configuration we would get an error. Instead, we should register Spring Security with the existing `ApplicationContext`. For example, if we were using Spring MVC our `SecurityWebApplicationInitializer` would look something like the following: @@ -417,7 +356,7 @@ public class MvcWebApplicationInitializer extends ---- [[jc-httpsecurity]] -==== HttpSecurity +=== HttpSecurity Thus far our <> only contains information about how to authenticate our users. How does Spring Security know that we want to require all users to be authenticated? How does Spring Security know we want to support form based authentication? The reason for this is that the `WebSecurityConfigurerAdapter` provides a default configuration in the `configure(HttpSecurity http)` method that looks like: @@ -454,7 +393,7 @@ You will notice that this configuration is quite similar the XML Namespace confi The Java Configuration equivalent of closing an XML tag is expressed using the `and()` method which allows us to continue configuring the parent. If you read the code it also makes sense. I want to configure authorized requests __and__ configure form login __and__ configure HTTP Basic authentication. [[jc-form]] -==== Java Configuration and Form Login +=== Java Configuration and Form Login 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. Since Spring Security's default configuration does not 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 logging in and so on. While the automatically generated log in page is convenient to get up and running quickly, most applications will want to provide their own log in page. To do so we can update our configuration as seen below: @@ -517,7 +456,7 @@ NOTE: The login page below represents our current configuration. We could easily <6> We must <> To learn more read the <> section of the reference [jc-authorize-requests]] -==== Authorize Requests +=== Authorize Requests Our examples have only required users to be authenticated and have done so for every URL in our application. We can specify custom requirements for our URLs by adding multiple children to our `http.authorizeRequests()` method. For example: @@ -543,11 +482,11 @@ protected void configure(HttpSecurity http) throws Exception { <5> Any URL that has not already been matched on only requires that the user be authenticated [[jc-authentication]] -==== Authentication +=== Authentication Thus far we have only taken a look at the most basic authentication configuration. Let's take a look at a few slightly more advanced options for configuring authentication. -===== In Memory Authentication +==== In Memory Authentication We have already seen an example of configuring in memory authentication for a single user. Below is an example to configure multiple users: @@ -562,7 +501,7 @@ public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception } ---- -===== JDBC Authentication +==== JDBC Authentication You can find the updates to suppport JDBC based authentication. The example below assumes that you have already defined a `DataSource` within your application. The https://github.com/spring-projects/spring-security/tree/master/samples/jdbc-jc[jdbc-jc sample] provides a complete example of using JDBC based authentication. @@ -582,7 +521,7 @@ public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception } ---- -===== LDAP Authentication +==== LDAP Authentication You can find the updates to suppport LDAP based authentication. The https://github.com/spring-projects/spring-security/tree/master/samples/lda-jc[ldap-jc sample] provides a complete example of using LDAP based authentication. @@ -648,7 +587,7 @@ cn: admin uniqueMember: uid=admin,ou=people,dc=springframework,dc=org ---- -==== Multiple HttpSecurity +=== Multiple HttpSecurity We can configure multiple HttpSecurity instances just as we can have multiple `` blocks. The key is to extend the `WebSecurityConfigurationAdapter` multiple times. For example, the following is an example of having a different configuration for URL's that start with `/api/`. @@ -656,7 +595,7 @@ We can configure multiple HttpSecurity instances just as we can have multiple `< ---- @Configuration @EnableWebSecurity -public static class MultiHttpSecurityConfig { +public class MultiHttpSecurityConfig { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) { <1> auth @@ -699,11 +638,11 @@ public static class MultiHttpSecurityConfig { <4> Create another instance of `WebSecurityConfigurerAdapter`. If the URL does not start with `/api/` this configuration will be used. This configuration is considered after `ApiWebSecurityConfigurationAdapter` since it has an `@Order` value after `1` (no `@Order` defaults to last). [[jc-method]] -==== Method Security +=== Method Security From 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 <>. 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. -===== EnableGlobalMethodSecurity +==== EnableGlobalMethodSecurity We can enable annotation-based security using the `@EnableGlobalMethodSecurity` annotation on any `@Configuration` instance. For example, the following would enable Spring Security's `@Secured` annotation. @@ -772,7 +711,7 @@ public interface BankService { } ---- -===== GlobalMethodSecurityConfiguration +==== GlobalMethodSecurityConfiguration Sometimes you may need to perform operations that are more complicated than are possible with the `@EnableGlobalMethodSecurity` annotation allow. For these instances, you can extend the `GlobalMethodSecurityConfiguration` ensuring that the `@EnableGlobalMethodSecurity` annotation is present on your subclass. For example, if you wanted to provide a custom `MethodSecurityExpressionHander`, you could use the following configuration: @@ -792,10 +731,10 @@ public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration { For additional information about methods that can be overriden, refer to the `GlobalMethodSecurityConfiguration` Javadoc. [[ns-config]] -=== Security Namespace Configuration +== Security Namespace Configuration -==== Introduction +=== Introduction 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 http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/htmlsingle/spring-framework-reference.html[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: [source,xml] @@ -847,7 +786,7 @@ In many of the examples you will see (and in the sample) applications, we We'll assume this syntax is being used from now on in this chapter. -===== Design of the Namespace +==== 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. @@ -865,11 +804,11 @@ The namespace is designed to capture the most common uses of the framework and p We'll see how to configure these in the following sections. [[ns-getting-started]] -==== Getting Started with Security Namespace Configuration +=== 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. [[ns-web-xml]] -===== web.xml Configuration +==== web.xml Configuration The first thing you need to do is add the following filter declaration to your `web.xml` file: [source,xml] @@ -890,7 +829,7 @@ context. In this case, the bean is named "springSecurityFilterChain", which is a 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 `` element. [[ns-minimal]] -===== A Minimal Configuration +==== A Minimal Configuration All you need to enable web security to begin with is [source,xml] @@ -946,7 +885,7 @@ At this point you should be able to start up your application and you will be re [[ns-form-and-basic]] -===== Form and Basic Login Options +==== 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 logging 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: [source,xml] @@ -993,7 +932,7 @@ If you want to use basic authentication instead of form login, then change the c 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. [[ns-form-target]] -====== Setting a Default Post-Login Destination +===== 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 successfully logging in, and defaults to "/". You can also configure things so that the 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: [source,xml] @@ -1009,11 +948,11 @@ If a form login isn't prompted by an attempt to access a protected resource, the For even more control over the destination, you can use the `authentication-success-handler-ref` attribute as an alternative to `default-target-url`. The referenced bean should be an instance of `AuthenticationSuccessHandler`. You'll find more on this in the <> chapter and also in the namespace appendix, as well as information on how to customize the flow when authentication fails. [[ns-logout]] -===== Logout Handling +==== Logout Handling The `logout` element adds support for logging out by navigating to a particular URL. The default logout URL is `/j_spring_security_logout`, but you can set it to something else using the `logout-url` attribute. More information on other available attributes may be found in the namespace appendix. [[ns-auth-providers]] -===== Using other Authentication Providers +==== 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 <>, 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 [source,xml] @@ -1064,7 +1003,7 @@ 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 the providers will be queried in the order they are declared. See <> for more on information on how the Spring Security `AuthenticationManager` is configured using the namespace. [[ns-password-encoder]] -====== Adding a Password Encoder +===== Adding a Password Encoder Passwords should always be encoded using a secure hashing algorithm designed for the purpose (not a standard algorithm like SHA or MD5). This is supported by the `` element. With bcrypt encoded passwords, the original authentication provider configuration would look like this: [source,xml] @@ -1091,14 +1030,14 @@ Passwords should always be encoded using a secure hashing algorithm designed for Bcrypt is a good choice for most cases, unless you have a legacy system which forces you to use a different algorithm. If you are using a simple hashing algorithm or, even worse, storing plain text passwords, then you should consider migrating to a more secure option like bcrypt. [[ns-web-advanced]] -==== Advanced Web Features +=== Advanced Web Features [[ns-remember-me]] -===== Remember-Me Authentication +==== Remember-Me Authentication See the separate <> for information on remember-me namespace configuration. [[ns-requires-channel]] -===== Adding HTTP/HTTPS Channel Security +==== Adding HTTP/HTTPS Channel Security If 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 ``: [source,xml] @@ -1127,9 +1066,9 @@ If your application uses non-standard ports for HTTP and/or HTTPS, you can speci Note that in order to be truly secure, an application should not use HTTP at all or switch between HTTP and HTTPS. It should start in HTTPS (with the user entering an HTTPS URL) and use a secure connection throughout to avoid any possibility of man-in-the-middle attacks. [[ns-session-mgmt]] -===== Session Management +==== Session Management -====== Detecting Timeouts +===== Detecting 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: [source,xml] @@ -1165,7 +1104,7 @@ If you are running your application behind a proxy, you may also be able to remo [[ns-concurrent-sessions]] -====== Concurrent Session Control +===== Concurrent Session Control If 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: [source,xml] @@ -1206,7 +1145,7 @@ The second login will then be rejected. By "rejected", we mean that the user wil 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 <>. [[ns-session-fixation]] -====== Session Fixation Attack Protection +===== Session Fixation Attack Protection http://en.wikipedia.org/wiki/Session_fixation[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 or otherwise changing the session ID when a user logs in. If you don't require this protection, or it conflicts with some other requirement, you can control the behavior using the `session-fixation-protection` attribute on ``, which has four options * `none` - Don't do anything. The original session will be retained. @@ -1222,7 +1161,7 @@ When session fixation protection occurs, it results in a `SessionFixationProtect [[ns-openid]] -===== OpenID Support +==== OpenID Support The namespace supports http://openid.net/[OpenID] login either instead of, or in addition to normal form-based login, with a simple change: [source,xml] @@ -1243,7 +1182,7 @@ You should then register yourself with an OpenID provider (such as myopenid.com) 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 <> 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 Exchange +===== Attribute Exchange Support for OpenID http://openid.net/specs/openid-attribute-exchange-1_0.html[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: [source,xml] @@ -1269,12 +1208,12 @@ The `OpenIDAttribute` contains the attribute type and the retrieved value (or va [[ns-headers]] -===== Response Headers +==== Response Headers For additional information on how to customize the headers element refer to the <> section of the reference. [[ns-custom-filters]] -===== Adding in Your Own Filters +==== Adding in Your Own Filters If 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 `` 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. @@ -1381,7 +1320,7 @@ You can add your own filter to the stack, using the `custom-filter` element and 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. -.Standard Filter Aliases and OrderingAvoiding filter position conflicts +.Avoiding filter position conflicts [TIP] ==== @@ -1395,20 +1334,19 @@ If you're replacing a namespace filter which requires an authentication entry po [[ns-entry-point-ref]] -====== Setting a Custom -`AuthenticationEntryPoint` +===== 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 `` 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 <> chapter. [[ns-method-security]] -==== Method Security +=== Method Security From 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 <>. 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. [[ns-global-method]] -===== The Element +==== The 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 `` element. The following declaration would enable support for Spring Security's `@Secured`: [source,xml] @@ -1477,7 +1415,7 @@ You can enable more than one type of annotation in the same application, but onl ==== [[ns-protect-pointcut]] -====== Adding Security Pointcuts using protect-pointcut +===== 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: @@ -1492,7 +1430,7 @@ The use of `protect-pointcut` is particularly powerful, as it allows you to appl 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. Security annotations take precedence over pointcuts. [[ns-access-manager]] -==== The Default AccessDecisionManager +=== 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). @@ -1501,7 +1439,7 @@ The default strategy is to use an `AffirmativeBased` `AccessDecisionManager` wit [[ns-custom-access-mgr]] -===== Customizing the AccessDecisionManager +==== 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: @@ -1523,7 +1461,7 @@ The syntax for web security is the same, but on the `http` element: ---- [[ns-auth-manager]] -==== The Authentication Manager and the Namespace +=== 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 <>. 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 `AuthenticationProvider` s that are used. You may want to register additional `AuthenticationProvider` beans with the `ProviderManager` and you can do this using the `` element with the `ref` attribute, where the value of the attribute is the name of the provider bean you want to add. For example: @@ -1556,22 +1494,22 @@ Another common requirement is that another bean in the context may require a ref ---- [[sample-apps]] -=== Sample Applications -There are several sample web applications that are available with the project. To avoid an overly large download, only the "tutorial" and "contacts" samples are included in the distribution zip file. The others can be built directly from the source which you can obtain as described in <>. It's easy to build the project yourself and there's more information on the project web site at http://www.springsource.org/security/[ http://www.springsource.org/security/ ]. All paths referred to in this chapter are relative to the project source directory. +== Sample Applications +There are several sample web applications that are available with the project. To avoid an overly large download, only the "tutorial" and "contacts" samples are included in the distribution zip file. The others can be built directly from the source which you can obtain as described in <>. It's easy to build the project yourself and there's more information on the project web site at http://spring.io/spring-security/[http://spring.io/spring-security/]. All paths referred to in this chapter are relative to the project source directory. [[tutorial-sample]] -==== Tutorial Sample +=== Tutorial Sample The tutorial sample is a nice basic example to get you started. It uses simple namespace configuration throughout. The compiled application is included in the distribution zip file, ready to be deployed into your web container (`spring-security-samples-tutorial-3.1.x.war`). The <> authentication mechanism is used in combination with the commonly-used <> authentication provider to automatically remember the login using cookies. We recommend you start with the tutorial sample, as the XML is minimal and easy to follow. Most importantly, you can easily add this one XML file (and its corresponding `web.xml` entries) to your existing application. Only when this basic integration is achieved do we suggest you attempt adding in method authorization or domain object security. [[contacts-sample]] -==== Contacts +=== Contacts The Contacts Sample is an advanced example in that it illustrates the more powerful features of domain object access control lists (ACLs) in addition to basic application security. The application provides an interface with which the users are able to administer a simple database of contacts (the domain objects). -To deploy, simply copy the WAR file from Spring Security distribution into your container���s `webapps` directory. The war should be called `spring-security-samples-contacts-3.1.x.war` (the appended version number will vary depending on what release you are using). +To deploy, simply copy the WAR file from Spring Security distribution into your container's `webapps` directory. The war should be called `spring-security-samples-contacts-3.1.x.war` (the appended version number will vary depending on what release you are using). After starting your container, check the application can load. Visit http://localhost:8080/contacts (or whichever URL is appropriate for your web container and the WAR you deployed). @@ -1611,40 +1549,40 @@ The application allows you to modify the access control lists associated with di [[ldap-sample]] -==== LDAP Sample +=== LDAP Sample The LDAP sample application provides a basic configuration and sets up both a namespace configuration and an equivalent configuration using traditional beans, both in the same application context file. This means there are actually two identical authentication providers configured in this application. [[openid-sample]] -==== OpenID Sample +=== OpenID Sample The OpenID sample demonstrates how to use the namespace to configure OpenID and how to set up http://openid.net/specs/openid-attribute-exchange-1_0.html[attribute exchange] configurations for Google, Yahoo and MyOpenID identity providers (you can experiment with adding others if you wish). It uses the JQuery-based http://code.google.com/p/openid-selector/[openid-selector] project to provide a user-friendly login page which allows the user to easily select a provider, rather than typing in the full OpenID identifier. The application differs from normal authentication scenarios in that it allows any user to access the site (provided their OpenID authentication is successful). The first time you login, you will get a "Welcome [your name]"" message. If you logout and log back in (with the same OpenID identity) then this should change to "Welcome Back". This is achieved by using a custom `UserDetailsService` which assigns a standard role to any user and stores the identities internally in a map. Obviously a real application would use a database instead. Have a look at the source form more information. This class also takes into account the fact that different attributes may be returned from different providers and builds the name with which it addresses the user accordingly. [[cas-sample]] -==== CAS Sample +=== CAS Sample The CAS sample requires that you run both a CAS server and CAS client. It isn't included in the distribution so you should check out the project code as described in <>. You'll find the relevant files under the `sample/cas` directory. There's also a `Readme.txt` file in there which explains how to run both the server and the client directly from the source tree, complete with SSL support. [[jaas-sample]] -==== JAAS Sample +=== JAAS Sample The JAAS sample is very simple example of how to use a JAAS LoginModule with Spring Security. The provided LoginModule will successfully authenticate a user if the username equals the password otherwise a LoginException is thrown. The AuthorityGranter used in this example always grants the role ROLE_USER. The sample application also demonstrates how to run as the JAAS Subject returned by the LoginModule by setting <> equal to "true". [[preauth-sample]] -==== Pre-Authentication Sample -This sample application demonstrates how to wire up beans from the <> framework to make use of login information from a J2EE container. The user name and roles are those setup by the container. +=== Pre-Authentication Sample +This sample application demonstrates how to wire up beans from the <> framework to make use of login information from a Java EE container. The user name and roles are those setup by the container. The code is in `samples/preauth`. [[community]] -=== Spring Security Community +== Spring Security Community [[jira]] -==== Issue Tracking +=== Issue Tracking Spring Security uses JIRA to manage bug reports and enhancement requests. If you find a bug, please log a report using JIRA. Do not log it on the support forum, mailing list or by emailing the project's developers. Such approaches are ad-hoc and we prefer to manage bugs using a more formal process. If possible, in your issue report please provide a JUnit test that demonstrates any incorrect behaviour. Or, better yet, provide a patch that corrects the issue. Similarly, enhancements are welcome to be logged in the issue tracker, although we only accept enhancement requests if you include corresponding unit tests. This is necessary to ensure project test coverage is adequately maintained. @@ -1653,25 +1591,25 @@ You can access the issue tracker at http://jira.springsource.org/browse/SEC[http [[becoming-involved]] -==== Becoming Involved +=== Becoming Involved We welcome your involvement in the Spring Security project. There are many ways of contributing, including reading the forum and responding to questions from other people, writing new code, improving existing code, assisting with documentation, developing samples or tutorials, or simply making suggestions. [[further-info]] -==== Further Information +=== Further Information Questions and comments on Spring Security are welcome. You can use the Spring Community Forum web site at http://forum.springsource.org[http://forum.springsource.org] to discuss Spring Security with other users of the framework. Remember to use JIRA for bug reports, as explained above. [[overall-architecture]] -== Architecture and Implementation += Architecture and Implementation Once you are familiar with setting up and running some namespace-configuration based applications, you may wish to develop more of an understanding of how the framework actually works behind the namespace facade. Like most software, Spring 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 look at some of these and see how they work together to support authentication and access-control within Spring Security. [[technical-overview]] -=== Technical Overview +== Technical Overview [[runtime-environment]] -==== Runtime Environment +=== Runtime Environment Spring Security 3.0 requires a Java 5.0 Runtime Environment or higher. As Spring 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 Spring 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 Spring Security in a server classloader. All the required files will be contained within your application. @@ -1680,17 +1618,17 @@ This design offers maximum deployment time flexibility, as you can simply copy y [[core-components]] -==== Core Components +=== Core Components In Spring Security 3.0, the contents of the `spring-security-core` jar were stripped down to the bare minimum. It no longer contains any code related to web-application security, LDAP or namespace configuration. We'll take a look here at some of the Java types that you'll find in the core module. They represent the building blocks of the the framework, so if you ever need to go beyond a simple namespace configuration then it's important that you understand what they are, even if you don't actually need to interact with them directly. -===== SecurityContextHolder, SecurityContext and Authentication Objects +==== SecurityContextHolder, SecurityContext and Authentication Objects 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, Spring 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. `SecurityContextHolder` can be configured with a strategy on startup to specify how you would like the context to be stored. For a standalone application you would use the `SecurityContextHolder.MODE_GLOBAL` strategy. 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, the second is to 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. -====== Obtaining information about the current user +===== Obtaining information about the current user Inside the `SecurityContextHolder` we store details of the principal currently interacting with the application. Spring Security uses an `Authentication` object to represent this information. You won't normally need to create an `Authentication` object yourself, but it is fairly common for users to query the `Authentication` object. You can use the following code block - from anywhere in your application - to obtain the name of the currently authenticated user, for example: @@ -1711,7 +1649,7 @@ The object returned by the call to `getContext()` is an instance of the `Securit [[tech-userdetailsservice]] -===== The UserDetailsService +==== The UserDetailsService 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 core interface in Spring 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 Spring 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`: @@ -1737,13 +1675,13 @@ There is often some confusion about `UserDetailsService`. It is purely a DAO for [[tech-granted-authority]] -===== GrantedAuthority +==== GrantedAuthority 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 Spring 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, Spring Security is expressly designed to handle this common requirement, but you'd instead use the project's domain object security capabilities for this purpose. -===== Summary +==== Summary Just to recap, the major building blocks of Spring Security that we've seen so far are: @@ -1765,11 +1703,11 @@ Now that you've gained an understanding of these repeatedly-used components, let [[tech-intro-authentication]] -==== Authentication +=== Authentication Spring Security can participate in many different authentication environments. While we recommend people use Spring Security for authentication and not integrate with existing Container Managed Authentication, it is nevertheless supported - as is integrating with your own proprietary authentication system. -===== What is authentication in Spring Security? +==== What is authentication in Spring Security? Let's consider a standard authentication scenario that everyone is familiar with. . A user is prompted to log in with a username and password. @@ -1867,7 +1805,7 @@ Successfully authenticated. Security context contains: \ Note that you don't normally need to write any code like this. The process will normally occur internally, in a web authentication filter for example. We've just included the code here to show that the question of what actually constitutes authentication in Spring Security has quite a simple answer. A user is authenticated when the `SecurityContextHolder` contains a fully populated `Authentication` object. -===== Setting the SecurityContextHolder Contents Directly +==== Setting the SecurityContextHolder Contents Directly In fact, Spring Security doesn't mind how you put the `Authentication` object inside the `SecurityContextHolder`. The only critical requirement is that the `SecurityContextHolder` contains an `Authentication` which represents a principal before the `AbstractSecurityInterceptor` (which we'll see more about later) needs to authorize a user operation. You can (and many users do) write their own filters or MVC controllers to provide interoperability with authentication systems that are not based on Spring 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 situations like this it's quite easy to get Spring 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 a Spring Security-specific `Authentication` object, and put it into the `SecurityContextHolder`. In this case you also need to think about things which are normally taken care of automatically by the built-in authentication infrastructure. For example, you might need to pre-emptively create an HTTP session to <>, before you write the response to the client footnote:[It isn't possible to create a session once the response has been committed.]. @@ -1876,7 +1814,7 @@ If you're wondering how the `AuthenticationManager` is implemented in a real wor [[tech-intro-web-authentication]] -==== Authentication in a Web Application +=== Authentication in a Web Application Now let's explore the situation where you are using Spring Security in a web application (without `web.xml` security enabled). How is a user authenticated and the security context established? Consider a typical web application's authentication process: @@ -1893,23 +1831,23 @@ Consider a typical web application's authentication process: Spring 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` and an "authentication mechanism", which is responsible for calling the `AuthenticationManager` which we saw in the previous section. -===== ExceptionTranslationFilter +==== ExceptionTranslationFilter `ExceptionTranslationFilter` is a Spring Security filter that has responsibility for detecting any Spring 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). [[tech-intro-auth-entry-point]] -===== AuthenticationEntryPoint +==== AuthenticationEntryPoint 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 Spring Security, but let's keep it simple for now). Each major authentication system will have its own `AuthenticationEntryPoint` implementation, which typically performs one of the actions described in step 3. -===== Authentication Mechanism +==== Authentication Mechanism Once your browser submits 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 Spring Security we have a special name for the function of collecting authentication details from a user agent (usually a web browser), referring to it as the "authentication mechanism". Examples are form-base login and Basic authentication. Once the authentication details have been collected from the user agent, an `Authentication`"request" object is built and then presented to the `AuthenticationManager`. 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 `AuthenticationManager` rejected the request, the authentication mechanism will ask the user agent to retry (step two above). [[tech-intro-sec-context-persistence]] -===== Storing the SecurityContext between requests +==== Storing the SecurityContext between requests Depending on the type of application, there may need to be a strategy in place to store the security context between user operations. In a typical web application, a user logs in once and is subsequently identified by their session Id. The server caches the principal information for the duration session. In Spring Security, the responsibility for storing the `SecurityContext` between requests falls to the `SecurityContextPersistenceFilter`, which by default stores the context as an `HttpSession` attribute between HTTP requests. It restores the context to the `SecurityContextHolder` for each request and, crucially, clears the `SecurityContextHolder` when the request completes. You shouldn't interact directly with the `HttpSession` for security purposes. There is simply no justification for doing so - always use the `SecurityContextHolder` instead. Many other types of application (for example, a stateless RESTful web service) do not use HTTP sessions and will re-authenticate on every request. However, it is still important that the `SecurityContextPersistenceFilter` is included in the chain to make sure that the `SecurityContextHolder` is cleared after each request. @@ -1920,20 +1858,20 @@ In an application which receives concurrent requests in a single session, the sa ==== [[tech-intro-access-control]] -==== Access-Control (Authorization) in Spring Security +=== Access-Control (Authorization) in Spring Security The main interface responsible for making access-control decisions in Spring Security is the `AccessDecisionManager`. It has a `decide` method which takes an `Authentication` object representing the principal requesting access, a "secure object" (see below) and a list of security metadata attributes which apply for the object (such as a list of roles which are required for access to be granted). -===== Security and AOP Advice +==== Security and AOP Advice 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. Spring Security provides an around advice for method invocations as well as web requests. We achieve an around advice for method invocations using Spring's standard AOP support 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 Spring 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. If you just need to secure method invocations in the services layer, Spring's standard AOP will be adequate. If you need to secure domain objects directly, you will likely find that AspectJ is worth considering. +For those not familiar with AOP, the key point to understand is that Spring 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 Java EE applications. If you just need to secure method invocations in the services layer, Spring's standard AOP 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 Spring AOP, 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 pattern is to perform some web request authorization, coupled with some Spring AOP method invocation authorization on the services layer. [[secure-objects]] -===== Secure Objects and the AbstractSecurityInterceptor +==== Secure Objects and the AbstractSecurityInterceptor So what __is__ a "secure object" anyway? Spring Security uses the term to refer to any object that can have security (such as an authorization decision) applied to it. The most common examples are method invocations and web requests. Each supported secure object type has its own interceptor class, which is a subclass of `AbstractSecurityInterceptor`. Importantly, by the time the `AbstractSecurityInterceptor` is called, the `SecurityContextHolder` will contain a valid `Authentication` if the principal has been authenticated. @@ -1947,29 +1885,29 @@ Each supported secure object type has its own interceptor class, which is a subc . Call the `AfterInvocationManager` if configured, once the invocation has returned. If the invocation raised an exception, the `AfterInvocationManager` will not be invoked. [[tech-intro-config-attributes]] -====== What are Configuration Attributes? +===== What are Configuration Attributes? A "configuration attribute" can be thought of as a String that has special meaning to the classes used by`AbstractSecurityInterceptor`. They are represented by the interface `ConfigAttribute` within the framework. They may be simple role names or have more complex meaning, depending on the how sophisticated the `AccessDecisionManager` implementation is. The `AbstractSecurityInterceptor` is configured with a `SecurityMetadataSource` which it uses to look up the attributes for a secure object. Usually this configuration will be hidden from the user. Configuration attributes will be entered as annotations on secured methods or as access attributes on secured URLs. For example, when we saw something like `` in the namespace introduction, this is saying that the configuration attributes `ROLE_A` and `ROLE_B` apply to web requests matching the given pattern. In practice, with the default `AccessDecisionManager` configuration, this means that anyone who has a `GrantedAuthority` matching either of these two attributes will be allowed access. Strictly speaking though, they are just attributes and the interpretation is dependent on the `AccessDecisionManager` implementation. The use of the prefix `ROLE_` is a marker to indicate that these attributes are roles and should be consumed by Spring Security's`RoleVoter`. This is only relevant when a voter-based `AccessDecisionManager` is in use. We'll see how the `AccessDecisionManager` is implemented in the <>. -====== RunAsManager +===== RunAsManager 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 Spring 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. -====== AfterInvocationManager +===== AfterInvocationManager Following the secure object invocation 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 can even entirely replace the object, or throw an exception, or not change it in any way as it chooses. The after-invocation checks will only be executed if the invocation is successful. If an exception occurs, the additional checks will be skipped. `AbstractSecurityInterceptor` and its related objects are shown in <> [[abstract-security-interceptor]] -.Security interceptors and the ���secure object��� model +.Security interceptors and the "secure object" model image::images/security-interception.png[Abstract Security Interceptor] -====== Extending the Secure Object Model +===== Extending the 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 `FilterInvocation`) with complete transparency. [[localization]] -==== Localization +=== Localization Spring Security supports localization of exception messages that end users are likely to see. If your application is designed for English-speaking users, you don't need to do anything as by default all Security 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 messages that are focused on developers or system deployers (including incorrect attributes, interface contract violations, using incorrect constructors, startup time validation, debug-level logging) are not localized and instead are hard-coded in English within Spring Security's code. @@ -1994,12 +1932,12 @@ The "contacts" sample application is set up to use localized messages. [[core-services]] -=== Core Services +== Core Services Now that we have a high-level overview of the Spring Security architecture and its core classes, let's take a closer look at one or two of the core interfaces and their implementations, in particular the `AuthenticationManager`, `UserDetailsService` and the `AccessDecisionManager`. These crop up regularly throughout the remainder of this document so it's important you know how they are configured and how they operate. [[core-services-authentication-manager]] -==== The AuthenticationManager, ProviderManager and AuthenticationProvider +=== The AuthenticationManager, ProviderManager and AuthenticationProvider The `AuthenticationManager` is just an interface, so the implementation can be anything we choose, but how does it work in practice? What if we need to check multiple authentication databases or a combination of different authentication services such as a database and an LDAP server? The default implementation in Spring Security is called `ProviderManager` and rather than handling the authentication request itself, it delegates to a list of configured `AuthenticationProvider` s, each of which is queried in turn to see if it can perform the authentication. Each 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 chapter and refresh your memory. The most common approach to verifying an authentication request is to load the corresponding `UserDetails` and check the loaded password against the one that has been entered by the user. This is the approach used by the `DaoAuthenticationProvider` (see below). The loaded `UserDetails` object - and particularly the `GrantedAuthority` s it contains - will be used when building the fully populated `Authentication` object which is returned from a successful authentication and stored in the `SecurityContext`. @@ -2027,14 +1965,14 @@ Authentication mechanisms such as a web form-login processing filter are injecte [[core-services-erasing-credentials]] -===== Erasing Credentials on Successful Authentication +==== Erasing Credentials on Successful Authentication By default (from Spring Security 3.1 onwards) the `ProviderManager` will attempt to clear any sensitive credentials information from the `Authentication` object which is returned by a successful authentication request. This prevents information like passwords being retained longer than necessary. This may cause issues when you are using a cache of user objects, for example, to improve performance in a stateless application. If the `Authentication` contains a reference to an object in the cache (such as a `UserDetails` instance) and this has its credentials removed, then it will no longer be possible to authenticate against the cached value. You need to take this into account if you are using a cache. An obvious solution is to make a copy of the object first, either in the cache implementation or in the `AuthenticationProvider` which creates the returned `Authentication` object. Alternatively, you can disable the `eraseCredentialsAfterAuthentication` property on `ProviderManager`. See the Javadoc for more information. [[core-services-dao-provider]] -===== DaoAuthenticationProvider +==== DaoAuthenticationProvider The simplest `AuthenticationProvider` implemented by Spring Security is `DaoAuthenticationProvider`, which is also one of the earliest supported by the framework. It leverages a `UserDetailsService` (as a DAO) in order to lookup the username, password and `GrantedAuthority` s. It authenticates the user simply by comparing the password submitted in a `UsernamePasswordAuthenticationToken` against the one loaded by the `UserDetailsService`. Configuring the provider is quite simple: [source,xml] @@ -2050,7 +1988,7 @@ The simplest `AuthenticationProvider` implemented by Spring Security is `DaoAuth The `PasswordEncoder` is optional. A `PasswordEncoder` provides encoding and decoding of passwords presented in the `UserDetails` object that is returned from the configured `UserDetailsService`. This will be discussed in more detail <>. -==== UserDetailsService Implementations +=== UserDetailsService Implementations As mentioned in the earlier in this reference guide, most authentication providers take advantage of the `UserDetails` and `UserDetailsService` interfaces. Recall that the contract for `UserDetailsService` is a single method: [source,java] @@ -2064,7 +2002,7 @@ Given `UserDetailsService` is so simple to implement, it should be easy for user [[core-services-in-memory-service]] -===== In-Memory Authentication +==== In-Memory Authentication Is easy to use create a custom `UserDetailsService` implementation that extracts information from a persistence engine of choice, but many applications do not require such complexity. This is particularly true if you're building a prototype application or just starting integrating Spring 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 use the `user-service` element from the security <>: [source,xml] @@ -2098,7 +2036,7 @@ bob=bobspassword,ROLE_USER,enabled ---- [[core-services-jdbc-user-service]] -===== JdbcDaoImpl +==== JdbcDaoImpl Spring 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: [source,xml] @@ -2118,18 +2056,18 @@ Spring Security also includes a `UserDetailsService` that can obtain authenticat 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 with any other Spring configuration. -====== Authority Groups +===== Authority Groups By default, `JdbcDaoImpl` loads the authorities for a single user with the assumption that the authorities are mapped directly to users (see the <>). An alternative approach is to partition the authorities into groups and assign groups to the user. Some people prefer this approach as a means of administering user rights. See the `JdbcDaoImpl` Javadoc for more information on how to enable the use of group authorities. The group schema is also included in the appendix. [[core-services-password-encoding]] -==== Password Encoding +=== Password Encoding Spring Security's `PasswordEncoder` interface is used to support the use of passwords which are encoded in some way in persistent storage. You should never store passwords in plain text. Always use a one-way password hashing algorithm such as bcrypt which uses a built-in salt value which is different for each stored password. Do not use a plain hash function such as MD5 or SHA, or even a salted version. Bcrypt is deliberately designed to be slow and to hinder offline password cracking, whereas standard hash algorithms are fast and can easily be used to test thousands of passwords in parallel on custom hardware. You might think this doesn't apply to you since your password database is secure and offline attacks aren't a risk. If so, do some research and read up on all the high-profile sites which have been compromised in this way and have been pilloried for storing their passwords insecurely. It's best to be on the safe side. Using `org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"` is a good choice for security. There are also compatible implementations in other common programming languages so it a good choice for interoperability too. If you are using a legacy system which already has hashed passwords, then you will need to use an encoder which matches your current algorithm, at least until you can migrate your users to a more secure scheme (usually this will involve asking the user to set a new password, since hashes are irreversible). Spring Security has a package containing legacy password encoding implementation, namely, `org.springframework.security.authentication.encoding`. The `DaoAuthenticationProvider` can be injected with either the new or legacy `PasswordEncoder` types. -===== What is a hash? +==== What is a hash? Password hashing is not unique to Spring Security but is a common source of confusion for users who are not familiar with the concept. A hash (or digest) algorithm is a one-way function which produces a piece of fixed-length output data (the hash) from some input data, such as a password. As an example, the MD5 hash of the string "password" (in hexadecimal) is [source,txt] @@ -2139,7 +2077,7 @@ Password hashing is not unique to Spring Security but is a common source of conf A hash is "one-way" in the sense that it is very difficult (effectively impossible) to obtain the original input given the hash value, or indeed any possible input which would produce that hash value. This property makes hash values very useful for authentication purposes. They can be stored in your user database as an alternative to plaintext passwords and even if the values are compromised they do not immediately reveal a password which can be used to login. Note that this also means you have no way of recovering the password once it is encoded. -===== Adding Salt to a Hash +==== Adding Salt to a Hash One potential problem with the use of password hashes that it is relatively easy to get round the one-way property of the hash if a common word is used for the input. People tend to choose similar passwords and huge dictionaries of these from previously hacked sites are available online. For example, if you search for the hash value `5f4dcc3b5aa765d61d8327deb882cf99` using google, you will quickly find the original word "password". In a similar way, an attacker can build a dictionary of hashes from a standard word list and use this to lookup the original password. One way to help prevent this is to have a suitably strong password policy to try to prevent common words from being used. Another is to use a"salt" when calculating the hashes. This is an additional string of known data for each user which is combined with the password before calculating the hash. Ideally the data should be as random as possible, but in practice any salt value is usually preferable to none. Using a salt means that an attacker has to build a separate dictionary of hashes for each salt value, making the attack more complicated (but not impossible). Bcrypt automatically generates a random salt value for each password when it is encoded, and stores it in the bcrypt string in a standard format. @@ -2149,25 +2087,25 @@ Bcrypt automatically generates a random salt value for each password when it is The legacy approach to handling salt was to inject a `SaltSource` into the `DaoAuthenticationProvider`, which would obtain a salt value for a particular user and pass it to the `PasswordEncoder`. Using bcrypt means you don't have worry about the details of salt handling (such as where the the value is stored), as it is all done internally. So we'd strongly recommend you use bcrypt unless you already have a system in place which stores the salt separately. ==== -===== Hashing and Authentication +==== Hashing and Authentication When an authentication provider (such as Spring Security's `DaoAuthenticationProvider`) needs to check the password in a submitted authentication request against the known value for a user, and the stored password is encoded in some way, then the submitted value must be encoded using exactly the same algorithm. It's up to you to check that these are compatible as Spring Security has no control over the persistent values. If you add password hashing to your authentication configuration in Spring Security, and your database contains plaintext passwords, then there is no way authentication can succeed. Even if you are aware that your database is using MD5 to encode the passwords, for example, and your application is configured to use Spring Security's `Md5PasswordEncoder`, there are still things that can go wrong. The database may have the passwords encoded in Base 64, for example while the encoder is using hexadecimal strings (the default). Alternatively your database may be using upper-case while the output from the encoder is lower-case. Make sure you write a test to check the output from your configured password encoder with a known password and salt combination and check that it matches the database value before going further and attempting to authenticate through your application. Using a standard like bcrypt will avoid these issues. If you want to generate encoded passwords directly in Java for storage in your user database, then you can use the `encode` method on the `PasswordEncoder`. [[web-app-security]] -== Web Application Security += Web Application Security Most Spring Security users will be using the framework in applications which make user of HTTP and the Servlet API. In this part, we'll take a look at how Spring Security provides authentication and access-control features for the web layer of an application. We'll look behind the facade of the namespace and see which classes and interfaces are actually assembled to provide web-layer security. In some situations it is necessary to use traditional bean configuration to provide full control over the configuration, so we'll also see how to configure these classes directly without the namespace. [[security-filter-chain]] -=== The Security Filter Chain +== The Security Filter Chain Spring Security's web infrastructure is based entirely on standard servlet filters. It doesn't use servlets or any other servlet-based frameworks (such as Spring MVC) internally, so it has no strong links to any particular web technology. It deals in `HttpServletRequest` s and `HttpServletResponse` s and doesn't care whether the requests come from a browser, a web service client, an `HttpInvoker` or an AJAX application. Spring Security maintains a filter chain internally where each of the filters has a particular responsibility and filters are added or removed from the configuration depending on which services are required. The ordering of the filters is important as there are dependencies between them. If you have been using <>, then the filters are automatically configured for you and you don't have to define any Spring beans explicitly but here may be times when you want full control over the security filter chain, either because you are using features which aren't supported in the namespace, or you are using your own customized versions of classes. [[delegating-filter-proxy]] -==== DelegatingFilterProxy +=== DelegatingFilterProxy When using servlet filters, you obviously need to declare them in your `web.xml`, or they will be ignored by the servlet container. In Spring Security, the filter classes are also Spring beans defined in the application context and thus able to take advantage of Spring's rich dependency-injection facilities and lifecycle interfaces. Spring's `DelegatingFilterProxy` provides the link between `web.xml` and the application context. When using `DelegatingFilterProxy`, you will see something like this in the `web.xml` file: @@ -2189,7 +2127,7 @@ Notice that the filter is actually a `DelegatingFilterProxy`, and not the class [[filter-chain-proxy]] -==== FilterChainProxy +=== FilterChainProxy Spring Security's web infrastructure should only be used by delegating to an instance of `FilterChainProxy`. The security filters should not be used by themselves. In theory you could declare each Spring Security filter bean that you require in your application context file and add a corresponding `DelegatingFilterProxy` entry to `web.xml` for each filter, making sure that they are ordered correctly, but this would be cumbersome and would clutter up the `web.xml` file quickly if you have a lot of filters. `FilterChainProxy` lets us add a single entry to `web.xml` and deal entirely with the application context file for managing our web security beans. It is wired using a`DelegatingFilterProxy`, just like in the example above, but with the `filter-name` set to the bean name "filterChainProxy". The filter chain is then declared in the application context with the same bean name. Here's an example: [source,xml] @@ -2221,11 +2159,11 @@ Note that `FilterChainProxy` does not invoke standard filter lifecycle methods o When we looked at how to set up web security using <>, we used a `DelegatingFilterProxy` with the name "springSecurityFilterChain". You should now be able to see that this is the name of the `FilterChainProxy` which is created by the namespace. -===== Bypassing the Filter Chain +==== Bypassing the Filter Chain You can use the attribute `filters = "none"` as an alternative to supplying a filter bean list. This will omit the request pattern from the security filter chain entirely. Note that anything matching this path will then have no authentication or authorization services applied and will be freely accessible. If you want to make use of the contents of the `SecurityContext` contents during a request, then it must have passed through the security filter chain. Otherwise the `SecurityContextHolder` will not have been populated and the contents will be null. -==== Filter Ordering +=== Filter Ordering The order that filters are defined in the chain is very important. Irrespective of which filters you are actually using, the order should be as follows: * `ChannelProcessingFilter`, because it might need to redirect to a different protocol @@ -2240,7 +2178,7 @@ The order that filters are defined in the chain is very important. Irrespective * `FilterSecurityInterceptor`, to protect web URIs and raise exceptions when access is denied [[request-matching]] -==== Request Matching and HttpFirewall +=== Request Matching and HttpFirewall Spring Security has several areas where patterns you have defined are tested against incoming requests in order to decide how the request should be handled. This occurs when the `FilterChainProxy` decides which filter chain a request should be passed through and also when the `FilterSecurityInterceptor` decides which security constraints apply to a request. It's important to understand what the mechanism is and what URL value is used when testing against the patterns that you define. The Servlet Specification defines several properties for the `HttpServletRequest` which are accessible via getter methods, and which we might want to match against. These are the `contextPath`, `servletPath`, `pathInfo` and `queryString`. Spring Security is only interested in securing paths within the application, so the `contextPath` is ignored. Unfortunately, the servlet spec does not define exactly what the values of `servletPath` and `pathInfo` will contain for a particular request URI. For example, each path segment of a URL may contain parameters, as defined in http://www.ietf.org/rfc/rfc2396.txt[RFC 2396] footnote:[You have probably seen this when a browser doesn't support cookies and the `jsessionid` parameter is appended to the URL after a semi-colon. However the RFC allows the presence of these parameters in any path segment of the URL]. The Specification does not clearly state whether these should be included in the `servletPath` and `pathInfo` values and the behaviour varies between different servlet containers. There is a danger that when an application is deployed in a container which does not strip path parameters from these values, an attacker could add them to the requested URL in order to cause a pattern match to succeed or fail unexpectedly. footnote:[The original values will be returned once the request leaves the `FilterChainProxy`, so will still be available to the application.]. Other variations in the incoming URL are also possible. For example, it could contain path-traversal sequences (like `/../`) or multiple forward slashes (`//`) which could also cause pattern-matches to fail. Some containers normalize these out before performing the servlet mapping, but others don't. To protect against issues like these, `FilterChainProxy` uses an `HttpFirewall` strategy to check and wrap the request. Un-normalized requests are automatically rejected by default, and path parameters and duplicate slashes are removed for matching purposes. footnote:[So, for example, an original request path `/secure;hack=1/somefile.html;hack=2` will be returned as `/secure/somefile.html`.]. It is therefore essential that a `FilterChainProxy` is used to manage the security filter chain. Note that the `servletPath` and `pathInfo` values are decoded by the container, so your application should not have any valid paths which contain semi-colons, as these parts will be removed for matching purposes. @@ -2254,12 +2192,12 @@ In practice we recommend that you use method security at your service layer, to Security defined at the service layer is much more robust and harder to bypass, so you should always take advantage of Spring Security's method security options. -==== Use with other Filter-Based Frameworks +=== Use with other Filter-Based Frameworks If you're using some other framework that is also filter-based, then you need to make sure that the Spring Security filters come first. This enables the `SecurityContextHolder` to be populated in time for use by the other filters. Examples are the use of SiteMesh to decorate your web pages or a web framework like Wicket which uses a filter to handle its requests. [[filter-chains-with-ns]] -==== Advanced Namespace Configuration +=== Advanced Namespace Configuration As we saw earlier in the namespace chapter, it's possible to use multiple `http` elements to define different security configurations for different URL patterns. Each element creates a filter chain within the internal `FilterChainProxy` and the URL pattern that should be mapped to it. The elements will be added in the order they are declared, so the most specific patterns must again be declared first. Here's another example, for a similar situation to that above, where the application supports both a stateless RESTful API and also a normal web application which users log into using a form. @@ -2283,11 +2221,11 @@ As we saw earlier in the namespace chapter, it's possible to use multiple `http` ---- [[core-web-filters]] -=== Core Security Filters +== Core Security Filters There are some key filters which will always be used in a web application which uses Spring Security, so we'll look at these and their supporting classes and interfaces first. We won't cover every feature, so be sure to look at the Javadoc for them if you want to get the complete picture. [[filter-security-interceptor]] -==== FilterSecurityInterceptor +=== FilterSecurityInterceptor We've already seen `FilterSecurityInterceptor` briefly when discussing <>, and we've already used it with the namespace where the `` elements are combined to configure it internally. Now we'll see how to explicitly configure it for use with a`FilterChainProxy`, along with its companion filter `ExceptionTranslationFilter`. A typical configuration example is shown below: [source,xml] @@ -2332,7 +2270,7 @@ The `SecurityMetadataSource` created by the namespace syntax obtains the configu Patterns are always evaluated in the order they are defined. Thus it is important that more specific patterns are defined higher in the list than less specific patterns. This is reflected in our example above, where the more specific `/secure/super/` pattern appears higher than the less specific `/secure/` pattern. If they were reversed, the `/secure/` pattern would always match and the `/secure/super/` pattern would never be evaluated. [[exception-translation-filter]] -==== ExceptionTranslationFilter +=== ExceptionTranslationFilter The `ExceptionTranslationFilter` sits above the `FilterSecurityInterceptor` in the security filter stack. It doesn't do any actual security enforcement itself, but handles exceptions thrown by the security interceptors and provides suitable and HTTP responses. [source,xml] @@ -2357,12 +2295,12 @@ The `ExceptionTranslationFilter` sits above the `FilterSecurityInterceptor` in t ---- [[auth-entry-point]] -===== AuthenticationEntryPoint +==== AuthenticationEntryPoint The `AuthenticationEntryPoint` will be called if the user requests a secure HTTP resource but they are not authenticated. An appropriate `AuthenticationException` or `AccessDeniedException` will be thrown by a security interceptor further down the call stack, triggering the `commence` method on the entry point. This does the job of presenting the appropriate response to the user so that authentication can begin. The one we've used here is `LoginUrlAuthenticationEntryPoint`, which redirects the request to a different URL (typically a login page). The actual implementation used will depend on the authentication mechanism you want to be used in your application. [[access-denied-handler]] -===== AccessDeniedHandler +==== AccessDeniedHandler What happens if a user is already authenticated and they try to access a protected resource? In normal usage, this shouldn't happen because the application workflow should be restricted to operations to which a user has access. For example, an HTML link to an administration page might be hidden from users who do not have an admin role. You can't rely on hiding links for security though, as there's always a possibility that a user will just enter the URL directly in an attempt to bypass the restrictions. Or they might modify a RESTful URL to change some of the argument values. Your application must be protected against these scenarios or it will definitely be insecure. You will typically use simple web layer security to apply constraints to basic URLs and use more specific method-based security on your service layer interfaces to really nail down what is permissible. If an `AccessDeniedException` is thrown and a user has already been authenticated, then this means that an operation has been attempted for which they don't have enough permissions. In this case, `ExceptionTranslationFilter` will invoke a second strategy, the `AccessDeniedHandler`. By default, an `AccessDeniedHandlerImpl` is used, which just sends a 403 (Forbidden) response to the client. Alternatively you can configure an instance explicitly (as in the above example) and set an error page URL which it will forwards the request to footnote:[ @@ -2373,7 +2311,7 @@ It's also possible to supply a custom `AccessDeniedHandler` when you're using th [[request-caching]] -===== SavedRequest s and the RequestCache Interface +==== SavedRequest s and the RequestCache Interface Another of `ExceptionTranslationFilter`'s responsibilities is to save the current request before invoking the `AuthenticationEntryPoint`. This allows the request to be restored after the use has authenticated (see previous overview of <>). A typical example would be where the user logs in with a form, and is then redirected to the original URL by the default `SavedRequestAwareAuthenticationSuccessHandler` (see <>). The `RequestCache` encapsulates the functionality required for storing and retrieving `HttpServletRequest` instances. By default the `HttpSessionRequestCache` is used, which stores the request in the `HttpSession`. The `RequestCacheFilter` has the job of actually restoring the saved request from the cache when the user is redirected to the original URL. @@ -2382,7 +2320,7 @@ Under normal circumstances, you shouldn't need to modify any of this functionali [[security-context-persistence-filter]] -==== SecurityContextPersistenceFilter +=== SecurityContextPersistenceFilter We covered the purpose of this all-important filter in the <> chapter so you might want to re-read that section at this point. Let's first take a look at how you would configure it for use with a `FilterChainProxy`. A basic configuration only requires the bean itself [source,xml] @@ -2395,7 +2333,7 @@ As we saw previously, this filter has two main tasks. It is responsible for stor [[security-context-repository]] -===== SecurityContextRepository +==== SecurityContextRepository From Spring Security 3.0, the job of loading and storing the security context is now delegated to a separate strategy interface: [source,java] @@ -2429,7 +2367,7 @@ Alternatively you could provide an instance of `NullSecurityContextRepository`, [[form-login-filter]] -==== UsernamePasswordAuthenticationFilter +=== UsernamePasswordAuthenticationFilter We've now seen the three main filters which are always present in a Spring Security web configuration. These are also the three which are automatically created by the namespace `` element and cannot be substituted with alternatives. The only thing that's missing now is an actual authentication mechanism, something that will allow a user to authenticate. This filter is the most commonly used authentication filter and the one that is most often customized footnote:[For historical reasons, prior to Spring Security 3.0, this filter was called `AuthenticationProcessingFilter` and the entry point was called `AuthenticationProcessingFilterEntryPoint`. Since the framework now supports many different forms of authentication, they have both been given more specific names in 3.0.]. It also provides the implementation used by the `` element from the namespace. There are three stages required to configure it. * Configure a `LoginUrlAuthenticationEntryPoint` with the URL of the login page, just as we did above, and set it on the `ExceptionTranslationFilter`. @@ -2449,7 +2387,7 @@ The login form simply contains `j_username` and `j_password` input fields, and p ---- [[form-login-flow-handling]] -===== Application Flow on Authentication Success and Failure +==== Application Flow on Authentication Success and Failure The filter calls the configured `AuthenticationManager` to process each authentication request. The destination following a successful authentication or an authentication failure is controlled by the `AuthenticationSuccessHandler` and `AuthenticationFailureHandler` strategy interfaces, respectively. The filter has properties which allow you to set these so you can customize the behaviour completely footnote:[In versions prior to 3.0, the application flow at this point had evolved to a stage was controlled by a mix of properties on this class and strategy plugins. The decision was made for 3.0 to refactor the code to make these two strategies entirely responsible.]. Some standard implementations are supplied such as `SimpleUrlAuthenticationSuccessHandler`, `SavedRequestAwareAuthenticationSuccessHandler`, `SimpleUrlAuthenticationFailureHandler` and `ExceptionMappingAuthenticationFailureHandler`. Have a look at the Javadoc for these classes and also for `AbstractAuthenticationProcessingFilter` to get an overview of how they work and the supported features. If authentication is successful, the resulting `Authentication` object will be placed into the `SecurityContextHolder`. The configured `AuthenticationSuccessHandler` will then be called to either redirect or forward the user to the appropriate destination. By default a `SavedRequestAwareAuthenticationSuccessHandler` is used, which means that the user will be redirected to the original destination they requested before they were asked to login. @@ -2462,21 +2400,21 @@ The `ExceptionTranslationFilter` caches the original request a user makes. When If authentication fails, the configured `AuthenticationFailureHandler` will be invoked. [[servletapi]] -=== Servlet API integration +== Servlet API integration This section describes how Spring Security is integrated with the Servlet API. The https://github.com/SpringSource/spring-security/blob/master/samples/servletapi-xml[servletapi-xml] sample application demonstrates the usage of each of these methods. [[servletapi-25]] -==== Servlet 2.5+ Integration +=== Servlet 2.5+ Integration [[servletapi-remote-user]] -===== HttpServletRequest.getRemoteUser() +==== HttpServletRequest.getRemoteUser() The http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getRemoteUser()[HttpServletRequest.getRemoteUser()] will return the result of `SecurityContextHolder.getContext().getAuthentication().getName()` which is typically the current username. This can be useful if you want to display the current username in your application. Additionally, checking if this is null can be used to indicate if a user has authenticated or is anonymous. Knowing if the user is authenticated or not can be useful for determining if certain UI elements should be shown or not (i.e. a log out link should only be displayed if the user is authenticated). [[servletapi-user-principal]] -===== HttpServletRequest.getUserPrincipal() +==== HttpServletRequest.getUserPrincipal() The http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getUserPrincipal()[HttpServletRequest.getUserPrincipal()] will return the result of `SecurityContextHolder.getContext().getAuthentication()`. This means it is an `Authentication` which is typically an instance of `UsernamePasswordAuthenticationToken` when using username and password based authentication. This can be useful if you need additional information about your user. For example, you might have created a custom `UserDetailsService` that returns a custom `UserDetails` containing a first and last name for your user. You could obtain this information with the following: @@ -2496,7 +2434,7 @@ It should be noted that it is typically bad practice to perform so much logic th ==== [[servletapi-user-in-role]] -===== HttpServletRequest.isUserInRole(String) +==== HttpServletRequest.isUserInRole(String) The http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#isUserInRole(java.lang.String)[HttpServletRequest.isUserInRole(String)] will determine if `SecurityContextHolder.getContext().getAuthentication().getAuthorities()` contains a `GrantedAuthority` with the role passed into `isUserInRole(String)`. Typically users should not pass in the "ROLE_" prefix into this method since it is added automatically. For example, if you want to determine if the current user has the authority "ROLE_ADMIN", you could use the the following: [source,java] @@ -2507,17 +2445,17 @@ boolean isAdmin = httpServletRequest.isUserInRole("ADMIN"); This might be useful to determine if certain UI components should be displayed. For example, you might display admin links only if the current user is an admin. [[servletapi-3]] -==== Servlet 3+ Integration +=== Servlet 3+ Integration The following section describes the Servlet 3 methods that Spring Security integrates with. [[servletapi-authenticate]] -===== HttpServletRequest.authenticate(HttpServletRequest,HttpServletResponse) +==== HttpServletRequest.authenticate(HttpServletRequest,HttpServletResponse) The http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#authenticate%28javax.servlet.http.HttpServletResponse%29[HttpServletRequest.authenticate(HttpServletRequest,HttpServletResponse)] method can be used to ensure that a user is authenticated. If they are not authenticated, the configured AuthenticationEntryPoint will be used to request the user to authenticate (i.e. redirect to the login page). [[servletapi-login]] -===== HttpServletRequest.login(String,String) +==== HttpServletRequest.login(String,String) The http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#login%28java.lang.String,%20java.lang.String%29[HttpServletRequest.login(String,String)] method can be used to authenticate the user with the current `AuthenticationManager`. For example, the following would attempt to authenticate with the username "user" and password "password": [source,java] @@ -2535,13 +2473,13 @@ It is not necessary to catch the ServletException if you want Spring Security to ==== [[servletapi-logout]] -===== HttpServletRequest.logout() +==== HttpServletRequest.logout() The http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#logout%28%29[HttpServletRequest.logout()] method can be used to log the current user out. Typically this means that the SecurityContextHolder will be cleared out, the HttpSession will be invalidated, any "Remember Me" authentication will be cleaned up, etc. However, the configured LogoutHandler implementations will vary depending on your Spring Security configuration. It is important to note that after HttpServletRequest.logout() has been invoked, you are still in charge of writing a response out. Typically this would involve a redirect to the welcome page. [[servletapi-start-runnable]] -===== AsyncContext.start(Runnable) +==== AsyncContext.start(Runnable) The http://docs.oracle.com/javaee/6/api/javax/servlet/AsyncContext.html#start%28java.lang.Runnable%29[AsynchContext.start(Runnable)] method that ensures your credentials will be propagated to the new Thread. Using Spring Security's concurrency support, Spring Security overrides the AsyncContext.start(Runnable) to ensure that the current SecurityContext is used when processing the Runnable. For example, the following would output the current user's Authentication: [source,java] @@ -2563,7 +2501,7 @@ async.start(new Runnable() { ---- [[servletapi-async]] -===== Async Servlet Support +==== Async Servlet Support If you are using Java Based configuration, you are ready to go. If you are using XML configuration, there are a few updates that are necessary. The first step is to ensure you have updated your web.xml to use at least the 3.0 schema as shown below: [source,xml] @@ -2623,23 +2561,23 @@ The issue is that this Thread is not known to Spring Security, so the SecurityCo Since version 3.2, Spring Security is smart enough to no longer automatically save the SecurityContext on commiting the HttpServletResponse as soon as HttpServletRequest.startAsync() is invoked. [[servletapi-31]] -==== Servlet 3.1+ Integration +=== Servlet 3.1+ Integration The following section describes the Servlet 3.1 methods that Spring Security integrates with. [[servletapi-change-session-id]] -===== HttpServletRequest#changeSessionId() +==== HttpServletRequest#changeSessionId() The http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletRequest.html#changeSessionId()[HttpServletRequest.changeSessionId()] is the default method for protecting against <> attacks in Servlet 3.1 and higher. [[basic]] -=== Basic and Digest Authentication +== Basic and Digest Authentication Basic and digest authentiation are alternative authentication mechanisms which are popular in web applications. Basic authentication is often used with stateless clients which pass their credentials on each request. It's quite common to use it in combination with form-based authentication where an application is used through both a browser-based user interface and as a web-service. However, basic authentication transmits the password as plain text so it should only really be used over an encrypted transport layer such as HTTPS. [[basic-processing-filter]] -==== BasicAuthenticationFilter +=== BasicAuthenticationFilter `BasicAuthenticationFilter` is responsible for processing basic authentication credentials presented in HTTP headers. This can be used for authenticating calls made by Spring remoting protocols (such as Hessian and Burlap), as well as normal browser user agents (such as Firefox and Internet Explorer). The standard governing HTTP Basic Authentication is defined by RFC 1945, Section 11, and `BasicAuthenticationFilter` conforms with this RFC. Basic Authentication is an attractive approach to authentication, because it is very widely deployed in user agents and implementation is extremely simple (it's just a Base64 encoding of the username:password, specified in an HTTP header). [[basic-config]] -===== Configuration +==== Configuration To implement HTTP Basic Authentication, you need to add a `BasicAuthenticationFilter` to your filter chain. The application context should contain `BasicAuthenticationFilter` and its required collaborator: @@ -2662,7 +2600,7 @@ The configured `AuthenticationManager` processes each authentication request. If If the authentication event was successful, or authentication was not attempted because the HTTP header did not contain a supported authentication request, the filter chain will continue as normal. The only time the filter chain will be interrupted is if authentication fails and the `AuthenticationEntryPoint` is called. [[digest-processing-filter]] -==== DigestAuthenticationFilter +=== DigestAuthenticationFilter `DigestAuthenticationFilter` is capable of processing digest authentication credentials presented in HTTP headers. Digest Authentication attempts to solve many of the weaknesses of Basic authentication, specifically by ensuring credentials are never sent in clear text across the wire. Many user agents support Digest Authentication, including FireFox and Internet Explorer. The standard governing HTTP Digest Authentication is defined by RFC 2617, which updates an earlier version of the Digest Authentication standard prescribed by RFC 2069. Most user agents implement RFC 2617. Spring Security's `DigestAuthenticationFilter` is compatible with the "`auth`" quality of protection (`qop`) prescribed by RFC 2617, which also provides backward compatibility with RFC 2069. Digest Authentication is a more attractive option if you need to use unencrypted HTTP (i.e. no TLS/HTTPS) and wish to maximise security of the authentication process. Indeed Digest Authentication is a mandatory requirement for the WebDAV protocol, as noted by RFC 2518 Section 17.1. Digest Authentication is definitely the most secure choice between Form Authentication, Basic Authentication and Digest Authentication, although extra security also means more complex user agent implementations. Central to Digest Authentication is a "nonce". This is a value the server generates. Spring Security's nonce adopts the following format: @@ -2682,7 +2620,7 @@ Because of the more complex implementation of Digest Authentication, there are o [[digest-config]] -===== Configuration +==== Configuration Now that we've reviewed the theory, let's see how to use it. To implement HTTP Digest Authentication, it is necessary to define `DigestAuthenticationFilter` in the filter chain. The application context will need to define the `DigestAuthenticationFilter` and its required collaborators: [source,xml] @@ -2710,18 +2648,18 @@ Digest Authentication's RFC offers a range of additional features to further inc [[remember-me]] -=== Remember-Me Authentication +== Remember-Me Authentication [[remember-me-overview]] -==== Overview +=== Overview Remember-me or persistent-login authentication refers to web sites being able to remember the identity of a principal between sessions. This is typically accomplished by sending a cookie to the browser, with the cookie being detected during future sessions and causing automated login to take place. Spring Security provides the necessary hooks for these operations to take place, and has two concrete remember-me implementations. One uses hashing to preserve the security of cookie-based tokens and the other uses a database or other persistent storage mechanism to store the generated tokens. Note that both implemementations require a `UserDetailsService`. If you are using an authentication provider which doesn't use a `UserDetailsService` (for example, the LDAP provider) then it won't work unless you also have a `UserDetailsService` bean in your application context. [[remember-me-hash-token]] -==== Simple Hash-Based Token Approach +=== Simple Hash-Based Token Approach This approach uses hashing to achieve a useful remember-me strategy. In essence a cookie is sent to the browser upon successful interactive authentication, with the cookie being composed as follows: [source,txt] @@ -2750,7 +2688,7 @@ If you are familiar with the topics discussed in the chapter on <>. `TokenBasedRememberMeServices` generates a `RememberMeAuthenticationToken`, which is processed by `RememberMeAuthenticationProvider`. A `key` is shared between this authentication provider and the `TokenBasedRememberMeServices`. In addition, `TokenBasedRememberMeServices` requires A UserDetailsService from which it can retrieve the username and password for signature comparison purposes, and generate the `RememberMeAuthenticationToken` to contain the correct `GrantedAuthority` s. Some sort of logout command should be provided by the application that invalidates the cookie if the user requests this. `TokenBasedRememberMeServices` also implements Spring Security's `LogoutHandler` interface so can be used with `LogoutFilter` to have the cookie cleared automatically. The beans required in an application context to enable remember-me services are as follows: @@ -2815,7 +2753,7 @@ The beans required in an application context to enable remember-me services are Don't forget to add your `RememberMeServices` implementation to your `UsernamePasswordAuthenticationFilter.setRememberMeServices()` property, include the `RememberMeAuthenticationProvider` in your `AuthenticationManager.setProviders()` list, and add `RememberMeAuthenticationFilter` into your `FilterChainProxy` (typically immediately after your `UsernamePasswordAuthenticationFilter`). -===== PersistentTokenBasedRememberMeServices +==== PersistentTokenBasedRememberMeServices This class can be used in the same way as `TokenBasedRememberMeServices`, but it additionally needs to be configured with a `PersistentTokenRepository` to store the tokens. There are two standard implementations. * `InMemoryTokenRepositoryImpl` which is intended for testing only. @@ -2824,11 +2762,11 @@ This class can be used in the same way as `TokenBasedRememberMeServices`, but it The database schema is described above in <>. [[csrf]] -=== Cross Site Request Forgery (CSRF) +== Cross Site Request Forgery (CSRF) This section discusses Spring Security's http://en.wikipedia.org/wiki/Cross-site_request_forgery[ Cross Site Request Forgery (CSRF)] support. -==== CSRF Attacks +=== CSRF Attacks Before we discuss how Spring Security can protect applications from CSRF attacks, we will explain what a CSRF attack is. Let's take a look at a concrete example to get a better understanding. Assume that your bank's website provides a form that allows transferring money from the currently logged in user to another bank account. For example, the HTTP request might look like: @@ -2867,7 +2805,7 @@ You like to win money, so you click on the submit button. In the process, you ha Worst yet, this whole process could have been automated using JavaScript. This means you didn't even need to click on the button. So how do we protect ourselves from such attacks? -==== Synchronizer Token Pattern +=== Synchronizer Token Pattern The issue is that the HTTP request from the bank's website and the request from the evil website are exactly the same. This means there is no way to reject requests coming from the evil website and allow requests coming from the bank's website. To protect against CSRF attacks we need to ensure there is something in the request that the evil site is unable to provide. One solution is to use the https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#General_Recommendation:_Synchronizer_Token_Pattern[Synchronizer Token Pattern]. This solution is to ensure that each request requires, in addition to our session cookie, a randomly generated token as an HTTP parameter. When a request is submitted, the server must look up the expected value for the parameter and compare it against the actual value in the request. If the values do not match, the request should fail. @@ -2891,12 +2829,12 @@ amount=100.00&routingNumber=1234&account=9876&_csrf= You will notice that we added the _csrf parameter with a random value. Now the evil website will not be able to guess the correct value for the _csrf parameter (which must be explicitly provided on the evil website) and the transfer will fail when the server compares the actual token to the expected token. -==== When to use CSRF protection +=== When to use CSRF protection When you use CSRF protection? Our recommendation is to use CSRF protection for any request that could be processed by a browser by normal users. If you are only creating a service that is used by non-browser clients, you will likely want to disable CSRF protection. -===== CSRF protection and JSON -A common question is, but do I need to protect JSON requests made by javascript? The short answer is, it depends. However, you must be very careful as there are CSRF exploits that can impact JSON requests. For example, a malicious user can create ahttp://blog.opensecurityresearch.com/2012/02/json-csrf-with-parameter-padding.html[CSRF with JSON using the following form]: +==== CSRF protection and JSON +A common question is, but do I need to protect JSON requests made by javascript? The short answer is, it depends. However, you must be very careful as there are CSRF exploits that can impact JSON requests. For example, a malicious user can create a http://blog.opensecurityresearch.com/2012/02/json-csrf-with-parameter-padding.html[CSRF with JSON using the following form]: [source,xml] @@ -2932,7 +2870,7 @@ If an application were not validating the Content-Type, then it would be exposed ---- -===== CSRF and Stateless Browser Applications +==== CSRF and Stateless Browser Applications What if my application is stateless? That doesn't necessarily mean you are protected. In fact, if a user does not need to perform any actions in the web browser for a given request, they are likely still vulnerable to CSRF attacks. For example, consider an application uses a custom cookie that contains all the state within it for authentication instead of the JSESSIONID. When the CSRF attack is made the custom cookie will be sent with the request in the same manner that the JSESSIONID cookie was sent in our previous example. @@ -2940,7 +2878,7 @@ For example, consider an application uses a custom cookie that contains all the User's using basic authentication are also vulnerable to CSRF attacks since the browser will automatically include the username password in any requests in the same manner that the JSESSIONID cookie was sent in our previous example. [[csrf-using]] -==== Using Spring Security CSRF Protection +=== Using Spring Security CSRF Protection So what are the steps necessary to use Spring Security's to protect our site against CSRF attacks? The steps to using Spring Security's CSRF protection are outlined below: * <> @@ -2948,14 +2886,14 @@ So what are the steps necessary to use Spring Security's to protect our site aga * <> [[csrf-use-proper-verbs]] -===== Use proper HTTP verbs +==== Use proper HTTP verbs The first step to protecting against CSRF attacks is to ensure your website uses proper HTTP verbs. Specifically, before Spring Security's CSRF support can be of use, you need to be certain that your application is using PATCH, POST, PUT, and/or DELETE for anything that modifies state. -This is not a limitation of Spring Security's support, but instead a general requirement for proper CSRF prevention. The reason is that including private information in an HTTP GET can cause the information to be leaked. Seehttp://www.w3.org/Protocols/rfc2616/rfc2616-sec15.html#sec15.1.3[RFC 2616 Section 15.1.3 Encoding Sensitive Information in URI's] for general guidance on using POST instead of GET for sensitive information. +This is not a limitation of Spring Security's support, but instead a general requirement for proper CSRF prevention. The reason is that including private information in an HTTP GET can cause the information to be leaked. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec15.html#sec15.1.3[RFC 2616 Section 15.1.3 Encoding Sensitive Information in URI's] for general guidance on using POST instead of GET for sensitive information. [[csrf-configure]] -===== Configure CSRF Protection +==== Configure CSRF Protection The next step is to include Spring Security's CSRF protection within your application. Some frameworks handle invalid CSRF tokens by invaliding the user's session, but this causes <>. Instead by default Spring Security's CSRF protection will produce an HTTP 403 access denied. This can be customized by configuring the <> to process `InvalidCsrfTokenException` differently. For passivity reasons, if you are using the XML configuration, CSRF protection must be explicitly enabled using the <>> element. Refer to the <>> element's documentation for additional customizations. @@ -2991,10 +2929,10 @@ public class WebSecurityConfig extends ---- [[csrf-include-csrf-token]] -===== Include the CSRF Token +==== Include the CSRF Token [[csrf-include-csrf-token-form]] -====== Form Submissions +===== Form Submissions The last step is to ensure that you include the CSRF token in all PATCH, POST, PUT, and DELETE methods. This can be done using the _csrf request attribute to obtain the current CsrfToken. An example of doing this with a JSP is shown below: @@ -3013,11 +2951,11 @@ The last step is to ensure that you include the CSRF token in all PATCH, POST, P [NOTE] ==== -If you are using Spring MVC tag, the `CsrfToken` is automatically included for you using the CsrfRequestDataValueProcessor. +If you are using Spring MVC tag or http://www.thymeleaf.org/whatsnew21.html#reqdata[Thymeleaf 2.1+], the `CsrfToken` is automatically included for you using the `CsrfRequestDataValueProcessor`. ==== [[csrf-include-csrf-token-ajax]] -====== Ajax and JSON Requests +===== Ajax and JSON Requests If you using JSON, then it is not possible to submit the CSRF token within an HTTP parameter. Instead you can submit the token within a HTTP header. A typical pattern would be to include the CSRF token within your meta tags. An example with a JSP is shown below: @@ -3046,7 +2984,7 @@ $(function () { }); ---- -As a alternative to jQuery, we recommend using http://cujojs.com/[cujoJS���s] rest.js. https://github.com/cujojs/rest[rest.js] provides advanced support for working with HTTP request and responses in RESTful ways. A core capability is the ability to contextualize the HTTP client adding behavior as needed by chaining interceptors on to the client. +As a alternative to jQuery, we recommend using http://cujojs.com/[cujoJS's] rest.js. The https://github.com/cujojs/rest[rest.js] module provides advanced support for working with HTTP request and responses in RESTful ways. A core capability is the ability to contextualize the HTTP client adding behavior as needed by chaining interceptors on to the client. [source,javascript] ---- @@ -3061,17 +2999,17 @@ The configured client can be shared with any component of the application that n [[csrf-caveats]] -==== CSRF Caveats +=== CSRF Caveats There are a few caveats when implementing CSRF. [[csrf-timeouts]] -===== Timeouts +==== Timeouts One issue is that the expected CSRF token is stored in the HttpSession, so as soon as the HttpSession expires your configured `AccessDeniedHandler` will receive a InvalidCsrfTokenException. If you are using the default `AccessDeniedHandler`, the browser will get an HTTP 403 and display a poor error message. [NOTE] ==== -One might ask why the expected `CsrfToken` isn't stored in a cookie. This is because there are known exploits in which headers (i.e. specify the cookies) can be set by another domain. This is the same reason Ruby on Railshttp://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails/[no longer skips CSRF checks when the header X-Requested-With is present]. See http://lists.webappsec.org/pipermail/websecurity_lists.webappsec.org/2011-February/007533.html[this webappsec.org thread] for details on how to perform the exploit. Another disadvantage is that by removing the state (i.e. the timeout) you lose the ability to forcibly terminate the token if something got compromised. +One might ask why the expected `CsrfToken` isn't stored in a cookie. This is because there are known exploits in which headers (i.e. specify the cookies) can be set by another domain. This is the same reason Ruby on Rails http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails/[no longer skips CSRF checks when the header X-Requested-With is present]. See http://lists.webappsec.org/pipermail/websecurity_lists.webappsec.org/2011-February/007533.html[this webappsec.org thread] for details on how to perform the exploit. Another disadvantage is that by removing the state (i.e. the timeout) you lose the ability to forcibly terminate the token if something got compromised. ==== A simple way to mitigate an active user experiencing a timeout is to have some JavaScript that lets the user know their session is about to expire. The user can click a button to continue and refresh the session. @@ -3080,19 +3018,19 @@ Alternatively, specifying a custom `AccessDeniedHandler` allows you to process t [[csrf-login]] -===== Logging In +==== Logging In In order to protect against forging log in requests the log in form should be protected against CSRF attacks too. Since the `CsrfToken` is stored in HttpSession, this means an HttpSession will be created as soon as `CsrfToken` token attribute is accessed. While this sounds bad in a RESTful / stateless architecture the reality is that state is necessary to implement practical security. Without state, we have nothing we can do if a token is compromised. Practically speaking, the CSRF token is quite small in size and should have a negligible impact on our architecture. [[csrf-logout]] -===== Logging Out +==== Logging Out Adding CSRF will update the LogoutFilter to only use HTTP POST. This ensures that log out requires a CSRF token and that a malicious user cannot forcibly log out your users. One approach is to use a form for log out. If you really want a link, you can use JavaScript to have the link perform a POST (i.e. maybe on a hidden form). For browsers with JavaScript that is disabled, you can optionally have the link take the user to a log out confirmation page that will perform the POST. [[csrf-multipart]] -===== Multipart (file upload) +==== Multipart (file upload) There are two options to using CSRF protection with multipart/form-data. Each option has its tradeoffs. * <> @@ -3104,7 +3042,7 @@ More information about using multipart forms with Spring can be found within the ==== [[csrf-multipartfilter]] -====== Placing MultipartFilter before Spring Security +===== Placing MultipartFilter before Spring Security The first option is to ensure that the `MultipartFilter` is specified before the Spring Security filter. Specifying the `MultipartFilter` before the Spring Security filter means that there is no authorization for invoking the `MultipartFilter` which means anyone can place temporary files on your server. However, only authorized users will be able to submit a File that is processed by your application. In general, this is the recommended approach because the temporary file upload should have a negligble impact on most servers. To ensure `MultipartFilter` is specified before the Spring Security filter with java configuration, users can override beforeSpringSecurityFilterChain as shown below: @@ -3144,7 +3082,7 @@ To ensure `MultipartFilter` is specified before the Spring Security filter with ---- [[csrf-include-csrf-token-in-action]] -====== Include CSRF token in action +===== Include CSRF token in action If allowing unauthorized users to upload temporariy files is not acceptable, an alternative is to place the `MultipartFilter` after the Spring Security filter and include the CSRF as a query parameter in the action attribute of the form. An example with a jsp is shown below [source,xml] @@ -3154,23 +3092,23 @@ If allowing unauthorized users to upload temporariy files is not acceptable, an The disadvantage to this approach is that query parameters can be leaked. More genearlly, it is considered best practice to place sensitive data within the body or headers to ensure it is not leaked. Additional information can be found in http://www.w3.org/Protocols/rfc2616/rfc2616-sec15.html#sec15.1.3[RFC 2616 Section 15.1.3 Encoding Sensitive Information in URI's]. -===== HiddenHttpMethodFilter +==== HiddenHttpMethodFilter The HiddenHttpMethodFilter should be placed before the Spring Security filter. In general this is true, but it could have additional implications when protecting against CSRF attacks. Note that the HiddenHttpMethodFilter only overrides the HTTP method on a POST, so this is actually unlikely to cause any real problems. However, it is still best practice to ensure it is placed before Spring Security's filters. -==== Overriding Defaults +=== Overriding Defaults Spring Security's goal is to provide defaults that protect your users from exploits. This does not mean that you are forced to accept all of its defaults. For example, you can provide a custom CsrfTokenRepository to override the way in which the `CsrfToken` is stored. -You can also specify a custom RequestMatcher to determine which requests are protected by CSRF (i.e. perhaps you don't care if log out is exploited). In short, if Spring Security's CSRF protection doesn't behave exactly as you want it, you are able to customize the behavior. Refer to the <>> documentation for details on how to make these customizations with XML and the `CsrfConfigurer` javadoc for details on how to make these customizations when using Java configuration. +You can also specify a custom RequestMatcher to determine which requests are protected by CSRF (i.e. perhaps you don't care if log out is exploited). In short, if Spring Security's CSRF protection doesn't behave exactly as you want it, you are able to customize the behavior. Refer to the <> documentation for details on how to make these customizations with XML and the `CsrfConfigurer` javadoc for details on how to make these customizations when using Java configuration. [[headers]] -=== Security HTTP Response Headers +== Security HTTP Response Headers This section discusses Spring Security's support for adding various security headers to the response. -==== Default Security Headers +=== Default Security Headers Spring Security allows users to easily inject the default security headers to assist in protecting their application. The following is a list of the current __Default Security Headers__ provided by Spring Security: * <> @@ -3251,7 +3189,7 @@ public class WebSecurityConfig extends ---- [[headers-cache-control]] -===== Cache Control +==== Cache Control In the past Spring Security required you to provide your own cache control for your web application. This seemed reasonable at the time, but browser caches have evolved to include caches for secure connections as well. This means that a user may view an authenticated page, log out, and then a malicious user can use the browser history to view the cached page. To help mitigate this Spring Security has added cache control support which will insert the following headers into you response. [source] @@ -3315,7 +3253,7 @@ public class WebMvcConfiguration extends WebMvcConfigurerAdapter { ---- [[headers-content-type-options]] -===== Content Type Options +==== Content Type Options Historically browsers, including Internet Explorer, would try to guess the content type of a request using http://en.wikipedia.org/wiki/Content_sniffing[content sniffing]. This allowed browsers to improve the user experience by guessing the content type on resources that had not specified the content type. For example, if a browser encountered a JavaScript file that did not have the content type specified, it would be able to guess the content type and then execute it. [NOTE] @@ -3365,7 +3303,7 @@ public class WebSecurityConfig extends ---- [[headers-hsts]] -===== HTTP Strict Transport Security (HSTS) +==== HTTP Strict Transport Security (HSTS) When you type in your bank's website, do you enter mybank.example.com or do you enter https://mybank.example.com[]? If you omit the https protocol, you are potentially vulnerable to http://en.wikipedia.org/wiki/Man-in-the-middle_attack[Man in the Middle attacks]. Even if the website performs a redirect to https://mybank.example.com a malicious user could intercept the initial HTTP request and manipulate the response (i.e. redirect to https://mibank.example.com and steal their credentials). Many users omit the https protocol and this is why http://tools.ietf.org/html/rfc6797[HTTP Strict Transport Security (HSTS)] was created. Once mybank.example.com is added as a http://tools.ietf.org/html/rfc6797#section-5.1[HSTS host], a browser can know ahead of time that any request to mybank.example.com should be interpreted as https://mybank.example.com. This greatly reduces the possibility of a Man in the Middle attack occurring. @@ -3417,12 +3355,12 @@ public class WebSecurityConfig extends ---- [[headers-frame-options]] -===== X-Frame-Options +==== X-Frame-Options Allowing your website to be added to a frame can be a security issue. For example, using clever CSS styling users could be tricked into clicking on something that they were not intending (http://www.youtube.com/watch?v=3mk0RySeNsU[video demo]). For example, a user that is logged into their bank might click a button that grants access to other users. This sort of attack is known ashttp://en.wikipedia.org/wiki/Clickjacking[Clickjacking]. [NOTE] ==== -Another modern approach to dealing with clickjacking is using a http://www.w3.org/TR/CSP/[Content Security Policy]. Spring Security does not provide support for this as the specification is not released and it is quite a bit more complicated. However, you could use the<> feature to implement this. To stay up to date with this issue and to see how you can implement it with Spring Security refer to https://jira.springsource.org/browse/SEC-2117[SEC-2117] +Another modern approach to dealing with clickjacking is using a http://www.w3.org/TR/CSP/[Content Security Policy]. Spring Security does not provide support for this as the specification is not released and it is quite a bit more complicated. However, you could use the <> feature to implement this. To stay up to date with this issue and to see how you can implement it with Spring Security refer to https://jira.springsource.org/browse/SEC-2117[SEC-2117] ==== There are a number ways to mitigate clickjacking attacks. For example, to protect legacy browsers from clickjacking attacks you can use https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet#Best-for-now_Legacy_Browser_Frame_Breaking_Script[frame breaking code]. While not perfect, the frame breaking code is the best you can do for the legacy browsers. @@ -3469,7 +3407,7 @@ public class WebSecurityConfig extends If you want to change the value for the X-Frame-Options header, then you can use a <>. [[headers-xss-protection]] -===== X-XSS-Protection +==== X-XSS-Protection Some browsers have built in support for filtering out https://www.owasp.org/index.php/Testing_for_Reflected_Cross_site_scripting_(OWASP-DV-001)[reflected XSS attacks]. This is by no means full proof, but does assist in XSS protection. The filtering is typically enabled by default, so adding the header typically just ensures it is enabled and instructs the browser what to do when a XSS attack is detected. For example, the filter might try to change the content in the least invasive way to still render everything. At times, this type of replacement can become a http://hackademix.net/2009/11/21/ies-xss-filter-creates-xss-vulnerabilities/[XSS vulnerability in itself]. Instead, it is best to block the content rather than attempt to fix it. To do this we can add the following header: @@ -3512,11 +3450,11 @@ public class WebSecurityConfig extends ---- [[headers-custom]] -==== Custom Headers +=== Custom Headers Spring Security has mechanisms to make it convenient to add the more common security headers to your application. However, it also provides hooks to enable adding custom headers. [[headers-static]] -===== Static Headers +==== Static Headers There may be times you wish to inject custom security headers into your application that are not supported out of the box. For example, perhaps you wish to have early support for http://www.w3.org/TR/CSP/[Content Security Policy] in order to ensure that resources are only loaded from the same origin. Since support for Content Security Policy has not been finalized, browsers use one of two common extension headers to implement the feature. This means we will need to inject the policy twice. An example of the headers can be seen below: [source] @@ -3560,7 +3498,7 @@ public class WebSecurityConfig extends ---- [[headers-writer]] -===== Headers Writer +==== Headers Writer When the namespace or Java configuration does not support the headers you want, you can create a custom `HeadersWriter` instance or even provide a custom implementation of the `HeadersWriter`. Let's take a look at an example of using an custom instance of `XFrameOptionsHeaderWriter`. Perhaps you want to allow framing of content for the same origin. This is easily supported by setting the <> attribute to "SAMEORIGIN", but let's take a look at a more explicit example using the <> attribute. @@ -3606,7 +3544,7 @@ public class WebSecurityConfig extends [[headers-delegatingrequestmatcherheaderwriter]] -===== DelegatingRequestMatcherHeaderWriter +==== DelegatingRequestMatcherHeaderWriter At times you may want to only write a header for certain requests. For example, perhaps you want to only protect your log in page from being framed. You could use the `DelegatingRequestMatcherHeaderWriter` to do so. When using the XML namespace configuration, this can be done with the following: @@ -3660,11 +3598,11 @@ public class WebSecurityConfig extends [[session-mgmt]] -=== Session Management +== Session Management HTTP session related functonality is handled by a combination of the `SessionManagementFilter` and the `SessionAuthenticationStrategy` interface, which the filter delegates to. Typical usage includes session-fixation protection attack prevention, detection of session timeouts and restrictions on how many sessions an authenticated user may have open concurrently. -==== SessionManagementFilter +=== SessionManagementFilter The `SessionManagementFilter` checks the contents of the `SecurityContextRepository` against the current contents of the `SecurityContextHolder` to determine whether a user has been authenticated during the current request, typically by a non-interactive authentication mechanism, such as pre-authentication or remember-me footnote:[ Authentication by mechanisms which perform a redirect after authenticating (such as form-login) will not be detected by`SessionManagementFilter`, as the filter will not be invoked during the authenticating request. Session-management functionality has to be handled separately in these cases. ]. If the repository contains a security context, the filter does nothing. If it doesn't, and the thread-local `SecurityContext` contains a (non-anonymous) `Authentication` object, the filter assumes they have been authenticated by a previous filter in the stack. It will then invoke the configured `SessionAuthenticationStrategy`. @@ -3672,7 +3610,7 @@ Authentication by mechanisms which perform a redirect after authenticating (such If the user is not currently authenticated, the filter will check whether an invalid session ID has been requested (because of a timeout, for example) and will invoke the configured`InvalidSessionStrategy`, if one is set. The most common behaviour is just to redirect to a fixed URL and this is encapsulated in the standard implementation`SimpleRedirectInvalidSessionStrategy`. The latter is also used when configuring an invalid session URL through the namespace,<>. -==== SessionAuthenticationStrategy +=== SessionAuthenticationStrategy `SessionAuthenticationStrategy` is used by both `SessionManagementFilter` and `AbstractAuthenticationProcessingFilter`, so if you are using a customized form-login class, for example, you will need to inject it into both of these. In this case, a typical configuration, combining the namespace and custom beans might look like this: [source,xml] @@ -3694,12 +3632,10 @@ If the user is not currently authenticated, the filter will check whether an inv ---- - - Note that the use of the default, `SessionFixationProtectionStrategy` may cause issues if you are storing beans in the session which implement `HttpSessionBindingListener`, including Spring session-scoped beans. See the Javadoc for this class for more information. - +Note that the use of the default, `SessionFixationProtectionStrategy` may cause issues if you are storing beans in the session which implement `HttpSessionBindingListener`, including Spring session-scoped beans. See the Javadoc for this class for more information. [[concurrent-sessions]] -==== Concurrency Control +=== Concurrency Control Spring 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. You can either expire their previous login or you can report an error when they try to log in again, preventing the second login. Note that if you are using the second approach, a user who has not explicitly logged out (but who has just closed their browser, for example) will not be able to log in again until their original session expires. Concurrency control is supported by the namespace, so please check the earlier namespace chapter for the simplest configuration. Sometimes you need to customize things though. @@ -3779,18 +3715,18 @@ Adding the listener to `web.xml` causes an `ApplicationEvent` to be published to [[list-authenticated-principals]] -===== Querying the SessionRegistry for currently authenticated users and their sessions +==== Querying the SessionRegistry for currently authenticated users and their sessions Setting up concurrency-control, either through the namespace or using plain beans has the useful side effect of providing you with a reference to the `SessionRegistry` which you can use directly within your application, so even if you don't want to restrict the number of sessions a user may have, it may be worth setting up the infrastructure anyway. You can set the `maximumSession` property to -1 to allow unlimited sessions. If you're using the namespace, you can set an alias for the internally-created `SessionRegistry` using the `session-registry-alias` attribute, providing a reference which you can inject into your own beans. The `getAllPrincipals()` method supplies you with a list of the currently authenticated users. You can list a user's sessions by calling the `getAllSessions(Object principal, boolean includeExpiredSessions)` method, which returns a list of `SessionInformation` objects. You can also expire a user's session by calling `expireNow()` on a `SessionInformation` instance. When the user returns to the application, they will be prevented from proceeding. You may find these methods useful in an administration application, for example. Have a look at the Javadoc for more information. [[anonymous]] -=== Anonymous Authentication +== Anonymous Authentication [[anonymous-overview]] -==== Overview +=== Overview It's generally considered good security practice to adopt a "deny-by-default" where you explicitly specify what is allowed and disallow everything else. Defining what is accessible to unauthenticated users is a similar situation, particularly for web applications. Many sites require that users must be authenticated for anything other than a few URLs (for example the home and login pages). In this case it is easiest to define access configuration attributes for these specific URLs rather than have for every secured resource. Put differently, sometimes it is nice to say `ROLE_SOMETHING` is required by default and only allow certain exceptions to this rule, such as for login, logout and home pages of an application. You could also omit these pages from the filter chain entirely, thus bypassing the access control checks, but this may be undesirable for other reasons, particularly if the pages behave differently for authenticated users. This is what we mean by anonymous authentication. Note that there is no real conceptual difference between a user who is "anonymously authenticated" and an unauthenticated user. Spring Security's anonymous authentication just gives you a more convenient way to configure your access-control attributes. Calls to servlet API calls such as `getCallerPrincipal`, for example, will still return null even though there is actually an anonymous authentication object in the `SecurityContextHolder`. @@ -3799,7 +3735,7 @@ There are other situations where anonymous authentication is useful, such as whe [[anonymous-config]] -==== Configuration +=== Configuration Anonymous authentication support is provided automatically when using the HTTP configuration Spring Security 3.0 and can be customized (or disabled) using the `` element. You don't need to configure the beans described here unless you are using traditional bean configuration. Three classes that together provide the anonymous authentication feature. `AnonymousAuthenticationToken` is an implementation of `Authentication`, and stores the `GrantedAuthority` s which apply to the anonymous principal. There is a corresponding `AnonymousAuthenticationProvider`, which is chained into the `ProviderManager` so that `AnonymousAuthenticationToken` s are accepted. Finally, there is an `AnonymousAuthenticationFilter`, which is chained after the normal authentication mechanisms and automatically adds an `AnonymousAuthenticationToken` to the `SecurityContextHolder` if there is no existing `Authentication` held there. The definition of the filter and authentication provider appears as follows: @@ -3854,25 +3790,25 @@ As explained earlier, the benefit of anonymous authentication is that all URI pa [[anonymous-auth-trust-resolver]] -==== AuthenticationTrustResolver +=== AuthenticationTrustResolver Rounding out the anonymous authentication discussion is the `AuthenticationTrustResolver` interface, with its corresponding `AuthenticationTrustResolverImpl` implementation. This interface provides an `isAnonymous(Authentication)` method, which allows interested classes to take into account this special type of authentication status. The `ExceptionTranslationFilter` uses this interface in processing `AccessDeniedException` s. If an `AccessDeniedException` is thrown, and the authentication is of an anonymous type, instead of throwing a 403 (forbidden) response, the filter will instead commence the `AuthenticationEntryPoint` so the principal can authenticate properly. This is a necessary distinction, otherwise principals would always be deemed "authenticated" and never be given an opportunity to login via form, basic, digest or some other normal authentication mechanism. You will often see the `ROLE_ANONYMOUS` attribute in the above interceptor configuration replaced with `IS_AUTHENTICATED_ANONYMOUSLY`, which is effectively the same thing when defining access controls. This is an example of the use of the `AuthenticatedVoter` which we will see in the <>. It uses an `AuthenticationTrustResolver` to process this particular configuration attribute and grant access to anonymous users. the `AuthenticatedVoter` approach is more powerful, since it allows you to differentiate between anonymous, remember-me and fully-authenticated users. If you don't need this functionality though, then you can stick with `ROLE_ANONYMOUS`, which will be processed by Spring Security's standard `RoleVoter`. [[authorization]] -== Authorization += Authorization The advanced authorization capabilities within Spring Security represent one of the most compelling reasons for its popularity. Irrespective of how you choose to authenticate - whether using a Spring Security-provided mechanism and provider, or integrating with a container or other non-Spring Security authentication authority - you will find the authorization services can be used within your application in a consistent and simple way. In this part we'll explore the different `AbstractSecurityInterceptor` implementations, which were introduced in Part I. We then move on to explore how to fine-tune authorization through use of domain access control lists. [[authz-arch]] -=== Authorization Architecture +== Authorization Architecture [[authz-authorities]] -==== Authorities +=== Authorities As we saw in the <>, all `Authentication` implementations store a list of `GrantedAuthority` objects. These represent the authorities that have been granted to the principal. the `GrantedAuthority` objects are inserted into the `Authentication` object by the `AuthenticationManager` and are later read by `AccessDecisionManager` s when making authorization decisions. `GrantedAuthority` is an interface with only one method: @@ -3893,12 +3829,12 @@ Spring Security includes one concrete `GrantedAuthority` implementation, `Grante [[authz-pre-invocation]] -==== Pre-Invocation Handling +=== Pre-Invocation Handling As we've also seen in the <> chapter, Spring Security provides interceptors which control access to secure objects such as method invocations or web requests. A pre-invocation decision on whether the invocation is allowed to proceed is made by the `AccessDecisionManager`. [[authz-access-decision-manager]] -===== The AccessDecisionManager +==== The AccessDecisionManager The `AccessDecisionManager` is called by the `AbstractSecurityInterceptor` and is responsible for making final access control decisions. the `AccessDecisionManager` interface contains three methods: [source,java] @@ -3916,7 +3852,7 @@ The `AccessDecisionManager`'s `decide` method is passed all the relevant informa The `supports(ConfigAttribute)` method is called by the `AbstractSecurityInterceptor` at startup time to determine if the `AccessDecisionManager` can process the passed `ConfigAttribute`. The `supports(Class)` method is called by a security interceptor implementation to ensure the configured `AccessDecisionManager` supports the type of secure object that the security interceptor will present. [[authz-voting-based]] -===== Voting-Based AccessDecisionManager ImplementationsVoting Decision Manager +==== Voting-Based AccessDecisionManager Implementations Whilst users can implement their own `AccessDecisionManager` to control all aspects of authorization, Spring Security includes several `AccessDecisionManager` implementations that are based on voting. <> illustrates the relevant classes. [[authz-access-voting]] @@ -3946,26 +3882,26 @@ It is possible to implement a custom `AccessDecisionManager` that tallies votes [[authz-role-voter]] -====== RoleVoter +===== RoleVoter The most commonly used `AccessDecisionVoter` provided with Spring Security is the simple `RoleVoter`, which treats configuration attributes as simple role names and votes to grant access if the user has been assigned that role. It will vote if any `ConfigAttribute` begins with the prefix `ROLE_`. It will vote to grant access if there is a `GrantedAuthority` which returns a `String` representation (via the `getAuthority()` method) exactly equal to one or more `ConfigAttributes` starting with the prefix `ROLE_`. If there is no exact match of any `ConfigAttribute` starting with `ROLE_`, the `RoleVoter` will vote to deny access. If no `ConfigAttribute` begins with `ROLE_`, the voter will abstain. [[authz-authenticated-voter]] -====== AuthenticatedVoter +===== AuthenticatedVoter Another voter which we've implicitly seen is the `AuthenticatedVoter`, which can be used to differentiate between anonymous, fully-authenticated and remember-me authenticated users. Many sites allow certain limited access under remember-me authentication, but require a user to confirm their identity by logging in for full access. When we've used the attribute `IS_AUTHENTICATED_ANONYMOUSLY` to grant anonymous access, this attribute was being processed by the `AuthenticatedVoter`. See the Javadoc for this class for more information. [[authz-custom-voter]] -====== Custom Voters +===== Custom Voters Obviously, you can also implement a custom `AccessDecisionVoter` and you can put just about any access-control logic you want in it. It might be specific to your application (business-logic related) or it might implement some security administration logic. For example, you'll find a http://blog.springsource.com/2009/01/02/spring-security-customization-part-2-adjusting-secured-session-in-real-time/[ blog article] on the SpringSource web site which describes how to use a voter to deny access in real-time to users whose accounts have been suspended. [[authz-after-invocation-handling]] -==== After Invocation Handling +=== After Invocation Handling Whilst the `AccessDecisionManager` is called by the `AbstractSecurityInterceptor` before proceeding with the secure object invocation, some applications need a way of modifying the object actually returned by the secure object invocation. Whilst you could easily implement your own AOP concern to achieve this, Spring Security provides a convenient hook that has several concrete implementations that integrate with its ACL capabilities. <> illustrates Spring Security's `AfterInvocationManager` and its concrete implementations. @@ -3980,7 +3916,7 @@ Please be aware that if you're using `AfterInvocationManager`, you will still ne [[authz-hierarchical-roles]] -==== Hierarchical Roles +=== Hierarchical Roles It is a common requirement that a particular role in an application should automatically "include" other roles. For example, in an application which has the concept of an "admin" and a "user" role, you may want an admin to be able to do everything a normal user can. To achieve this, you can either make sure that all admin users are also assigned the "user" role. Alternatively, you can modify every access constraint which requires the "user" role to also include the "admin" role. This can get quite complicated if you have a lot of different roles in your application. The use of a role-hierarchy allows you to configure which roles (or authorities) should include others. An extended version of Spring Security's <>, `RoleHierarchyVoter`, is configured with a `RoleHierarchy`, from which it obtains all the "reachable authorities" which the user is assigned. A typical configuration might look like this: @@ -4008,15 +3944,15 @@ Here we have four roles in a hierarchy `ROLE_ADMIN => ROLE_STAFF => ROLE_USER => Role hierarchies offer a convenient means of simplifying the access-control configuration data for your application and/or reducing the number of authorities which you need to assign to a user. For more complex requirements you may wish to define a logical mapping between the specific access-rights your application requires and the roles that are assigned to users, translating between the two when loading the user information. [[secure-object-impls]] -=== Secure Object Implementations +== Secure Object Implementations [[aop-alliance]] -==== AOP Alliance (MethodInvocation) Security Interceptor +=== AOP Alliance (MethodInvocation) Security Interceptor Prior to Spring Security 2.0, securing `MethodInvocation` s needed quite a lot of boiler plate configuration. Now the recommended approach for method security is to use <>. This way the method security infrastructure beans are configured automatically for you so you don't really need to know about the implementation classes. We'll just provide a quick overview of the classes that are involved here. Method security in enforced using a `MethodSecurityInterceptor`, which secures `MethodInvocation` s. Depending on the configuration approach, an interceptor may be specific to a single bean or shared between multiple beans. The interceptor uses a `MethodSecurityMetadataSource` instance to obtain the configuration attributes that apply to a particular method invocation. `MapBasedMethodSecurityMetadataSource` is used to store configuration attributes keyed by method names (which can be wildcarded) and will be used internally when the attributes are defined in the application context using the `` or `` elements. Other implementations will be used to handle annotation-based configuration. -===== Explicit MethodSecurityInterceptor Configuration +==== Explicit MethodSecurityInterceptor Configuration You can of course configure a `MethodSecurityIterceptor` directly in your application context for use with one of Spring AOP's proxying mechanisms: [source,xml] @@ -4037,7 +3973,7 @@ You can of course configure a `MethodSecurityIterceptor` directly in your applic ---- [[aspectj]] -==== AspectJ (JoinPoint) Security Interceptor +=== AspectJ (JoinPoint) Security Interceptor The AspectJ security interceptor is very similar to the AOP Alliance security interceptor discussed in the previous section. Indeed we will only discuss the differences in this section. The AspectJ interceptor is named `AspectJSecurityInterceptor`. Unlike the AOP Alliance security interceptor, which relies on the Spring application context to weave in the security interceptor via proxying, the `AspectJSecurityInterceptor` is weaved in via the AspectJ compiler. It would not be uncommon to use both types of security interceptors in the same application, with `AspectJSecurityInterceptor` being used for domain object instance security and the AOP Alliance `MethodSecurityInterceptor` being used for services layer security. @@ -4135,16 +4071,16 @@ That's it! Now you can create your beans from anywhere within your application, [[el-access]] -=== Expression-Based Access Control +== Expression-Based Access Control Spring Security 3.0 introduced the ability to use Spring EL expressions as an authorization mechanism in addition to the simple use of configuration attributes and access-decision voters which have seen before. Expression-based access control is built on the same architecture but allows complicated boolean logic to be encapsulated in a single expression. -==== Overview +=== Overview Spring Security uses Spring EL for expression support and you should look at how that works if you are interested in understanding the topic in more depth. Expressions are evaluated with a "root object" as part of the evaluation context. Spring Security uses specific classes for web and method security as the root object, in order to provide built-in expressions and access to values such as the current principal. [[el-common-built-in]] -===== Common Built-In ExpressionsCommon built-in expressions +==== Common Built-In Expressions The base class for expression root objects is `SecurityExpressionRoot`. This provides some common expressions which are available in both web and method security. [[common-expressions]] @@ -4186,7 +4122,7 @@ The base class for expression root objects is `SecurityExpressionRoot`. This pro [[el-access-web]] -==== Web Security Expressions +=== Web Security Expressions To use expressions to secure individual URLs, you would first need to set the `use-expressions` attribute in the `` element to `true`. Spring Security will then expect the `access` attributes of the `` elements to contain Spring EL expressions. The expressions should evaluate to a boolean, defining whether access should be allowed or not. For example: [source,xml] @@ -4204,12 +4140,12 @@ Here we have defined that the "admin" area of an application (defined by the URL If expressions are being used, a `WebExpressionVoter` will be added to the `AccessDecisionManager` which is used by the namespace. So if you aren't using the namespace and want to use expressions, you will have to add one of these to your configuration. -==== Method Security Expressions +=== Method Security Expressions Method security is a bit more complicated than a simple allow or deny rule. Spring Security 3.0 introduced some new annotations in order to allow comprehensive support for the use of expressions. [[el-pre-post-annotations]] -===== @Pre and @Post Annotations +==== @Pre and @Post Annotations There are four annotations which support expression attributes to allow pre and post-invocation authorization checks and also to support filtering of submitted collection arguments or return values. They are `@PreAuthorize`, `@PreFilter`, `@PostAuthorize` and `@PostFilter`. Their use is enabled through the `global-method-security` namespace element: [source,xml] @@ -4217,7 +4153,7 @@ There are four annotations which support expression attributes to allow pre and ---- -====== Access Control using @PreAuthorize and @PostAuthorize +===== Access Control using @PreAuthorize and @PostAuthorize The most obviously useful annotation is `@PreAuthorize` which decides whether a method can actually be invoked or not. For example (from the"Contacts" sample application) [source,java] @@ -4226,12 +4162,7 @@ The most obviously useful annotation is `@PreAuthorize` which decides whether a public void create(Contact contact); ---- -which means that access will only be allowed for users with the role "ROLE_USER". - - -[[el-pre-post-annotations-arguments]] -* **Resolving method arguments** -Obviously the same thing could easily be achieved using a traditional configuration and a simple configuration attribute for the required role. But what about: +which means that access will only be allowed for users with the role "ROLE_USER". Obviously the same thing could easily be achieved using a traditional configuration and a simple configuration attribute for the required role. But what about: [source,java] ---- @@ -4283,10 +4214,10 @@ Behind the scenes this use implemented using `AnnotationParameterNameDiscoverer` * Last, if the code was compiled with the debug symbols, the parameter names will be discovered using the debug symbols. This will not work for interfaces since they do not have debug information about the parameter names. For interfaces, annotations or the JDK 8 approach must be used. -[[el-pre-post-annotations-spel]] -* **Method Expressions and SpEL** +.[[el-pre-post-annotations-spel]] +-- Any Spring-EL functionality is available within the expression, so you can also access properties on the arguments. For example, if you wanted a particular method to only allow access to a user whose username matched that of the contact, you could write - +-- [source,java] ---- @@ -4294,15 +4225,14 @@ Any Spring-EL functionality is available within the expression, so you can also public void doSomething(Contact contact); ---- -Here we are accessing another built���in expression, `authentication`, which is the `Authentication` stored in the security context. You can also access its "principal" property directly, using the expression `principal`. The value will often be a `UserDetails` instance, so you might use an expression like `principal.username` or `principal.enabled`. +Here we are accessing another built-in expression, `authentication`, which is the `Authentication` stored in the security context. You can also access its "principal" property directly, using the expression `principal`. The value will often be a `UserDetails` instance, so you might use an expression like `principal.username` or `principal.enabled`. -[[el-pre-post-annotations-post]] -* **Accessing the return value** -Less commonly, you may wish to perform an access-control check after the method has been invoked. This can be achieved using the `@PostAuthorize` annotation. To access the return value from a method, use the built���in name `returnObject` in the expression. +.[[el-pre-post-annotations-post]] +-- +Less commonly, you may wish to perform an access-control check after the method has been invoked. This can be achieved using the `@PostAuthorize` annotation. To access the return value from a method, use the built-in name `returnObject` in the expression. +-- - -====== Filtering using -`@PreFilter` and `@PostFilter` +===== Filtering using @PreFilter and @PostFilter As you may already be aware, Spring Security supports filtering of collections and arrays and this can now be achieved using expressions. This is most commonly performed on the return value of a method. For example: [source,java] @@ -4318,12 +4248,12 @@ Note that filtering is obviously not a substitute for tuning your data retrieval [[el-method-built-in]] -===== Built-In Expressions +==== Built-In Expressions There are some built-in expressions which are specific to method security, which we have already seen in use above. The `filterTarget` and `returnValue` values are simple enough, but the use of the `hasPermission()` expression warrants a closer look. [[el-permission-evaluator]] -====== The PermissionEvaluator interface +===== The PermissionEvaluator interface `hasPermission()` expressions are delegated to an instance of `PermissionEvaluator`. It is intended to bridge between the expression system and Spring Security's ACL system, allowing you to specify authorization constraints on domain objects, based on abstract permissions. It has no explicit dependencies on the ACL module, so you could swap that out for an alternative implementation if required. The interface has two methods: [source,java] @@ -4354,14 +4284,14 @@ To use `hasPermission()` expressions, you have to explicitly configure a `Permis Where `myPermissionEvaluator` is the bean which implements `PermissionEvaluator`. Usually this will be the implementation from the ACL module which is called`AclPermissionEvaluator`. See the "Contacts" sample application configuration for more details. [[advanced-topics]] -== Additional Topics += Additional Topics In this part we cover features which require a knowledge of previous chapters as well as some of the more advanced and less-commonly used features of the framework. [[domain-acls]] -=== Domain Object Security (ACLs) +== Domain Object Security (ACLs) [[domain-acls-overview]] -==== Overview +=== Overview Complex applications often will find the need to define access permissions not simply at a web request or method invocation level. Instead, security decisions need to comprise both who (`Authentication`), where (`MethodInvocation`) and what (`SomeDomainObject`). In other words, authorization decisions also need to consider the actual domain object instance subject of a method invocation. Imagine you're designing an application for a pet clinic. There will be two main groups of users of your Spring-based application: staff of the pet clinic, as well as the pet clinic's customers. The staff will have access to all of the data, whilst your customers will only be able to see their own customer records. To make it a little more interesting, your customers can allow other users to see their customer records, such as their "puppy preschool" mentor or president of their local "Pony Club". Using Spring Security as the foundation, you have several approaches that can be used: @@ -4377,7 +4307,7 @@ Fortunately, there is another alternative, which we'll talk about below. [[domain-acls-key-concepts]] -==== Key Concepts +=== Key Concepts Spring Security's ACL services are shipped in the `spring-security-acl-xxx.jar`. You will need to add this JAR to your classpath to use Spring Security's domain object instance security capabilities. Spring Security's domain object instance security capabilities centre on the concept of an access control list (ACL). Every domain object instance in your system has its own ACL, and the ACL records details of who can and can't work with that domain object. With this in mind, Spring Security delivers three main ACL-related capabilities to your application: @@ -4432,7 +4362,7 @@ Two samples ship with Spring Security that demonstrate the ACL module. The first [[domain-acls-getting-started]] -==== Getting Started +=== Getting Started To get starting using Spring Security's ACL capability, you will need to store your ACL information somewhere. This necessitates the instantiation of a `DataSource` using Spring. The `DataSource` is then injected into a `JdbcMutableAclService` and `BasicLookupStrategy` instance. The latter provides high-performance ACL retrieval capabilities, and the former provides mutator capabilities. Refer to one of the samples that ship with Spring Security for an example configuration. You'll also need to populate the database with the four ACL-specific tables listed in the last section (refer to the ACL samples for the appropriate SQL statements). Once you've created the required schema and instantiated `JdbcMutableAclService`, you'll next need to ensure your domain model supports interoperability with the Spring Security ACL package. Hopefully `ObjectIdentityImpl` will prove sufficient, as it provides a large number of ways in which it can be used. Most people will have domain objects that contain a `public Serializable getId()` method. If the return type is long, or compatible with long (eg an int), you will find you need not give further consideration to `ObjectIdentity` issues. Many parts of the ACL module rely on long identifiers. If you're not using long (or an int, byte etc), there is a very good chance you'll need to reimplement a number of classes. We do not intend to support non-long identifiers in Spring Security's ACL module, as longs are already compatible with all database sequences, the most common identifier data type, and are of sufficient length to accommodate all common usage scenarios. @@ -4469,8 +4399,8 @@ Once you've used the above techniques to store some ACL information in the datab [[preauth]] -=== Pre-Authentication Scenarios -There are situations where you want to use Spring Security for authorization, but the user has already been reliably authenticated by some external system prior to accessing the application. We refer to these situations as "pre-authenticated" scenarios. Examples include X.509, Siteminder and authentication by the J2EE container in which the application is running. When using pre-authentication, Spring Security has to +== Pre-Authentication Scenarios +There are situations where you want to use Spring Security for authorization, but the user has already been reliably authenticated by some external system prior to accessing the application. We refer to these situations as "pre-authenticated" scenarios. Examples include X.509, Siteminder and authentication by the Java EE container in which the application is running. When using pre-authentication, Spring Security has to * Identify the user making the request. @@ -4480,11 +4410,11 @@ There are situations where you want to use Spring Security for authorization, bu The details will depend on the external authentication mechanism. A user might be identified by their certificate information in the case of X.509, or by an HTTP request header in the case of Siteminder. If relying on container authentication, the user will be identified by calling the `getUserPrincipal()` method on the incoming HTTP request. In some cases, the external mechanism may supply role/authority information for the user but in others the authorities must be obtained from a separate source, such as a `UserDetailsService`. -==== Pre-Authentication Framework Classes +=== Pre-Authentication Framework Classes Because most pre-authentication mechanisms follow the same pattern, Spring Security has a set of classes which provide an internal framework for implementing pre-authenticated authentication providers. This removes duplication and allows new implementations to be added in a structured fashion, without having to write everything from scratch. You don't need to know about these classes if you want to use something like <>, as it already has a namespace configuration option which is simpler to use and get started with. If you need to use explicit bean configuration or are planning on writing your own implementation then an understanding of how the provided implementations work will be useful. You will find classes under the `org.springframework.security.web.authentication.preauth`. We just provide an outline here so you should consult the Javadoc and source where appropriate. -===== AbstractPreAuthenticatedProcessingFilter +==== AbstractPreAuthenticatedProcessingFilter This class will check the current contents of the security context and, if empty, it will attempt to extract user information from the HTTP request and submit it to the `AuthenticationManager`. Subclasses override the following methods to obtain this information: [source,java] @@ -4501,13 +4431,13 @@ Like other Spring Security authentication filters, the pre-authentication filter [[j2ee-preauth-details]] -====== J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource +===== J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource If the filter is configured with an `authenticationDetailsSource` which is an instance of this class, the authority information is obtained by calling the `isUserInRole(String role)` method for each of a pre-determined set of "mappable roles". The class gets these from a configured `MappableAttributesRetriever`. Possible implementations include hard-coding a list in the application context and reading the role information from the `` information in a `web.xml` file. The pre-authentication sample application uses the latter approach. There is an additional stage where the roles (or attributes) are mapped to Spring Security `GrantedAuthority` objects using a configured `Attributes2GrantedAuthoritiesMapper`. The default will just add the usual `ROLE_` prefix to the names, but it gives you full control over the behaviour. -===== PreAuthenticatedAuthenticationProvider +==== PreAuthenticatedAuthenticationProvider The pre-authenticated provider has little more to do than load the `UserDetails` object for the user. It does this by delegating to a `AuthenticationUserDetailsService`. The latter is similar to the standard `UserDetailsService` but takes an `Authentication` object rather than just user name: [source,java] @@ -4519,15 +4449,15 @@ public interface AuthenticationUserDetailsService { This interface may have also other uses but with pre-authentication it allows access to the authorities which were packaged in the `Authentication` object, as we saw in the previous section. the `PreAuthenticatedGrantedAuthoritiesUserDetailsService` class does this. Alternatively, it may delegate to a standard `UserDetailsService` via the `UserDetailsByNameServiceWrapper` implementation. -===== Http403ForbiddenEntryPoint +==== Http403ForbiddenEntryPoint The `AuthenticationEntryPoint` was discussed in the <> chapter. Normally it is responsible for kick-starting the authentication process for an unauthenticated user (when they try to access a protected resource), but in the pre-authenticated case this doesn't apply. You would only configure the `ExceptionTranslationFilter` with an instance of this class if you aren't using pre-authentication in combination with other authentication mechanisms. It will be called if the user is rejected by the `AbstractPreAuthenticatedProcessingFilter` resulting in a null authentication. It always returns a `403`-forbidden response code if called. -==== Concrete Implementations +=== Concrete Implementations X.509 authentication is covered in its <>. Here we'll look at some classes which provide support for other pre-authenticated scenarios. -===== Request-Header Authentication (Siteminder) +==== Request-Header Authentication (Siteminder) An external authentication system may supply information to the application by setting specific headers on the HTTP request. A well known example of this is Siteminder, which passes the username in a header called `SM_USER`. This mechanism is supported by the class `RequestHeaderAuthenticationFilter` which simply extracts the username from the header. It defaults to using the name `SM_USER` as the header name. See the Javadoc for more details. [TIP] @@ -4535,7 +4465,7 @@ An external authentication system may supply information to the application by s Note that when using a system like this, the framework performs no authentication checks at all and it is __extremely__ important that the external system is configured properly and protects all access to the application. If an attacker is able to forge the headers in their original request without this being detected then they could potentially choose any username they wished. ==== -====== Siteminder Example Configuration +===== Siteminder Example Configuration A typical configuration using this filter would look like this: [source,xml] @@ -4567,18 +4497,18 @@ A typical configuration using this filter would look like this: We've assumed here that the <> is being used for configuration. It's also assumed that you have added a `UserDetailsService` (called "userDetailsService") to your configuration to load the user's roles. -===== J2EE Container Authentication -The class `J2eePreAuthenticatedProcessingFilter` will extract the username from the `userPrincipal` property of the `HttpServletRequest`. Use of this filter would usually be combined with the use of J2EE roles as described above in <>. +==== Java EE Container Authentication +The class `J2eePreAuthenticatedProcessingFilter` will extract the username from the `userPrincipal` property of the `HttpServletRequest`. Use of this filter would usually be combined with the use of Java EE roles as described above in <>. There is a sample application in the codebase which uses this approach, so get hold of the code from subversion and have a look at the application context file if you are interested. The code is in the `samples/preauth` directory. [[ldap]] -=== LDAP Authentication +== LDAP Authentication [[ldap-overview]] -==== Overview +=== Overview LDAP is often used by organizations as a central repository for user information and as an authentication service. It can also be used to store the role information for application users. There are many different scenarios for how an LDAP server may be configured so Spring Security's LDAP provider is fully configurable. It uses separate strategy interfaces for authentication and role retrieval and provides default implementations which can be configured to handle a wide range of situations. @@ -4587,7 +4517,7 @@ You should be familiar with LDAP before trying to use it with Spring Security. T When using LDAP authentication, it is important to ensure that you configure LDAP connection pooling properly. If you are unfamiliar with how to do this, you can refer to the http://docs.oracle.com/javase/jndi/tutorial/ldap/connect/config.html[Java LDAP documentation]. -==== Using LDAP with Spring Security +=== Using LDAP with Spring Security LDAP authentication in Spring Security can be roughly divided into the following stages. * Obtaining the unique LDAP "Distinguished Name", or DN, from the login name. This will often mean performing a search in the directory, unless the exact mapping of usernames to DNs is known in advance. So a user might enter the name "joe" when logging in, but the actual name used to authenticate to LDAP will be the full DN, such as`uid=joe,ou=users,dc=springsource,dc=com`. @@ -4602,7 +4532,7 @@ We will look at some configuration scenarios below. For full information on avai [[ldap-server]] -==== Configuring an LDAP Server +=== Configuring an LDAP Server The first thing you need to do is configure the server against which authentication should take place. This is done using the `` element from the security namespace. This can be configured to point at an external LDAP server, using the `url` attribute: [source,xml] @@ -4610,7 +4540,7 @@ The first thing you need to do is configure the server against which authenticat ---- -===== Using an Embedded Test Server +==== Using an Embedded Test Server The `` element can also be used to create an embedded server, which can be very useful for testing and demonstrations. In this case you use it without the `url` attribute: [source,xml] @@ -4627,7 +4557,7 @@ Here we've specified that the root DIT of the directory should be "dc=springfram This makes it a lot easier to get up and running with LDAP, since it can be inconvenient to work all the time with an external server. It also insulates the user from the complex bean configuration needed to wire up an Apache Directory server. Using plain Spring Beans the configuration would be much more cluttered. You must have the necessary Apache Directory dependency jars available for your application to use. These can be obtained from the LDAP sample application. -===== Using Bind Authentication +==== Using Bind Authentication This is the most common LDAP authentication scenario. [source,xml] @@ -4645,7 +4575,7 @@ This simple example would obtain the DN for the user by substituting the user lo If used with the server definition above, this would perform a search under the DN `ou=people,dc=springframework,dc=org` using the value of the `user-search-filter` attribute as a filter. Again the user login name is substituted for the parameter in the filter name, so it will search for an entry with the `uid` attribute equal to the user name. If `user-search-base` isn't supplied, the search will be performed from the root. -===== Loading Authorities +==== Loading Authorities How authorities are loaded from groups in the LDAP directory is controlled by the following attributes. * `group-search-base`. Defines the part of the directory tree under which group searches should be performed. @@ -4662,14 +4592,14 @@ So if we used the following configuration and authenticated successfully as user "ben", the subsequent loading of authorities would perform a search under the directory entry`ou=groups,dc=springframework,dc=org`, looking for entries which contain the attribute `uniqueMember` with value `uid=ben,ou=people,dc=springframework,dc=org`. By default the authority names will have the prefix `ROLE_` prepended. You can change this using the `role-prefix` attribute. If you don't want any prefix, use `role-prefix="none"`. For more information on loading authorities, see the Javadoc for the `DefaultLdapAuthoritiesPopulator` class. -==== Implementation Classes +=== Implementation Classes The namespace configuration options we've used above are simple to use and much more concise than using Spring beans explicitly. There are situations when you may need to know how to configure Spring Security LDAP directly in your application context. You may wish to customize the behaviour of some of the classes, for example. If you're happy using namespace configuration then you can skip this section and the next one. The main LDAP provider class, `LdapAuthenticationProvider`, doesn't actually do much itself but delegates the work to two other beans, an `LdapAuthenticator` and an `LdapAuthoritiesPopulator` which are responsible for authenticating the user and retrieving the user's set of `GrantedAuthority` s respectively. [[ldap-ldap-authenticators]] -===== LdapAuthenticator Implementations +==== LdapAuthenticator Implementations The authenticator is also responsible for retrieving any required user attributes. This is because the permissions on the attributes may depend on the type of authentication being used. For example, if binding as the user, it may be necessary to read them with the user's own permissions. There are currently two authentication strategies supplied with Spring Security: @@ -4679,43 +4609,43 @@ There are currently two authentication strategies supplied with Spring Security: * Password comparison, where the password supplied by the user is compared with the one stored in the repository. This can either be done by retrieving the value of the password attribute and checking it locally or by performing an LDAP "compare" operation, where the supplied password is passed to the server for comparison and the real password value is never retrieved. [[ldap-ldap-authenticators-common]] -====== Common Functionality +===== Common Functionality Before it is possible to authenticate a user (by either strategy), the distinguished name (DN) has to be obtained from the login name supplied to the application. This can be done either by simple pattern-matching (by setting the `setUserDnPatterns` array property) or by setting the `userSearch` property. For the DN pattern-matching approach, a standard Java pattern format is used, and the login name will be substituted for the parameter `{0}`. The pattern should be relative to the DN that the configured `SpringSecurityContextSource` will bind to (see the section on <> for more information on this). For example, if you are using an LDAP server with the URL`ldap://monkeymachine.co.uk/dc=springframework,dc=org`, and have a pattern `uid={0},ou=greatapes`, then a login name of "gorilla" will map to a DN`uid=gorilla,ou=greatapes,dc=springframework,dc=org`. Each configured DN pattern will be tried in turn until a match is found. For information on using a search, see the section on <> below. A combination of the two approaches can also be used - the patterns will be checked first and if no matching DN is found, the search will be used. [[ldap-ldap-authenticators-bind]] -====== BindAuthenticator +===== BindAuthenticator The class `BindAuthenticator` in the package `org.springframework.security.ldap.authentication` implements the bind authentication strategy. It simply attempts to bind as the user. [[ldap-ldap-authenticators-password]] -====== PasswordComparisonAuthenticator +===== PasswordComparisonAuthenticator The class `PasswordComparisonAuthenticator` implements the password comparison authentication strategy. [[ldap-context-source]] -===== Connecting to the LDAP Server +==== Connecting to the LDAP Server The beans discussed above have to be able to connect to the server. They both have to be supplied with a `SpringSecurityContextSource` which is an extension of Spring LDAP's `ContextSource`. Unless you have special requirements, you will usually configure a `DefaultSpringSecurityContextSource` bean, which can be configured with the URL of your LDAP server and optionally with the username and password of a "manager" user which will be used by default when binding to the server (instead of binding anonymously). For more information read the Javadoc for this class and for Spring LDAP's `AbstractContextSource`. [[ldap-searchobjects]] -===== LDAP Search Objects +==== LDAP Search Objects Often a more complicated strategy than simple DN-matching is required to locate a user entry in the directory. This can be encapsulated in an `LdapUserSearch` instance which can be supplied to the authenticator implementations, for example, to allow them to locate a user. The supplied implementation is `FilterBasedLdapUserSearch`. [[ldap-searchobjects-filter]] -====== FilterBasedLdapUserSearch +===== FilterBasedLdapUserSearch This bean uses an LDAP filter to match the user object in the directory. The process is explained in the Javadoc for the corresponding search method on thehttp://java.sun.com/j2se/1.4.2/docs/api/javax/naming/directory/DirContext.html#search(javax.naming.Name,%20java.lang.String,%20java.lang.Object[],%20javax.naming.directory.SearchControls)[JDK DirContext class]. As explained there, the search filter can be supplied with parameters. For this class, the only valid parameter is `{0}` which will be replaced with the user's login name. [[ldap-authorities]] -===== LdapAuthoritiesPopulator +==== LdapAuthoritiesPopulator After authenticating the user successfully, the `LdapAuthenticationProvider` will attempt to load a set of authorities for the user by calling the configured `LdapAuthoritiesPopulator` bean. The `DefaultLdapAuthoritiesPopulator` is an implementation which will load the authorities by searching the directory for groups of which the user is a member (typically these will be `groupOfNames` or `groupOfUniqueNames` entries in the directory). Consult the Javadoc for this class for more details on how it works. If you want to use LDAP only for authentication, but load the authorities from a difference source (such as a database) then you can provide your own implementation of this interface and inject that instead. [[ldap-bean-config]] -===== Spring Bean Configuration +==== Spring Bean Configuration A typical configuration, using some of the beans we've discussed here, might look like this: [source,xml] @@ -4767,7 +4697,7 @@ and use it by setting the `BindAuthenticator` bean's `userSearch` property. The [[ldap-custom-user-details]] -===== LDAP Attributes and Customized UserDetails +==== LDAP Attributes and Customized UserDetails The net result of an authentication using `LdapAuthenticationProvider` is the same as a normal Spring Security authentication using the standard `UserDetailsService` interface. A `UserDetails` object is created and stored in the returned `Authentication` object. As with using a `UserDetailsService`, a common requirement is to be able to customize this implementation and add extra properties. When using LDAP, these will normally be attributes from the user entry. The creation of the `UserDetails` object is controlled by the provider's `UserDetailsContextMapper` strategy, which is responsible for mapping user objects to and from LDAP context data: [source,java] @@ -4787,11 +4717,11 @@ The way the context data is loaded varies slightly depending on the type of auth [[ldap-active-directory]] -==== Active Directory Authentication +=== Active Directory Authentication Active Directory supports its own non-standard authentication options, and the normal usage pattern doesn't fit too cleanly with the standard `LdapAuthenticationProvider`. Typically authentication is performed using the domain username (in the form `user@domain`), rather than using an LDAP distinguished name. To make this easier, Spring Security 3.1 has an authentication provider which is customized for a typical Active Directory setup. -===== ActiveDirectoryLdapAuthenticationProvider +==== ActiveDirectoryLdapAuthenticationProvider Configuring `ActiveDirectoryLdapAuthenticationProvider` is quite straightforward. You just need to supply the domain name and an LDAP URL supplying the address of the server footnote:[It is also possible to obtain the server's IP address using a DNS lookup. This is not currently supported, but hopefully will be in a future version.]. An example configuration would then look like this: [source,xml] @@ -4809,16 +4739,16 @@ Note that there is no need to specify a separate `ContextSource` in order to def By default, the user authorities are obtained from the `memberOf` attribute values of the user entry. The authorities allocated to the user can again be customized using a `UserDetailsContextMapper`. You can also inject a `GrantedAuthoritiesMapper` into the provider instance to control the authorities which end up in the `Authentication` object. -====== Active Directory Error Codes +===== Active Directory Error Codes By default, a failed result will cause a standard Spring Security `BadCredentialsException`. If you set the property `convertSubErrorCodesToExceptions` to `true`, the exception messages will be parsed to attempt to extract the Active Directory-specific error code and raise a more specific exception. Check the class Javadoc for more information. [[taglibs]] -=== JSP Tag Libraries +== JSP Tag Libraries Spring Security has its own taglib which provides basic support for accessing security information and applying security constraints in JSPs. -==== Declaring the Taglib +=== Declaring the Taglib To use any of the tags, you must have the security taglib declared in your JSP: [source,xml] @@ -4826,7 +4756,7 @@ To use any of the tags, you must have the security taglib declared in your JSP: <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> ---- -==== The authorize Tag +=== The authorize Tag This tag is used to determine whether its contents should be evaluated or not. In Spring Security 3.0, it can be used in two ways footnote:[ The legacy options from Spring Security 2.0 are also supported, but discouraged. ]. The first approach uses a <>, specified in the `access` attribute of the tag. The expression evaluation will be delegated to the `SecurityExpressionHandler` defined in the application context (you should have web expressions enabled in your `` namespace configuration to make sure this service is available). So, for example, you might have @@ -4856,19 +4786,19 @@ To use this tag there must also be an instance of `WebInvocationPrivilegeEvaluat The boolean result of evaluating the tag (whether it grants or denies access) can be stored in a page context scope variable by setting the `var` attribute to the variable name, avoiding the need for duplicating and re-evaluating the condition at other points in the page. -===== Disabling Tag Authorization for Testing +==== Disabling Tag Authorization for Testing Hiding a link in a page for unauthorized users doesn't prevent them from accessing the URL. They could just type it into their browser directly, for example. As part of your testing process, you may want to reveal the hidden areas in order to check that links really are secured at the back end. If you set the system property `spring.security.disableUISecurity` to `true`, the `authorize` tag will still run but will not hide its contents. By default it will also surround the content with `...` tags. This allows you to display "hidden" content with a particular CSS style such as a different background colour. Try running the "tutorial" sample application with this property enabled, for example. You can also set the properties `spring.security.securedUIPrefix` and `spring.security.securedUISuffix` if you want to change surrounding text from the default `span` tags (or use empty strings to remove it completely). -==== The authentication Tag +=== The authentication Tag This tag allows access to the current `Authentication` object stored in the security context. It renders a property of the object directly in the JSP. So, for example, if the `principal` property of the `Authentication` is an instance of Spring Security's `UserDetails` object, then using `` will render the name of the current user. Of course, it isn't necessary to use JSP tags for this kind of thing and some people prefer to keep as little logic as possible in the view. You can access the `Authentication` object in your MVC controller (by calling `SecurityContextHolder.getContext().getAuthentication()`) and add the data directly to your model for rendering by the view. -==== The accesscontrollist Tag +=== The accesscontrollist Tag This tag is only valid when used with Spring Security's ACL module. It checks a comma-separated list of required permissions for a specified domain object. If the current user has any of those permissions, then the tag body will be evaluated. If they don't, it will be skipped. An example might be [source,xml] @@ -4886,50 +4816,50 @@ This tag also supports the `var` attribute, in the same way as the `authorize` t [[jaas]] -=== Java Authentication and Authorization Service (JAAS) Provider +== Java Authentication and Authorization Service (JAAS) Provider -==== Overview +=== Overview Spring Security provides a package able to delegate authentication requests to the Java Authentication and Authorization Service (JAAS). This package is discussed in detail below. [[jaas-abstractjaasauthenticationprovider]] -==== AbstractJaasAuthenticationProvider +=== AbstractJaasAuthenticationProvider The `AbstractJaasAuthenticationProvider` is the basis for the provided JAAS `AuthenticationProvider` implementations. Subclasses must implement a method that creates the `LoginContext`. The `AbstractJaasAuthenticationProvider` has a number of dependencies that can be injected into it that are discussed below. [[jaas-callbackhandler]] -===== JAAS CallbackHandler +==== JAAS CallbackHandler Most JAAS `LoginModule` s require a callback of some sort. These callbacks are usually used to obtain the username and password from the user. In a Spring Security deployment, Spring Security is responsible for this user interaction (via the authentication mechanism). Thus, by the time the authentication request is delegated through to JAAS, Spring Security's authentication mechanism will already have fully-populated an `Authentication` object containing all the information required by the JAAS `LoginModule`. Therefore, the JAAS package for Spring Security provides two default callback handlers, `JaasNameCallbackHandler` and `JaasPasswordCallbackHandler`. Each of these callback handlers implement `JaasAuthenticationCallbackHandler`. In most cases these callback handlers can simply be used without understanding the internal mechanics. -For those needing full control over the callback behavior, internally `AbstractJaasAuthenticationProvider` wraps these `JaasAuthenticationCallbackHandler` s with an `InternalCallbackHandler`. The `InternalCallbackHandler` is the class that actually implements JAAS��� normal `CallbackHandler` interface. Any time that the JAAS `LoginModule` is used, it is passed a list of application context configured `InternalCallbackHandler` s. If the `LoginModule` requests a callback against the `InternalCallbackHandler` s, the callback is in-turn passed to the `JaasAuthenticationCallbackHandler` s being wrapped. +For those needing full control over the callback behavior, internally `AbstractJaasAuthenticationProvider` wraps these `JaasAuthenticationCallbackHandler` s with an `InternalCallbackHandler`. The `InternalCallbackHandler` is the class that actually implements JAAS normal `CallbackHandler` interface. Any time that the JAAS `LoginModule` is used, it is passed a list of application context configured `InternalCallbackHandler` s. If the `LoginModule` requests a callback against the `InternalCallbackHandler` s, the callback is in-turn passed to the `JaasAuthenticationCallbackHandler` s being wrapped. [[jaas-authoritygranter]] -===== JAAS AuthorityGranter +==== JAAS AuthorityGranter JAAS works with principals. Even "roles" are represented as principals in JAAS. Spring Security, on the other hand, works with `Authentication` objects. Each `Authentication` object contains a single principal, and multiple `GrantedAuthority` s. To facilitate mapping between these different concepts, Spring Security's JAAS package includes an `AuthorityGranter` interface. -An `AuthorityGranter` is responsible for inspecting a JAAS principal and returning a set of `String` s, representing the authorities assigned to the principal. For each returned authority string, the `AbstractJaasAuthenticationProvider` creates a `JaasGrantedAuthority` (which implements Spring Security���s `GrantedAuthority` interface) containing the authority string and the JAAS principal that the `AuthorityGranter` was passed. The `AbstractJaasAuthenticationProvider` obtains the JAAS principals by firstly successfully authenticating the user���s credentials using the JAAS `LoginModule`, and then accessing the `LoginContext` it returns. A call to `LoginContext.getSubject().getPrincipals()` is made, with each resulting principal passed to each `AuthorityGranter` defined against the `AbstractJaasAuthenticationProvider.setAuthorityGranters(List)` property. +An `AuthorityGranter` is responsible for inspecting a JAAS principal and returning a set of `String` s, representing the authorities assigned to the principal. For each returned authority string, the `AbstractJaasAuthenticationProvider` creates a `JaasGrantedAuthority` (which implements Spring Security's `GrantedAuthority` interface) containing the authority string and the JAAS principal that the `AuthorityGranter` was passed. The `AbstractJaasAuthenticationProvider` obtains the JAAS principals by firstly successfully authenticating the user's credentials using the JAAS `LoginModule`, and then accessing the `LoginContext` it returns. A call to `LoginContext.getSubject().getPrincipals()` is made, with each resulting principal passed to each `AuthorityGranter` defined against the `AbstractJaasAuthenticationProvider.setAuthorityGranters(List)` property. Spring Security does not include any production `AuthorityGranter` s given that every JAAS principal has an implementation-specific meaning. However, there is a `TestAuthorityGranter` in the unit tests that demonstrates a simple `AuthorityGranter` implementation. [[jaas-defaultjaasauthenticationprovider]] -==== DefaultJaasAuthenticationProvider +=== DefaultJaasAuthenticationProvider The `DefaultJaasAuthenticationProvider` allows a JAAS `Configuration` object to be injected into it as a dependency. It then creates a `LoginContext` using the injected JAAS `Configuration`. This means that `DefaultJaasAuthenticationProvider` is not bound any particular implementation of `Configuration` as `JaasAuthenticationProvider` is. [[jaas-inmemoryconfiguration]] -===== InMemoryConfiguration +==== InMemoryConfiguration In order to make it easy to inject a `Configuration` into `DefaultJaasAuthenticationProvider`, a default in memory implementation named `InMemoryConfiguration` is provided. The implementation constructor accepts a `Map` where each key represents a login configuration name and the value represents an `Array` of `AppConfigurationEntry` s. `InMemoryConfiguration` also supports a default `Array` of `AppConfigurationEntry` objects that will be used if no mapping is found within the provided `Map`. For details, refer to the class level javadoc of `InMemoryConfiguration`. [[jaas-djap-config]] -===== DefaultJaasAuthenticationProvider Example Configuration +==== DefaultJaasAuthenticationProvider Example Configuration While the Spring configuration for `InMemoryConfiguration` can be more verbose than the standarad JAAS configuration files, using it in conjuction with `DefaultJaasAuthenticationProvider` is more flexible than `JaasAuthenticationProvider` since it not dependant on the default `Configuration` implementation. An example configuration of `DefaultJaasAuthenticationProvider` using `InMemoryConfiguration` is provided below. Note that custom implementations of `Configuration` can easily be injected into `DefaultJaasAuthenticationProvider` as well. @@ -4979,10 +4909,10 @@ An example configuration of `DefaultJaasAuthenticationProvider` using `InMemoryC [[jaas-jaasauthenticationprovider]] -==== JaasAuthenticationProvider +=== JaasAuthenticationProvider The `JaasAuthenticationProvider` assumes the default `Configuration` is an instance of http://download.oracle.com/javase/1.4.2/docs/guide/security/jaas/spec/com/sun/security/auth/login/ConfigFile.html[ ConfigFile]. This assumption is made in order to attempt to update the `Configuration`. The `JaasAuthenticationProvider` then uses the default `Configuration` to create the `LoginContext`. -Let���s assume we have a JAAS login configuration file, `/WEB-INF/login.conf`, with the following contents: +Let's assume we have a JAAS login configuration file, `/WEB-INF/login.conf`, with the following contents: [source,txt] ---- @@ -5017,7 +4947,7 @@ Like all Spring Security beans, the `JaasAuthenticationProvider` is configured v ---- [[jaas-apiprovision]] -==== Running as a Subject +=== Running as a Subject If configured, the `JaasApiIntegrationFilter` will attempt to run as the `Subject` on the `JaasAuthenticationToken`. This means that the `Subject` can be accessed using: [source,java] @@ -5028,16 +4958,16 @@ Subject subject = Subject.getSubject(AccessController.getContext()); This integration can easily be configured using the <> attribute. This feature is useful when integrating with legacy or external API's that rely on the JAAS Subject being populated. [[cas]] -=== CAS Authentication +== CAS Authentication [[cas-overview]] -==== Overview +=== Overview JA-SIG produces an enterprise-wide single sign on system known as CAS. Unlike other initiatives, JA-SIG's Central Authentication Service is open source, widely used, simple to understand, platform independent, and supports proxy capabilities. Spring Security fully supports CAS, and provides an easy migration path from single-application deployments of Spring Security through to multiple-application deployments secured by an enterprise-wide CAS server. You can learn more about CAS at http://www.ja-sig.org/cas. You will also need to visit this site to download the CAS Server files. [[cas-how-it-works]] -==== How CAS Works +=== How CAS Works Whilst the CAS web site contains documents that detail the architecture of CAS, we present the general overview again here within the context of Spring Security. Spring Security 3.x supports CAS 3. At the time of writing, the CAS server was at version 3.4. Somewhere in your enterprise you will need to setup a CAS server. The CAS server is simply a standard WAR file, so there isn't anything difficult about setting up your server. Inside the WAR file you will customise the login and other single sign on pages displayed to users. @@ -5048,7 +4978,7 @@ Apart from the CAS server itself, the other key players are of course the secure [[cas-sequence]] -===== Spring Security and CAS Interaction Sequence +==== Spring Security and CAS Interaction Sequence The basic interaction between a web browser, CAS server and a Spring Security-secured service is as follows: * The web user is browsing the service's public pages. CAS or Spring Security is not involved. @@ -5072,12 +5002,12 @@ The basic interaction between a web browser, CAS server and a Spring Security-se It's good that you're still here! Let's now look at how this is configured [[cas-client]] -==== Configuration of CAS Client +=== Configuration of CAS Client The web application side of CAS is made easy due to Spring Security. It is assumed you already know the basics of using Spring Security, so these are not covered again below. We'll assume a namespace based configuration is being used and add in the CAS beans as required. Each section builds upon the previous section. A full<> can be found in the Spring Security Samples. [[cas-st]] -===== Service Ticket Authentication +==== Service Ticket Authentication This section describes how to setup Spring Security to authenticate Service Tickets. Often times this is all a web application requires. You will need to add a `ServiceProperties` bean to your application context. This represents your CAS service: [source,xml] @@ -5155,7 +5085,7 @@ This completes the most basic configuration for CAS. If you haven't made any mis [[cas-singlelogout]] -===== Single Logout +==== Single Logout The CAS protocol supports Single Logout and can be easily added to your Spring Security configuration. Below are updates to the Spring Security configuration that handle Single Logout [source,xml] @@ -5222,12 +5152,12 @@ When using the SingleSignOutFilter you might encounter some encoding issues. The [[cas-pt-client]] -===== Authenticating to a Stateless Service with CAS +==== Authenticating to a Stateless Service with CAS This section describes how to authenticate to a service using CAS. In other words, this section discusses how to setup a client that uses a service that authenticates with CAS. The next section describes how to setup a stateless service to Authenticate using CAS. [[cas-pt-client-config]] -====== Configuring CAS to Obtain Proxy Granting Tickets +===== Configuring CAS to Obtain Proxy Granting Tickets In order to authenticate to a stateless service, the application needs to obtain a proxy granting ticket (PGT). This section describes how to configure Spring Security to obtain a PGT building upon thencas-st[Service Ticket Authentication] configuration. The first step is to include a `ProxyGrantingTicketStorage` in your Spring Security configuration. This is used to store PGT's that are obtained by the `CasAuthenticationFilter` so that they can be used to obtain proxy tickets. An example configuration is shown below @@ -5275,7 +5205,7 @@ The last step is to update the `CasAuthenticationFilter` to accept PGT and to st ---- [[cas-pt-client-sample]] -====== Calling a Stateless Service Using a Proxy Ticket +===== Calling a Stateless Service Using a Proxy Ticket Now that Spring Security obtains PGTs, you can use them to create proxy tickets which can be used to authenticate to a stateless service. The <> contains a working example in the `ProxyTicketSampleServlet`. Example code can be found below: [source,java] @@ -5297,7 +5227,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) ---- [[cas-pt]] -===== Proxy Ticket Authentication +==== Proxy Ticket Authentication The `CasAuthenticationProvider` distinguishes between stateful and stateless clients. A stateful client is considered any that submits to the `filterProcessUrl` of the `CasAuthenticationFilter`. A stateless client is any that presents an authentication request to `CasAuthenticationFilter` on a URL other than the `filterProcessUrl`. Because remoting protocols have no way of presenting themselves within the context of an `HttpSession`, it isn't possible to rely on the default practice of storing the security context in the session between requests. Furthermore, because the CAS server invalidates a ticket after it has been validated by the `TicketValidator`, presenting the same proxy ticket on subsequent requests will not work. @@ -5363,11 +5293,11 @@ You will also need to update the `CasAuthenticationProvider` to handle proxy tic ---- [[x509]] -=== X.509 Authentication +== X.509 Authentication [[x509-overview]] -==== Overview +=== Overview The most common use of X.509 certificate authentication is in verifying the identity of a server when using SSL, most commonly when using HTTPS from a browser. The browser will automatically check that the certificate presented by a server has been issued (ie digitally signed) by one of a list of trusted certificate authorities which it maintains. You can also use SSL with "mutual authentication"; the server will then request a valid certificate from the client as part of the SSL handshake. The server will authenticate the client by checking that its certificate is signed by an acceptable authority. If a valid certificate has been provided, it can be obtained through the servlet API in an application. Spring Security X.509 module extracts the certificate using a filter. It maps the certificate to an application user and loads that user's set of granted authorities for use with the standard Spring Security infrastructure. @@ -5375,7 +5305,7 @@ You can also use SSL with "mutual authentication"; the server will then request You should be familiar with using certificates and setting up client authentication for your servlet container before attempting to use it with Spring Security. Most of the work is in creating and installing suitable certificates and keys. For example, if you're using Tomcat then read the instructions here http://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html[http://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html]. It's important that you get this working before trying it out with Spring Security -==== Adding X.509 Authentication to Your Web Application +=== Adding X.509 Authentication to Your Web Application Enabling X.509 client authentication is very straightforward. Just add the `` element to your http security namespace configuration. [source,xml] @@ -5391,10 +5321,10 @@ The element has two optional attributes: * `subject-principal-regex`. The regular expression used to extract a username from the certificate's subject name. The default value is shown above. This is the username which will be passed to the `UserDetailsService` to load the authorities for the user. * `user-service-ref`. This is the bean Id of the `UserDetailsService` to be used with X.509. It isn't needed if there is only one defined in your application context. - The `subject-principal-regex` should contain a single group. For example the default expression "CN=(.*?)," matches the common name field. So if the subject name in the certificate is "CN=Jimi Hendrix, OU=...", this will give a user name of "Jimi Hendrix". The matches are case insensitive. So "emailAddress=(.?)," will match "EMAILADDRESS=jimi@hendrix.org,CN=..." giving a user name "jimi@hendrix.org". If the client presents a certificate and a valid username is successfully extracted, then there should be a valid `Authentication` object in the security context. If no certificate is found, or no corresponding user could be found then the security context will remain empty. This means that you can easily use X.509 authentication with other options such as a form-based login. +The `subject-principal-regex` should contain a single group. For example the default expression "CN=(.*?)," matches the common name field. So if the subject name in the certificate is "CN=Jimi Hendrix, OU=...", this will give a user name of "Jimi Hendrix". The matches are case insensitive. So "emailAddress=(.?)," will match "EMAILADDRESS=jimi@hendrix.org,CN=..." giving a user name "jimi@hendrix.org". If the client presents a certificate and a valid username is successfully extracted, then there should be a valid `Authentication` object in the security context. If no certificate is found, or no corresponding user could be found then the security context will remain empty. This means that you can easily use X.509 authentication with other options such as a form-based login. [[x509-ssl-config]] -==== Setting up SSL in Tomcat +=== Setting up SSL in Tomcat There are some pre-generated certificates in the `samples/certificate` directory in the Spring Security project. You can use these to enable SSL for testing if you don't want to generate your own. The file `server.jks` contains the server certificate, private key and the issuing certificate authority certificate. There are also some client certificate files for the users from the sample applications. You can install these in your browser to enable SSL client authentication. To run tomcat with SSL support, drop the `server.jks` file into the tomcat `conf` directory and add the following connector to the `server.xml` file @@ -5416,16 +5346,16 @@ To run tomcat with SSL support, drop the `server.jks` file into the tomcat `conf [[runas]] -=== Run-As Authentication Replacement +== Run-As Authentication Replacement [[runas-overview]] -==== Overview +=== Overview The `AbstractSecurityInterceptor` is able to temporarily replace the `Authentication` object in the `SecurityContext` and `SecurityContextHolder` during the secure object callback phase. This only occurs if the original `Authentication` object was successfully processed by the `AuthenticationManager` and `AccessDecisionManager`. The `RunAsManager` will indicate the replacement `Authentication` object, if any, that should be used during the `SecurityInterceptorCallback`. By temporarily replacing the `Authentication` object during the secure object callback phase, the secured invocation will be able to call other objects which require different authentication and authorization credentials. It will also be able to perform any internal security checks for specific `GrantedAuthority` objects. Because Spring Security provides a number of helper classes that automatically configure remoting protocols based on the contents of the `SecurityContextHolder`, these run-as replacements are particularly useful when calling remote web services [[runas-config]] -==== Configuration +=== Configuration A `RunAsManager` interface is provided by Spring Security: [source,java] @@ -5468,20 +5398,20 @@ By using the same key, each `RunAsUserToken` can be validated it was created by [[crypto]] -=== Spring Security Crypto Module +== Spring Security Crypto Module [[spring-security-crypto-introduction]] -==== Introduction +=== Introduction The Spring Security Crypto module provides support for symmetric encryption, key generation, and password encoding. The code is distributed as part of the core module but has no dependencies on any other Spring Security (or Spring) code. [[spring-security-crypto-encryption]] -==== Encryptors +=== Encryptors The Encryptors class provides factory methods for constructing symmetric encryptors. Using this class, you can create ByteEncryptors to encrypt data in raw byte[] form. You can also construct TextEncryptors to encrypt text strings. Encryptors are thread safe. [[spring-security-crypto-encryption-bytes]] -===== BytesEncryptor +==== BytesEncryptor Use the Encryptors.standard factory method to construct a "standard" BytesEncryptor: [source,java] @@ -5499,7 +5429,7 @@ String salt = KeyGenerators.string().generateKey(); // generates a random 8-byte ---- [[spring-security-crypto-encryption-text]] -===== TextEncryptor +==== TextEncryptor Use the Encryptors.text factory method to construct a standard TextEncryptor: [source,java] @@ -5520,10 +5450,10 @@ Encryptors.queryableText("password", "salt"); The difference between a queryable TextEncryptor and a standard TextEncryptor has to do with initialization vector (iv) handling. The iv used in a queryable TextEncryptor#encrypt operation is shared, or constant, and is not randomly generated. This means the same text encrypted multiple times will always produce the same encryption result. This is less secure, but necessary for encrypted data that needs to be queried against. An example of queryable encrypted text would be an OAuth apiKey. [[spring-security-crypto-keygenerators]] -==== Key Generators +=== Key Generators The KeyGenerators class provides a number of convenience factory methods for constructing different types of key generators. Using this class, you can create a BytesKeyGenerator to generate byte[] keys. You can also construct a StringKeyGenerator to generate string keys. KeyGenerators are thread safe. -===== BytesKeyGenerator +==== BytesKeyGenerator Use the KeyGenerators.secureRandom factory methods to generate a BytesKeyGenerator backed by a SecureRandom instance: [source,java] @@ -5546,7 +5476,7 @@ Use the KeyGenerators.shared factory method to construct a BytesKeyGenerator tha KeyGenerators.shared(16); ---- -===== StringKeyGenerator +==== StringKeyGenerator Use the KeyGenerators.string factory method to construct a 8-byte, SecureRandom KeyGenerator that hex-encodes each key as a String: [source,java] @@ -5555,7 +5485,7 @@ KeyGenerators.string(); ---- [[spring-security-crypto-passwordencoders]] -==== Password Encoding +=== Password Encoding The password package of the spring-security-crypto module provides support for encoding passwords. `PasswordEncoder` is the central service interface and has the following signature: [source,java] @@ -5582,11 +5512,11 @@ assertTrue(encoder.matches("myPassword", result)); ---- [[concurrency]] -=== Concurrency Support +== Concurrency Support In most environments, Security is stored on a per `Thread` basis. This means that when work is done on a new `Thread`, the `SecurityContext` is lost. Spring Security provides some infrastructure to help make this much easier for users. Spring Security provides low level abstractions for working with Spring Security in multi threaded environments. In fact, this is what Spring Security builds on to integration with <> and <>. -==== DelegatingSecurityContextRunnable +=== DelegatingSecurityContextRunnable One of the most fundamental building blocks within Spring Security's concurrency support is the `DelegatingSecurityContextRunnable`. It wraps a delegate `Runnable` in order to initialize the `SecurityContextHolder` with a specified `SecurityContext` for the delegate. It then invokes the delegate Runnable ensuring to clear the `SecurityContextHolder` afterwards. The `DelegatingSecurityContextRunnable` looks something like this: @@ -5645,7 +5575,7 @@ new Thread(wrappedRunnable).start(); The code we have is simple to use, but it still requires knowledge that we are using Spring Security. In the next section we will take a look at how we can utilize `DelegatingSecurityContextExecutor` to hide the fact that we are using Spring Security. -==== DelegatingSecurityContextExecutor +=== DelegatingSecurityContextExecutor In the previous section we found that it was easy to use the `DelegatingSecurityContextRunnable`, but it was not ideal since we had to be aware of Spring Security in order to use it. Let's take a look at how `DelegatingSecurityContextExecutor` can shield our code from any knowledge that we are using Spring Security. @@ -5707,7 +5637,7 @@ DelegatingSecurityContextExecutor executor = Now anytime `executor.execute(Runnable)` is executed the `SecurityContext` is first obtained by the `SecurityContextHolder` and then that `SecurityContext` is used to create our `DelegatingSecurityContextRunnable`. This means that we are executing our `Runnable` with the same user that was used to invoke the `executor.execute(Runnable)` code. -==== Spring Security Concurrency Classes +=== Spring Security Concurrency Classes Refer to the Javadoc for additional integrations with both the Java concurrent APIs and the Spring Task abstractions. They are quite self explanatory once you understand the previous code. @@ -5721,12 +5651,12 @@ Refer to the Javadoc for additional integrations with both the Java concurrent A * DelegatingSecurityContextTaskExecutor [[mvc]] -=== Spring MVC Integration +== Spring MVC Integration Spring Security provides a number of optional integrations with Spring MVC. This section covers the integration in further detail. [[mvc-authentication-principal]] -==== @AuthenticationPrincipal +=== @AuthenticationPrincipal Spring Security provides ability to automatically resolve the current `Authentication.getPrincipal()` for Spring MVC arguments. This means that you can be entirely decoupled from Spring Security in your Spring MVC layer. @@ -5785,7 +5715,7 @@ public ModelAndView findMessagesForUser(@CurrentUser CustomUser customUser) { [[mvc-async]] -==== Spring MVC Async Integration +=== Spring MVC Async Integration Spring Web MVC 3.2+ has excellent support for http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-async[Asynchronous Request Processing]. With no additional configuration, Spring Security will automatically setup the `SecurityContext` to the `Thread` that executes a `Callable` returned by your controllers. For example, the following method will automatically have its `Callable` executed with the `SecurityContext` that was available when the `Callable` was created: @@ -5812,7 +5742,7 @@ More technically speaking, Spring Security integrates with `WebAsyncManager`. Th There is no automatic integration with a `DeferredResult` that is returned by controllers. This is because `DeferredResult` is processed by the users and thus there is no way of automatically integrating with it. However, you can still use <> to provide transparent integration with Spring Security. [[mvc-csrf]] -==== Spring MVC and CSRF Integration +=== Spring MVC and CSRF Integration Spring Security will automatically <> within forms that use the http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/view.html#view-jsp-formtaglib-formtag[Spring MVC form tag]. For example, the following JSP: @@ -5854,16 +5784,16 @@ Will output HTML that is similar to the following: ---- -== Appendix += Appendix [[appendix-schema]] -=== Security Database Schema +== Security Database Schema There are various database schema used by the framework and this appendix provides a single reference point to them all. You only need to provide the tables for the areas of functonality you require. DDL statements are given for the HSQLDB database. You can use these as a guideline for defining the schema for the database you are using. -==== User Schema +=== User Schema The standard JDBC implementation of the `UserDetailsService` (`JdbcDaoImpl`) requires tables to load the password, account status (enabled or disabled) and a list of authorities (roles) for the user. [source] @@ -5881,7 +5811,7 @@ create table authorities ( create unique index ix_auth_username on authorities (username,authority); ---- -===== Group Authorities +==== Group Authorities Spring Security 2.0 introduced support for group authorities in `JdbcDaoImpl`. The table structure if groups are enabled is as follows: [source] @@ -5906,7 +5836,7 @@ create table group_members ( Remember that these tables are only required if you are using the provided JDBC `UserDetailsService` implementation. If you write your own or choose to implement `AuthenticationProvider` without a `UserDetailsService`, then you have complete freedom over how you store the data, as long as the interface contract is satisfied. -==== Persistent Login (Remember-Me) Schema +=== Persistent Login (Remember-Me) Schema This table is used to store data used by the more secure <> remember-me implementation. If you are using `JdbcTokenRepositoryImpl` either directly or through the namespace, then you will need this table. [source] @@ -5921,7 +5851,7 @@ create table persistent_logins ( ---- [[dbschema-acl]] -==== ACL Schema +=== ACL Schema There are four tables used by the Spring Security <> implementation. . `acl_sid` stores the security identities recognised by the ACL system. These can be unique principals or authorities which may apply to multiple principals. @@ -5931,7 +5861,7 @@ There are four tables used by the Spring Security <> implementa It is assumed that the database will auto-generate the primary keys for each of the identities. The `JdbcMutableAclService` has to be able to retrieve these when it has created a new row in the `acl_sid` or `acl_class` tables. It has two properties which define the SQL needed to retrieve these values `classIdentityQuery` and `sidIdentityQuery`. Both of these default to `call identity()` -===== Hypersonic SQL +==== Hypersonic SQL The default schema works with the embedded HSQLDB database that is used in unit tests within the framework. [source] @@ -5971,7 +5901,7 @@ create table acl_entry ( constraint foreign_fk_5 foreign key(sid) references acl_sid(id) ); ---- -===== PostgreSQL +==== PostgreSQL [source,ddl] ---- create table acl_sid( @@ -6018,18 +5948,18 @@ You will have to set the `classIdentityQuery` and `sidIdentityQuery` properties * `select currval(pg_get_serial_sequence('acl_sid', 'id'))` [[appendix-namespace]] -=== The Security Namespace +== The Security Namespace This appendix provides a reference to the elements available in the security namespace and information on the underlying beans they create (a knowledge of the individual classes and how they work together is assumed - you can find more information in the project Javadoc and elsewhere in this document). If you haven't used the namespace before, please read the <> on namespace configuration, as this is intended as a supplement to the information there. Using a good quality XML editor while editing a configuration based on the schema is recommended as this will provide contextual information on which elements and attributes are available as well as comments explaining their purpose. The namespace is written in http://www.relaxng.org/[RELAX NG] Compact format and later converted into an XSD schema. If you are familiar with this format, you may wish to examine the https://fisheye.springsource.org/browse/spring-security/config/src/main/resources/org/springframework/security/config/spring-security-3.2.rnc[schema file] directly. [[nsa-web]] -==== Web Application Security +=== Web Application Security [[nsa-debug]] -===== +==== Enables Spring Security debugging infrastructure. This will provide human-readable (multi-line) debugging information to monitor requests coming into the security filters. This may include sensitive information, such as request parameters or headers, and should only be used in a development environment. [[nsa-http]] -===== +==== If you use an `` element within your application, a `FilterChainProxy` bean named "springSecurityFilterChain" is created and the configuration within the element is used to build a filter chain within `FilterChainProxy`. As of Spring Security 3.1, additional `http` elements can be used to add extra filter chains footnote:[ See the pass:specialcharacters,macros[<>] for how to set up the mapping from your `web.xml` ]. Some core filters are always created in a filter chain and others will be added to the stack depending on the attributes and child elements which are present. The positions of the standard filters are fixed (see @@ -6043,7 +5973,7 @@ Each `` namespace block always creates an `SecurityContextPersistenceFilte [[nsa-http-attributes]] -====== Attributes +===== Attributes The attributes on the `` element control some of the properties on the core filters. @@ -6147,7 +6077,7 @@ Enables EL-expressions in the `access` attribute, as described in the chapter on [[nsa-http-children]] -====== Child Elements of +===== Child Elements of * <> * <> * <> @@ -6168,17 +6098,17 @@ Enables EL-expressions in the `access` attribute, as described in the chapter on [[nsa-access-denied-handler]] -===== +==== This element allows you to set the `errorPage` property for the default `AccessDeniedHandler` used by the `ExceptionTranslationFilter`, using the <> attribute, or to supply your own implementation using the<> attribute. This is discussed in more detail in the section on the <>. [[nsa-access-denied-handler-parents]] -====== Parent Elements of +===== Parent Elements of * <> [[nsa-access-denied-handler-attributes]] -====== Attributes +===== Attributes [[nsa-access-denied-handler-error-page]] @@ -6192,7 +6122,7 @@ Defines a reference to a Spring bean of type `AccessDeniedHandler `. [[nsa-headers]] -===== +==== This element allows for configuring additional (security) headers to be send with the response. It enables easy configuration for several headers and also allows for setting custom headers through the <> element. Additional information, can be found in the <> section of the reference. ** `Cache-Control`, `Pragma`, and `Expires` - Can be set using the <> element. This ensures that the browser does not cache your secured pages. @@ -6205,14 +6135,14 @@ This element allows for configuring additional (security) headers to be send wit [[nsa-headers-parents]] -====== Parent Elements of +===== Parent Elements of * <> [[nsa-headers-children]] -====== Child Elements of +===== Child Elements of * <> @@ -6225,12 +6155,12 @@ This element allows for configuring additional (security) headers to be send wit [[nsa-cache-control]] -===== +==== Adds `Cache-Control`, `Pragma`, and `Expires` headers to ensure that the browser does not cache your secured pages. [[nsa-cache-control-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -6238,12 +6168,12 @@ Adds `Cache-Control`, `Pragma`, and `Expires` headers to ensure that the browser [[nsa-hsts]] -===== +==== When enabled adds the http://tools.ietf.org/html/rfc6797[Strict-Transport-Security] header to the response for any secure request. This allows the server to instruct browsers to automatically use HTTPS for future requests. [[nsa-hsts-attributes]] -====== Attributes +===== Attributes [[nsa-hsts-include-subdomains]] @@ -6262,19 +6192,19 @@ The RequestMatcher instance to be used to determine if the header should be set. [[nsa-hsts-parents]] -====== Parent Elements of +===== Parent Elements of * <> [[nsa-frame-options]] -===== +==== When enabled adds the http://tools.ietf.org/html/draft-ietf-websec-x-frame-options[X-Frame-Options header] to the response, this allows newer browsers to do some security checks and prevent http://en.wikipedia.org/wiki/Clickjacking[clickjacking] attacks. [[nsa-frame-options-attributes]] -====== Attributes +===== Attributes [[nsa-frame-options-policy]] @@ -6314,24 +6244,24 @@ Specify the name of the request parameter to use when using regexp or whitelist [[nsa-frame-options-parents]] -====== Parent Elements of +===== Parent Elements of * <> [[nsa-xss-protection]] -===== -Adds the http://blogs.msdn.com/b/ie/archive/2008/07/02/ie8-security-part-iv-the-xss-filter.aspx[X-XSS-Protection header] to the response to assist in protecting against http://en.wikipedia.org/wiki/Cross-site_scripting#Non-Persistent[reflected / ���Type-1��� Cross-Site Scripting (XSS)] attacks. This is in no-way a full protection to XSS attacks! +==== +Adds the http://blogs.msdn.com/b/ie/archive/2008/07/02/ie8-security-part-iv-the-xss-filter.aspx[X-XSS-Protection header] to the response to assist in protecting against http://en.wikipedia.org/wiki/Cross-site_scripting#Non-Persistent[reflected / Type-1 Cross-Site Scripting (XSS)] attacks. This is in no-way a full protection to XSS attacks! [[nsa-xss-protection-attributes]] -====== Attributes +===== Attributes [[nsa-xss-protection-enabled]] * **xss-protection-enabled** -Enable or Disable http://en.wikipedia.org/wiki/Cross-site_scripting#Non-Persistent[reflected / ���Type-1��� Cross-Site Scripting (XSS)] protection. +Enable or Disable http://en.wikipedia.org/wiki/Cross-site_scripting#Non-Persistent[reflected / Type-1 Cross-Site Scripting (XSS)] protection. [[nsa-xss-protection-block]] @@ -6340,19 +6270,19 @@ When true and xss-protection-enabled is true, adds mode=block to the header. Thi [[nsa-xss-protection-parents]] -====== Parent Elements of +===== Parent Elements of * <> [[nsa-content-type-options]] -===== +==== Add the X-Content-Type-Options header with the value of nosniff to the response. This http://blogs.msdn.com/b/ie/archive/2008/09/02/ie8-security-part-vi-beta-2-update.aspx[disables MIME-sniffing] for IE8+ and Chrome extensions. [[nsa-content-type-options-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -6360,12 +6290,12 @@ Add the X-Content-Type-Options header with the value of nosniff to the response. [[nsa-header]] -=====
+====
Add additional headers to the response, both the name and value need to be specified. [[nsa-header-attributes]] -====== Attributes +===== Attributes [[nsa-header-name]] @@ -6384,7 +6314,7 @@ Reference to a custom implementation of the `HeaderWriter` interface. [[nsa-header-parents]] -====== Parent Elements of
+===== Parent Elements of
* <> @@ -6392,12 +6322,12 @@ Reference to a custom implementation of the `HeaderWriter` interface. [[nsa-anonymous]] -===== +==== Adds an `AnonymousAuthenticationFilter` to the stack and an `AnonymousAuthenticationProvider`. Required if you are using the `IS_AUTHENTICATED_ANONYMOUSLY` attribute. [[nsa-anonymous-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -6405,7 +6335,7 @@ Adds an `AnonymousAuthenticationFilter` to the stack and an `AnonymousAuthentica [[nsa-anonymous-attributes]] -====== Attributes +===== Attributes [[nsa-anonymous-enabled]] @@ -6429,12 +6359,12 @@ The username that should be assigned to the anonymous request. This allows the p [[nsa-csrf]] -===== +==== This element will add http://en.wikipedia.org/wiki/Cross-site_request_forgery[Cross Site Request Forger (CSRF)] protection to the application. It also updates the default RequestCache to only replay "GET" requests upon successful authentication. Additional information can be found in the <> section of the reference. [[nsa-csrf-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -6442,7 +6372,7 @@ This element will add http://en.wikipedia.org/wiki/Cross-site_request_forgery[Cr [[nsa-csrf-attributes]] -====== Attributes +===== Attributes [[nsa-csrf-token-repository-ref]] @@ -6456,12 +6386,12 @@ The RequestMatcher instance to be used to determine if CSRF should be applied. D [[nsa-custom-filter]] -===== +==== This element is used to add a filter to the filter chain. It doesn't create any additional beans but is used to select a bean of type `javax.servlet.Filter` which is already defined in the application context and add that at a particular position in the filter chain maintained by Spring Security. Full details can be found in the <>. [[nsa-custom-filter-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -6469,7 +6399,7 @@ This element is used to add a filter to the filter chain. It doesn't create any [[nsa-custom-filter-attributes]] -====== Attributes +===== Attributes [[nsa-custom-filter-after]] @@ -6493,12 +6423,12 @@ Defines a reference to a Spring bean that implements `Filter`. [[nsa-expression-handler]] -===== +==== Defines the `SecurityExpressionHandler` instance which will be used if expression-based access-control is enabled. A default implementation (with no ACL support) will be used if not supplied. [[nsa-expression-handler-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -6507,7 +6437,7 @@ Defines the `SecurityExpressionHandler` instance which will be used if expressio [[nsa-expression-handler-attributes]] -====== Attributes +===== Attributes [[nsa-expression-handler-ref]] @@ -6516,14 +6446,14 @@ Defines a reference to a Spring bean that implements `SecurityExpressionHandler` [[nsa-form-login]] -===== +==== Used to add an `UsernamePasswordAuthenticationFilter` to the filter stack and an `LoginUrlAuthenticationEntryPoint` to the application context to provide authentication on demand. This will always take precedence over other namespace-created entry points. If no attributes are supplied, a login page will be generated automatically at the URL "/spring_security_login" footnote:[ This feature is really just provided for convenience and is not intended for production (where a view technology will have been chosen and can be used to render a customized login page). The class `DefaultLoginPageGeneratingFilter` is responsible for rendering the login page and will provide login forms for both normal form login and/or OpenID if required. ] The behaviour can be customized using the <` Attributes>>. [[nsa-form-login-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -6531,7 +6461,7 @@ This feature is really just provided for convenience and is not intended for pro [[nsa-form-login-attributes]] -====== Attributes +===== Attributes [[nsa-form-login-always-use-default-target]] @@ -6585,12 +6515,12 @@ The name of the request parameter which contains the username. Defaults to "j_us [[nsa-http-basic]] -===== +==== Adds a `BasicAuthenticationFilter` and `BasicAuthenticationEntryPoint` to the configuration. The latter will only be used as the configuration entry point if form-based login is not enabled. [[nsa-http-basic-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -6598,7 +6528,7 @@ Adds a `BasicAuthenticationFilter` and `BasicAuthenticationEntryPoint` to the co [[nsa-http-basic-attributes]] -====== Attributes +===== Attributes [[nsa-http-basic-authentication-details-source-ref]] @@ -6612,12 +6542,12 @@ Sets the `AuthenticationEntryPoint` which is used by the `BasicAuthenticationFil [[nsa-http-firewall]] -===== Element +==== Element This is a top-level element which can be used to inject a custom implementation of `HttpFirewall` into the `FilterChainProxy` created by the namespace. The default implementation should be suitable for most applications. [[nsa-http-firewall-attributes]] -====== Attributes +===== Attributes [[nsa-http-firewall-ref]] @@ -6626,12 +6556,12 @@ Defines a reference to a Spring bean that implements `HttpFirewall`. [[nsa-intercept-url]] -===== +==== This element is used to define the set of URL patterns that the application is interested in and to configure how they should be handled. It is used to construct the `FilterInvocationSecurityMetadataSource` used by the `FilterSecurityInterceptor`. It is also responsible for configuring a `ChannelProcessingFilter` if particular URLs need to be accessed by HTTPS, for example. When matching the specified patterns against an incoming request, the matching is done in the order in which the elements are declared. So the most specific matches patterns should come first and the most general should come last. [[nsa-intercept-url-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -6641,7 +6571,7 @@ This element is used to define the set of URL patterns that the application is i [[nsa-intercept-url-attributes]] -====== Attributes +===== Attributes [[nsa-intercept-url-access]] @@ -6672,12 +6602,12 @@ If a `` configuration is added, this will be used to by the `Secu [[nsa-jee]] -===== +==== Adds a J2eePreAuthenticatedProcessingFilter to the filter chain to provide integration with container authentication. [[nsa-jee-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -6685,7 +6615,7 @@ Adds a J2eePreAuthenticatedProcessingFilter to the filter chain to provide integ [[nsa-jee-attributes]] -====== Attributes +===== Attributes [[nsa-jee-mappable-roles]] @@ -6699,12 +6629,12 @@ A reference to a user-service (or UserDetailsService bean) Id [[nsa-logout]] -===== +==== Adds a `LogoutFilter` to the filter stack. This is configured with a `SecurityContextLogoutHandler`. [[nsa-logout-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -6712,7 +6642,7 @@ Adds a `LogoutFilter` to the filter stack. This is configured with a `SecurityCo [[nsa-logout-attributes]] -====== Attributes +===== Attributes [[nsa-logout-delete-cookies]] @@ -6745,12 +6675,12 @@ May be used to supply an instance of `LogoutSuccessHandler` which will be invoke [[nsa-openid-login]] -===== +==== Similar to `` and has the same attributes. The default value for `login-processing-url` is "/j_spring_openid_security_check". An `OpenIDAuthenticationFilter` and `OpenIDAuthenticationProvider` will be registered. The latter requires a reference to a `UserDetailsService`. Again, this can be specified by `id`, using the `user-service-ref` attribute, or will be located automatically in the application context. [[nsa-openid-login-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -6758,7 +6688,7 @@ Similar to `` and has the same attributes. The default value for `lo [[nsa-openid-login-attributes]] -====== Attributes +===== Attributes [[nsa-openid-login-always-use-default-target]] @@ -6817,18 +6747,18 @@ The name of the request parameter which contains the username. Defaults to "j_us [[nsa-openid-login-children]] -====== Child Elements of +===== Child Elements of * <> [[nsa-attribute-exchange]] -===== +==== The `attribute-exchange` element defines the list of attributes which should be requested from the identity provider. An example can be found in the <> section of the namespace configuration chapter. More than one can be used, in which case each must have an `identifier-match` attribute, containing a regular expression which is matched against the supplied OpenID identifier. This allows different attribute lists to be fetched from different providers (Google, Yahoo etc). [[nsa-attribute-exchange-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -6836,7 +6766,7 @@ The `attribute-exchange` element defines the list of attributes which should be [[nsa-attribute-exchange-attributes]] -====== Attributes +===== Attributes [[nsa-attribute-exchange-identifier-match]] @@ -6845,7 +6775,7 @@ A regular expression which will be compared against the claimed identity, when d [[nsa-attribute-exchange-children]] -====== Child Elements of +===== Child Elements of * <> @@ -6853,12 +6783,12 @@ A regular expression which will be compared against the claimed identity, when d [[nsa-openid-attribute]] -===== +==== Attributes used when making an OpenID AX http://openid.net/specs/openid-attribute-exchange-1_0.html#fetch_request[ Fetch Request] [[nsa-openid-attribute-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -6866,7 +6796,7 @@ Attributes used when making an OpenID AX http://openid.net/specs/openid-attribut [[nsa-openid-attribute-attributes]] -====== Attributes +===== Attributes [[nsa-openid-attribute-count]] @@ -6890,12 +6820,12 @@ Specifies the attribute type. For example, http://axschema.org/contact/email. Se [[nsa-port-mappings]] -===== +==== By default, an instance of `PortMapperImpl` will be added to the configuration for use in redirecting to secure and insecure URLs. This element can optionally be used to override the default mappings which that class defines. Each child `` element defines a pair of HTTP:HTTPS ports. The default mappings are 80:443 and 8080:8443. An example of overriding these can be found in the <>. [[nsa-port-mappings-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -6903,7 +6833,7 @@ By default, an instance of `PortMapperImpl` will be added to the configuration f [[nsa-port-mappings-children]] -====== Child Elements of +===== Child Elements of * <> @@ -6911,12 +6841,12 @@ By default, an instance of `PortMapperImpl` will be added to the configuration f [[nsa-port-mapping]] -===== +==== Provides a method to map http ports to https ports when forcing a redirect. [[nsa-port-mapping-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -6924,7 +6854,7 @@ Provides a method to map http ports to https ports when forcing a redirect. [[nsa-port-mapping-attributes]] -====== Attributes +===== Attributes [[nsa-port-mapping-http]] @@ -6938,12 +6868,12 @@ The https port to use. [[nsa-remember-me]] -===== +==== Adds the `RememberMeAuthenticationFilter` to the stack. This in turn will be configured with either a `TokenBasedRememberMeServices`, a `PersistentTokenBasedRememberMeServices` or a user-specified bean implementing `RememberMeServices` depending on the attribute settings. [[nsa-remember-me-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -6951,7 +6881,7 @@ Adds the `RememberMeAuthenticationFilter` to the stack. This in turn will be con [[nsa-remember-me-attributes]] -====== Attributes +===== Attributes [[nsa-remember-me-authentication-success-handler-ref]] @@ -7007,17 +6937,17 @@ The remember-me services implementations require access to a `UserDetailsService [[nsa-request-cache]] -===== Element +==== Element Sets the `RequestCache` instance which will be used by the `ExceptionTranslationFilter` to store request information before invoking an `AuthenticationEntryPoint`. [[nsa-request-cache-parents]] -====== Parent Elements of +===== Parent Elements of * <> [[nsa-request-cache-attributes]] -====== Attributes +===== Attributes [[nsa-request-cache-ref]] @@ -7026,12 +6956,12 @@ Defines a reference to a Spring bean that is a `RequestCache`. [[nsa-session-management]] -===== +==== Session-management related functionality is implemented by the addition of a `SessionManagementFilter` to the filter stack. [[nsa-session-management-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -7039,7 +6969,7 @@ Session-management related functionality is implemented by the addition of a `Se [[nsa-session-management-attributes]] -====== Attributes +===== Attributes [[nsa-session-management-invalid-session-url]] @@ -7067,7 +6997,7 @@ If session fixation protection is enabled, the `SessionManagementFilter` is inje [[nsa-session-management-children]] -====== Child Elements of +===== Child Elements of * <> @@ -7075,12 +7005,12 @@ If session fixation protection is enabled, the `SessionManagementFilter` is inje [[nsa-concurrency-control]] -===== +==== Adds support for concurrent session control, allowing limits to be placed on the number of active sessions a user can have. A `ConcurrentSessionFilter` will be created, and a `ConcurrentSessionControlAuthenticationStrategy` will be used with the `SessionManagementFilter`. If a `form-login` element has been declared, the strategy object will also be injected into the created authentication filter. An instance of `SessionRegistry` (a `SessionRegistryImpl` instance unless the user wishes to use a custom bean) will be created for use by the strategy. [[nsa-concurrency-control-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -7088,7 +7018,7 @@ Adds support for concurrent session control, allowing limits to be placed on the [[nsa-concurrency-control-attributes]] -====== Attributes +===== Attributes [[nsa-concurrency-control-error-if-maximum-exceeded]] @@ -7117,12 +7047,12 @@ The user can supply their own `SessionRegistry` implementation using the `sessio [[nsa-x509]] -===== +==== Adds support for X.509 authentication. An `X509AuthenticationFilter` will be added to the stack and an `Http403ForbiddenEntryPoint` bean will be created. The latter will only be used if no other authentication mechanisms are in use (its only functionality is to return an HTTP 403 error code). A `PreAuthenticatedAuthenticationProvider` will also be created which delegates the loading of user authorities to a `UserDetailsService`. [[nsa-x509-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -7130,7 +7060,7 @@ Adds support for X.509 authentication. An `X509AuthenticationFilter` will be add [[nsa-x509-attributes]] -====== Attributes +===== Attributes [[nsa-x509-authentication-details-source-ref]] @@ -7149,12 +7079,12 @@ Allows a specific `UserDetailsService` to be used with X.509 in the case where m [[nsa-filter-chain-map]] -===== +==== Used to explicitly configure a FilterChainProxy instance with a FilterChainMap [[nsa-filter-chain-map-attributes]] -====== Attributes +===== Attributes [[nsa-filter-chain-map-path-type]] @@ -7168,7 +7098,7 @@ Supersedes the 'path-type' attribute. Defines the strategy use for matching inco [[nsa-filter-chain-map-children]] -====== Child Elements of +===== Child Elements of * <> @@ -7176,12 +7106,12 @@ Supersedes the 'path-type' attribute. Defines the strategy use for matching inco [[nsa-filter-chain]] -===== +==== Used within to define a specific URL pattern and the list of filters which apply to the URLs matching that pattern. When multiple filter-chain elements are assembled in a list in order to configure a FilterChainProxy, the most specific patterns must be placed at the top of the list, with most general ones at the bottom. [[nsa-filter-chain-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -7189,7 +7119,7 @@ Used within to define a specific URL pattern and the list of filters which apply [[nsa-filter-chain-attributes]] -====== Attributes +===== Attributes [[nsa-filter-chain-filters]] @@ -7208,12 +7138,12 @@ A reference to a `RequestMatcher` that will be used to determine if the `Filter` [[nsa-filter-invocation-definition-source]] -===== +==== Deprecated synonym for filter-security-metadata-source [[nsa-filter-invocation-definition-source-attributes]] -====== Attributes +===== Attributes [[nsa-filter-invocation-definition-source-id]] @@ -7242,7 +7172,7 @@ Enables the use of expressions in the 'access' attributes in ele [[nsa-filter-invocation-definition-source-children]] -====== Child Elements of +===== Child Elements of * <> @@ -7250,12 +7180,12 @@ Enables the use of expressions in the 'access' attributes in ele [[nsa-filter-security-metadata-source]] -===== +==== Used to explicitly configure a FilterSecurityMetadataSource bean for use with a FilterSecurityInterceptor. Usually only needed if you are configuring a FilterChainProxy explicitly, rather than using the element. The intercept-url elements used should only contain pattern, method and access attributes. Any others will result in a configuration error. [[nsa-filter-security-metadata-source-attributes]] -====== Attributes +===== Attributes [[nsa-filter-security-metadata-source-id]] @@ -7284,7 +7214,7 @@ Enables the use of expressions in the 'access' attributes in ele [[nsa-filter-security-metadata-source-children]] -====== Child Elements of +===== Child Elements of * <> @@ -7292,17 +7222,17 @@ Enables the use of expressions in the 'access' attributes in ele [[nsa-authentication]] -==== Authentication Services +=== Authentication Services Before Spring Security 3.0, an `AuthenticationManager` was automatically registered internally. Now you must register one explicitly using the `` element. This creates an instance of Spring Security's `ProviderManager` class, which needs to be configured with a list of one or more `AuthenticationProvider` instances. These can either be created using syntax elements provided by the namespace, or they can be standard bean definitions, marked for addition to the list using the `authentication-provider` element. [[nsa-authentication-manager]] -===== +==== Every Spring Security application which uses the namespace must have include this element somewhere. It is responsible for registering the `AuthenticationManager` which provides authentication services to the application. All elements which create `AuthenticationProvider` instances should be children of this element. [[nsa-authentication-manager-attributes]] -====== Attributes +===== Attributes [[nsa-authentication-manager-alias]] @@ -7321,7 +7251,7 @@ This attribute allows you to define an id for the internal instance for use in y [[nsa-authentication-manager-children]] -====== Child Elements of +===== Child Elements of * <> @@ -7330,12 +7260,12 @@ This attribute allows you to define an id for the internal instance for use in y [[nsa-authentication-provider]] -===== +==== Unless used with a `ref` attribute, this element is shorthand for configuring a <>. `DaoAuthenticationProvider` loads user information from a `UserDetailsService` and compares the username/password combination with the values supplied at login. The `UserDetailsService` instance can be defined either by using an available namespace element ( `jdbc-user-service` or by using the `user-service-ref` attribute to point to a bean defined elsewhere in the application context). You can find examples of these variations in the <>. [[nsa-authentication-provider-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -7343,7 +7273,7 @@ Unless used with a `ref` attribute, this element is shorthand for configuring a [[nsa-authentication-provider-attributes]] -====== Attributes +===== Attributes [[nsa-authentication-provider-ref]] @@ -7371,7 +7301,7 @@ A reference to a bean that implements UserDetailsService that may be created usi [[nsa-authentication-provider-children]] -====== Child Elements of +===== Child Elements of * <> @@ -7382,12 +7312,12 @@ A reference to a bean that implements UserDetailsService that may be created usi [[nsa-jdbc-user-service]] -===== +==== Causes creation of a JDBC-based UserDetailsService. [[nsa-jdbc-user-service-attributes]] -====== Attributes +===== Attributes [[nsa-jdbc-user-service-authorities-by-username-query]] @@ -7458,12 +7388,12 @@ select username, password, enabled from users where username = ? [[nsa-password-encoder]] -===== +==== Authentication providers can optionally be configured to use a password encoder as described in the <>. This will result in the bean being injected with the appropriate `PasswordEncoder` instance, potentially with an accompanying `SaltSource` bean to provide salt values for hashing. [[nsa-password-encoder-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -7472,7 +7402,7 @@ Authentication providers can optionally be configured to use a password encoder [[nsa-password-encoder-attributes]] -====== Attributes +===== Attributes [[nsa-password-encoder-base64]] @@ -7491,7 +7421,7 @@ Defines a reference to a Spring bean that implements `PasswordEncoder `. [[nsa-password-encoder-children]] -====== Child Elements of +===== Child Elements of * <> @@ -7499,12 +7429,12 @@ Defines a reference to a Spring bean that implements `PasswordEncoder `. [[nsa-salt-source]] -===== +==== Password salting strategy. A system-wide constant or a property from the UserDetails object can be used. [[nsa-salt-source-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -7512,7 +7442,7 @@ Password salting strategy. A system-wide constant or a property from the UserDet [[nsa-salt-source-attributes]] -====== Attributes +===== Attributes [[nsa-salt-source-ref]] @@ -7531,12 +7461,12 @@ A property of the UserDetails object which will be used as salt by a password en [[nsa-user-service]] -===== +==== Creates an in-memory UserDetailsService from a properties file or a list of "user" child elements. Usernames are converted to lower-case internally to allow for case-insensitive lookups, so this should not be used if case-sensitivity is required. [[nsa-user-service-attributes]] -====== Attributes +===== Attributes [[nsa-user-service-id]] @@ -7559,7 +7489,7 @@ username=password,grantedAuthority[,grantedAuthority][,enabled|disabled] [[nsa-user-service-children]] -====== Child Elements of +===== Child Elements of * <> @@ -7567,12 +7497,12 @@ username=password,grantedAuthority[,grantedAuthority][,enabled|disabled] [[nsa-user]] -===== +==== Represents a user in the application. [[nsa-user-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -7580,7 +7510,7 @@ Represents a user in the application. [[nsa-user-attributes]] -====== Attributes +===== Attributes [[nsa-user-authorities]] @@ -7609,16 +7539,16 @@ The password assigned to the user. This may be hashed if the corresponding authe [[nsa-method-security]] -==== Method Security +=== Method Security [[nsa-global-method-security]] -===== +==== This element is the primary means of adding support for securing methods on Spring Security beans. Methods can be secured by the use of annotations (defined at the interface or class level) or by defining a set of pointcuts as child elements, using AspectJ syntax. [[nsa-global-method-security-attributes]] -====== Attributes +===== Attributes [[nsa-global-method-security-access-decision-manager-ref]] @@ -7674,7 +7604,7 @@ Specifies whether the use of Spring Security's @Secured annotations should be en [[nsa-global-method-security-children]] -====== Child Elements of +===== Child Elements of * <> @@ -7685,12 +7615,12 @@ Specifies whether the use of Spring Security's @Secured annotations should be en [[nsa-after-invocation-provider]] -===== +==== This element can be used to decorate an `AfterInvocationProvider` for use by the security interceptor maintained by the `` namespace. You can define zero or more of these within the `global-method-security` element, each with a `ref` attribute pointing to an `AfterInvocationProvider` bean instance within your application context. [[nsa-after-invocation-provider-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -7698,7 +7628,7 @@ This element can be used to decorate an `AfterInvocationProvider` for use by the [[nsa-after-invocation-provider-attributes]] -====== Attributes +===== Attributes [[nsa-after-invocation-provider-ref]] @@ -7707,12 +7637,12 @@ Defines a reference to a Spring bean that implements ` AfterInvocationProvider`. [[nsa-pre-post-annotation-handling]] -===== +==== Allows the default expression-based mechanism for handling Spring Security's pre and post invocation annotations (@PreFilter, @PreAuthorize, @PostFilter, @PostAuthorize) to be replace entirely. Only applies if these annotations are enabled. [[nsa-pre-post-annotation-handling-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -7720,7 +7650,7 @@ Allows the default expression-based mechanism for handling Spring Security's pre [[nsa-pre-post-annotation-handling-children]] -====== Child Elements of +===== Child Elements of * <> @@ -7730,12 +7660,12 @@ Allows the default expression-based mechanism for handling Spring Security's pre [[nsa-invocation-attribute-factory]] -===== +==== Defines the PrePostInvocationAttributeFactory instance which is used to generate pre and post invocation metadata from the annotated methods. [[nsa-invocation-attribute-factory-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -7743,7 +7673,7 @@ Defines the PrePostInvocationAttributeFactory instance which is used to generate [[nsa-invocation-attribute-factory-attributes]] -====== Attributes +===== Attributes [[nsa-invocation-attribute-factory-ref]] @@ -7752,12 +7682,12 @@ Defines a reference to a Spring bean Id. [[nsa-post-invocation-advice]] -===== +==== Customizes the `PostInvocationAdviceProvider` with the ref as the `PostInvocationAuthorizationAdvice` for the element. [[nsa-post-invocation-advice-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -7765,7 +7695,7 @@ Customizes the `PostInvocationAdviceProvider` with the ref as the `PostInvocatio [[nsa-post-invocation-advice-attributes]] -====== Attributes +===== Attributes [[nsa-post-invocation-advice-ref]] @@ -7774,12 +7704,12 @@ Defines a reference to a Spring bean Id. [[nsa-pre-invocation-advice]] -===== +==== Customizes the `PreInvocationAuthorizationAdviceVoter` with the ref as the `PreInvocationAuthorizationAdviceVoter` for the element. [[nsa-pre-invocation-advice-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -7787,7 +7717,7 @@ Customizes the `PreInvocationAuthorizationAdviceVoter` with the ref as the `PreI [[nsa-pre-invocation-advice-attributes]] -====== Attributes +===== Attributes [[nsa-pre-invocation-advice-ref]] @@ -7796,13 +7726,13 @@ Defines a reference to a Spring bean Id. [[nsa-protect-pointcut]] -===== Securing Methods using +==== Securing Methods using `` Rather than defining security attributes on an individual method or class basis using the `@Secured` annotation, you can define cross-cutting security constraints across whole sets of methods and interfaces in your service layer using the `` element. You can find an example in the <>. [[nsa-protect-pointcut-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -7810,7 +7740,7 @@ Rather than defining security attributes on an individual method or class basis [[nsa-protect-pointcut-attributes]] -====== Attributes +===== Attributes [[nsa-protect-pointcut-access]] @@ -7824,12 +7754,12 @@ An AspectJ expression, including the 'execution' keyword. For example, 'executio [[nsa-intercept-methods]] -===== +==== Can be used inside a bean definition to add a security interceptor to the bean and set up access configuration attributes for the bean's methods [[nsa-intercept-methods-attributes]] -====== Attributes +===== Attributes [[nsa-intercept-methods-access-decision-manager-ref]] @@ -7838,7 +7768,7 @@ Optional AccessDecisionManager bean ID to be used by the created method security [[nsa-intercept-methods-children]] -====== Child Elements of +===== Child Elements of * <> @@ -7846,12 +7776,12 @@ Optional AccessDecisionManager bean ID to be used by the created method security [[nsa-method-security-metadata-source]] -===== +==== Creates a MethodSecurityMetadataSource instance [[nsa-method-security-metadata-source-attributes]] -====== Attributes +===== Attributes [[nsa-method-security-metadata-source-id]] @@ -7865,7 +7795,7 @@ Enables the use of expressions in the 'access' attributes in ele [[nsa-method-security-metadata-source-children]] -====== Child Elements of +===== Child Elements of * <> @@ -7873,12 +7803,12 @@ Enables the use of expressions in the 'access' attributes in ele [[nsa-protect]] -===== +==== Defines a protected method and the access control configuration attributes that apply to it. We strongly advise you NOT to mix "protect" declarations with any services provided "global-method-security". [[nsa-protect-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -7887,7 +7817,7 @@ Defines a protected method and the access control configuration attributes that [[nsa-protect-attributes]] -====== Attributes +===== Attributes [[nsa-protect-access]] @@ -7901,12 +7831,12 @@ A method name [[nsa-ldap]] -==== LDAP Namespace Options +=== LDAP Namespace Options LDAP is covered in some details in <>. We will expand on that here with some explanation of how the namespace options map to Spring beans. The LDAP implementation uses Spring LDAP extensively, so some familiarity with that project's API may be useful. [[nsa-ldap-server]] -===== Defining the LDAP Server using the +==== Defining the LDAP Server using the `` Element This element sets up a Spring LDAP `ContextSource` for use by the other LDAP beans, defining the location of the LDAP server and other information (such as a username and password, if it doesn't allow anonymous access) for connecting to it. It can also be used to create an embedded server for testing. Details of the syntax for both options are covered in the <>. The actual `ContextSource` implementation is `DefaultSpringSecurityContextSource` which extends Spring LDAP's `LdapContextSource` class. The `manager-dn` and `manager-password` attributes map to the latter's `userDn` and `password` properties respectively. @@ -7914,7 +7844,7 @@ If you only have one server defined in your application context, the other LDAP [[nsa-ldap-server-attributes]] -====== Attributes +===== Attributes [[nsa-ldap-server-id]] @@ -7953,12 +7883,12 @@ Specifies the ldap server URL when not using the embedded LDAP server. [[nsa-ldap-authentication-provider]] -===== +==== This element is shorthand for the creation of an `LdapAuthenticationProvider` instance. By default this will be configured with a `BindAuthenticator` instance and a `DefaultAuthoritiesPopulator`. As with all namespace authentication providers, it must be included as a child of the `authentication-provider` element. [[nsa-ldap-authentication-provider-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -7966,7 +7896,7 @@ This element is shorthand for the creation of an `LdapAuthenticationProvider` in [[nsa-ldap-authentication-provider-attributes]] -====== Attributes +===== Attributes [[nsa-ldap-authentication-provider-group-role-attribute]] @@ -8028,7 +7958,7 @@ If you need to perform a search to locate the user in the directory, then you ca [[nsa-ldap-authentication-provider-children]] -====== Child Elements of +===== Child Elements of * <> @@ -8036,12 +7966,12 @@ If you need to perform a search to locate the user in the directory, then you ca [[nsa-password-compare]] -===== +==== This is used as child element to `` and switches the authentication strategy from `BindAuthenticator` to `PasswordComparisonAuthenticator`. [[nsa-password-compare-parents]] -====== Parent Elements of +===== Parent Elements of * <> @@ -8049,7 +7979,7 @@ This is used as child element to `` and switches the authenticati [[nsa-password-compare-attributes]] -====== Attributes +===== Attributes [[nsa-password-compare-hash]] @@ -8063,7 +7993,7 @@ The attribute in the directory which contains the user password. Defaults to "us [[nsa-password-compare-children]] -====== Child Elements of +===== Child Elements of * <> @@ -8071,12 +8001,12 @@ The attribute in the directory which contains the user password. Defaults to "us [[nsa-ldap-user-service]] -===== +==== This element configures an LDAP `UserDetailsService`. The class used is `LdapUserDetailsService` which is a combination of a `FilterBasedLdapUserSearch` and a `DefaultLdapAuthoritiesPopulator`. The attributes it supports have the same usage as in ``. [[nsa-ldap-user-service-attributes]] -====== Attributes +===== Attributes [[nsa-ldap-user-service-cache-ref]] @@ -8135,7 +8065,7 @@ The LDAP filter used to search for users (optional). For example "(uid={0})". Th [[appendix-dependencies]] -=== Spring Security Dependencies +== Spring Security Dependencies This appendix provides a reference of the modules in Spring Security and the additional dependencies that they require in order to function in a running application. We don't include dependenices that are only used when building or testing Spring Security itself. Nor do we include transitive dependencies which are required by external dependencies. The version of Spring required is listed on the project website, so the specific versions are omitted for Spring dependencies below. Note that some of the dependencies listed as"optional" below may still be required for other non-security functionality in a Spring application. Also dependencies listed as "optional" may not actually be marked as such in the project's Maven pom files if they are used in most applications. They are"optional" only in the sense that you don't need them unless you are using the specified functionality. @@ -8143,7 +8073,7 @@ The version of Spring required is listed on the project website, so the specific Where a module depends on another Spring Security module, the non-optional dependencies of the module it depends on are also assumed to be required and are not listed separately. -==== spring-security-core +=== spring-security-core The core module must be included in any project using Spring Security. @@ -8188,7 +8118,7 @@ The core module must be included in any project using Spring Security. | Required if you are using JSR-250 method-security annotations (optional). |=== -==== spring-security-remoting +=== spring-security-remoting This module is typically required in web applications which use the Servlet API. .Remoting Dependencies @@ -8204,7 +8134,7 @@ This module is typically required in web applications which use the Servlet API. | Required for clients which use HTTP remoting support. |=== -==== spring-security-web +=== spring-security-web This module is typically required in web applications which use the Servlet API. .Web Dependencies @@ -8228,7 +8158,7 @@ This module is typically required in web applications which use the Servlet API. | Required by remember-me persistent token repository implementations (optional). |=== -==== spring-security-ldap +=== spring-security-ldap This module is only required if you are using LDAP authentication. .LDAP Dependencies @@ -8262,7 +8192,7 @@ This module is only required if you are using LDAP authentication. |=== -==== spring-security-config +=== spring-security-config This module is required if you are using Spring Security namespace configuration. .Config Dependencies @@ -8291,7 +8221,7 @@ This module is required if you are using Spring Security namespace configuration |=== -==== spring-security-acl +=== spring-security-acl The ACL module. .ACL Dependencies @@ -8315,7 +8245,7 @@ The ACL module. | Required if you are using the default JDBC-based AclService (optional if you implement your own). |=== -==== spring-security-cas +=== spring-security-cas The CAS module provides integration with JA-SIG CAS. .CAS Dependencies @@ -8339,7 +8269,7 @@ The CAS module provides integration with JA-SIG CAS. | Required if you are using the ehcache-based ticket cache (optional). |=== -==== spring-security-openid +=== spring-security-openid The OpenID module. .OpenID Dependencies @@ -8367,7 +8297,7 @@ The OpenID module. | openid4java-nodeps depends on Guice 2. |=== -==== spring-security-taglibs +=== spring-security-taglibs Provides Spring Security's JSP tag implementations. .Taglib Dependencies