diff --git a/docs/faq/src/docbook/faq.xml b/docs/faq/src/docbook/faq.xml index cae1ff6010..3927454c60 100644 --- a/docs/faq/src/docbook/faq.xml +++ b/docs/faq/src/docbook/faq.xml @@ -1,19 +1,15 @@
- Frequently Answered Questions (FAQ) - + xmlns:xlink="http://www.w3.org/1999/xlink" version="5.0">Frequently Answered + Questions (FAQ) General - - Will Spring Security take care of all my application security - requirements? - - - Spring Security provides you with a very flexible framework for your + Will Spring Security take care of all my application security + requirements? + Spring Security provides you with a very flexible framework for your authentication and authorization requirements, but there are many other considerations for building a secure application that are outside its scope. Web applications are vulnerable to all kinds of attacks which you should be @@ -21,141 +17,113 @@ code with them in mind from the beginning. Check out the OWASP web site for information on the major issues facing web application developers and the - countermeasures you can use against them. - + countermeasures you can use against them. - - Why not just use web.xml security? - - - Let's assume you're developing an enterprise application based on Spring. - There are four security concerns you typically need to address: + Why not just use web.xml security? + Let's assume you're developing an enterprise application based on + Spring. There are four security concerns you typically need to address: authentication, web request security, service layer security (i.e. your methods that implement business logic), and domain object instance security (i.e. different domain objects have different permissions). With these - typical requirements in mind: - - Authentication: The servlet specification - provides an approach to authentication. However, you will need - to configure the container to perform authentication which - typically requires editing of container-specific "realm" - settings. This makes a non-portable configuration, and if you - need to write an actual Java class to implement the container's - authentication interface, it becomes even more non-portable. - With Spring Security you achieve complete portability - right - down to the WAR level. Also, Spring Security offers a choice of + typical requirements in mind: + Authentication: + The servlet specification provides an approach to + authentication. However, you will need to configure the + container to perform authentication which typically requires + editing of container-specific "realm" settings. This makes a + non-portable configuration, and if you need to write an actual + Java class to implement the container's authentication + interface, it becomes even more non-portable. With Spring + Security you achieve complete portability - right down to the + WAR level. Also, Spring Security offers a choice of production-proven authentication providers and mechanisms, meaning you can switch your authentication approaches at deployment time. This is particularly valuable for software vendors writing products that need to work in an unknown target - environment. - - - Web request security: The servlet - specification provides an approach to secure your request URIs. - However, these URIs can only be expressed in the servlet - specification's own limited URI path format. Spring Security - provides a far more comprehensive approach. For instance, you - can use Ant paths or regular expressions, you can consider parts - of the URI other than simply the requested page (e.g. you can - consider HTTP GET parameters) and you can implement your own - runtime source of configuration data. This means your web - request security can be dynamically changed during the actual - execution of your webapp. - - - Service layer and domain object security: - The absence of support in the servlet specification for services - layer security or domain object instance security represent - serious limitations for multi-tiered applications. Typically - developers either ignore these requirements, or implement - security logic within their MVC controller code (or even worse, - inside the views). There are serious disadvantages with this - approach: - - Separation of concerns: - Authorization is a crosscutting concern and should - be implemented as such. MVC controllers or views - implementing authorization code makes it more - difficult to test both the controller and - authorization logic, more difficult to debug, and - will often lead to code duplication. - - - Support for rich clients and web - services: If an additional client type - must ultimately be supported, any authorization code - embedded within the web layer is non-reusable. It - should be considered that Spring remoting exporters - only export service layer beans (not MVC - controllers). As such authorization logic needs to - be located in the services layer to support a - multitude of client types. - - - Layering issues: An MVC - controller or view is simply the incorrect - architectural layer to implement authorization - decisions concerning services layer methods or - domain object instances. Whilst the Principal may be - passed to the services layer to enable it to make - the authorization decision, doing so would introduce - an additional argument on every services layer - method. A more elegant approach is to use a - ThreadLocal to hold the Principal, although this - would likely increase development time to a point - where it would become more economical (on a - cost-benefit basis) to simply use a dedicated - security framework. - - - Authorisation code quality: - It is often said of web frameworks that they "make - it easier to do the right things, and harder to do - the wrong things". Security frameworks are the same, - because they are designed in an abstract manner for - a wide range of purposes. Writing your own - authorization code from scratch does not provide the - "design check" a framework would offer, and in-house - authorization code will typically lack the - improvements that emerge from widespread deployment, - peer review and new versions. - - - - - For simple applications, servlet specification security may just be - enough. Although when considered within the context of web container - portability, configuration requirements, limited web request security - flexibility, and non-existent services layer and domain object instance - security, it becomes clear why developers often look to alternative - solutions. - + environment.Web + request security: The servlet specification + provides an approach to secure your request URIs. However, these + URIs can only be expressed in the servlet specification's own + limited URI path format. Spring Security provides a far more + comprehensive approach. For instance, you can use Ant paths or + regular expressions, you can consider parts of the URI other + than simply the requested page (e.g. you can consider HTTP GET + parameters) and you can implement your own runtime source of + configuration data. This means your web request security can be + dynamically changed during the actual execution of your + webapp.Service layer + and domain object security: The absence of + support in the servlet specification for services layer security + or domain object instance security represent serious limitations + for multi-tiered applications. Typically developers either + ignore these requirements, or implement security logic within + their MVC controller code (or even worse, inside the views). + There are serious disadvantages with this approach: + Separation + of concerns: Authorization is a + crosscutting concern and should be implemented as + such. MVC controllers or views implementing + authorization code makes it more difficult to test + both the controller and authorization logic, more + difficult to debug, and will often lead to code + duplication.Support + for rich clients and web services: If + an additional client type must ultimately be + supported, any authorization code embedded within + the web layer is non-reusable. It should be + considered that Spring remoting exporters only + export service layer beans (not MVC controllers). As + such authorization logic needs to be located in the + services layer to support a multitude of client + types.Layering + issues: An MVC controller or view is + simply the incorrect architectural layer to + implement authorization decisions concerning + services layer methods or domain object instances. + Whilst the Principal may be passed to the services + layer to enable it to make the authorization + decision, doing so would introduce an additional + argument on every services layer method. A more + elegant approach is to use a ThreadLocal to hold the + Principal, although this would likely increase + development time to a point where it would become + more economical (on a cost-benefit basis) to simply + use a dedicated security + framework.Authorisation + code quality: It is often said of web + frameworks that they "make it easier to do the right + things, and harder to do the wrong things". Security + frameworks are the same, because they are designed + in an abstract manner for a wide range of purposes. + Writing your own authorization code from scratch + does not provide the "design check" a framework + would offer, and in-house authorization code will + typically lack the improvements that emerge from + widespread deployment, peer review and new versions. + + For simple applications, servlet specification security may just be enough. + Although when considered within the context of web container portability, + configuration requirements, limited web request security flexibility, and + non-existent services layer and domain object instance security, it becomes + clear why developers often look to alternative solutions. - - What Java and Spring Framework versions are required? - - - Spring Security 2.0.x requires a minimum JDK version of 1.4 and is built - against Spring 2.0.x. It should also be compatible with applications using - Spring 2.5.x. - Spring Security 3.0 requires JDK 1.5 as a minimum and will also require - Spring 3.0. - + What Java and Spring Framework versions are + required? + Spring Security 2.0.x requires a minimum JDK version of 1.4 and is + built against Spring 2.0.x. It should also be compatible with applications + using Spring 2.5.x. Spring Security 3.0 requires JDK 1.5 as a + minimum and will also require Spring 3.0. - - I'm new to Spring Security and I need to build an application that + I'm new to Spring Security and I need to build an application that supports CAS single sign-on over HTTPS, while allowing Basic authentication locally for certain URLs, authenticating against multiple back end user information sources (LDAP and JDBC). I've copied some configuration files I - found but it doesn't work. What could be wrong? - Or subsititute an alternative complex scenario... - - - Realistically, you need an understanding of the technolgies you are + found but it doesn't work. What could be wrong? Or subsititute + an alternative complex scenario... + Realistically, you need an understanding of the technolgies you are intending to use before you can successfully build applications with them. Security is complicated. Setting up a simple configuration using a login form and some hard-coded users using Spring Security's namespace is @@ -164,251 +132,208 @@ scenario like this you will almost certainly be frustrated. There is a big jump in the learning curve required to set up systems like CAS, configure LDAP servers and install SSL certificates properly. So you need to take - things one step at a time. - From a Spring Security perspective, the first thing you should do is - follow the Getting Started guide on the web site. This will - take you through a series of steps to get up and running and get some idea - of how the framework operates. If you are using other technologies which you - aren't familiar with then you should do some research and try to make sure - you can use them in isolation before combining them in a complex system. - - + things one step at a time. From a Spring Security perspective, + the first thing you should do is follow the Getting Started + guide on the web site. This will take you through a series of steps to get + up and running and get some idea of how the framework operates. If you are + using other technologies which you aren't familiar with then you should do + some research and try to make sure you can use them in isolation before + combining them in a complex system. Common Problems - - My application goes into an "endless loop" when I try to login, what's - going on? - - - A common user problem with infinite loop and redirecting to the login page - is caused by accidently configuring the login page as a "secured" resource. - Make sure your configuration allows anonymous access to the login page, - either by excluding it from the security filter chain or marking it as - requiring ROLE_ANONYMOUS. - If your AccessDecisionManager includes an AutheticatedVoter, you can use - the attribute "IS_AUTHENTICATED_ANONYMOUSLY". This is automatically - available if you are using the standard namespace configuration setup. - From Spring Security 2.0.1 onwards, when you are using namespace-based - configuration, a check will be made on loading the application context and a - warning message logged if your login page appears to be protected. - + My application goes into an "endless loop" when I try to login, + what's going on? + A common user problem with infinite loop and redirecting to the login + page is caused by accidently configuring the login page as a "secured" + resource. Make sure your configuration allows anonymous access to the login + page, either by excluding it from the security filter chain or marking it as + requiring ROLE_ANONYMOUS.If your AccessDecisionManager includes + an AuthenticatedVoter, you can use the attribute + "IS_AUTHENTICATED_ANONYMOUSLY". This is automatically available if you are + using the standard namespace configuration setup. From Spring + Security 2.0.1 onwards, when you are using namespace-based configuration, a + check will be made on loading the application context and a warning message + logged if your login page appears to be protected. - - I get an exception with the message "Access is denied (user is - anonymous);". What's wrong? - - - This is a debug level message which occurs the first time an anonymous - user attempts to access a protected resource. + I get an exception with the message "Access is denied (user is + anonymous);". What's wrong? + This is a debug level message which occurs the first time an + anonymous user attempts to access a protected resource. DEBUG [ExceptionTranslationFilter] - Access is denied (user is anonymous); redirecting to authentication entry point org.springframework.security.AccessDeniedException: Access is denied at org.springframework.security.vote.AffirmativeBased.decide(AffirmativeBased.java:68) at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:262) - It is normal and shouldn't be anything to worry about. - + It is normal and shouldn't be anything to worry about. - - Why can I still see a secured page even after I've logged out of my application? - - - The most common reason for this is that your browser has cached the page and you are seeing a - copy which is being retrieved from the browsers cache. Verify this by checking whether the browser is actually sending - the request (check your server access logs, the debug log or use a suitable browser debugging plugin such as Tamper Data - for Firefox). This has nothing to do with Spring Security and you should configure your application or server to set the - appropriate Cache-Control response headers. Note that SSL requests are never cached. - + Why can I still see a secured page even after I've logged out of my + application? + The most common reason for this is that your browser has cached the + page and you are seeing a copy which is being retrieved from the browsers + cache. Verify this by checking whether the browser is actually sending the + request (check your server access logs, the debug log or use a suitable + browser debugging plugin such as Tamper Data for Firefox). + This has nothing to do with Spring Security and you should configure your + application or server to set the appropriate + Cache-Control response headers. Note that SSL + requests are never cached. - - I get an exception with the message "An Authentication object was not - found in the SecurityContext". What's wrong? - - - This is a another debug level message which occurs the first time an + I get an exception with the message "An Authentication object was + not found in the SecurityContext". What's wrong? + This is a another debug level message which occurs the first time an anonymous user attempts to access a protected resource, but when you do not - have an AnonymousAuthenticationFilter in your filter chain configuration. + have an AnonymousAuthenticationFilter in your filter + chain configuration. DEBUG [ExceptionTranslationFilter] - Authentication exception occurred; redirecting to authentication entry point org.springframework.security.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext at org.springframework.security.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:342) at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:254) - It is normal and shouldn't be anything to worry about. - + It is normal and shouldn't be anything to worry about. - - I'm using Tomcat and have enabled HTTPS for my login page, switching back - to HTTP afterwards. It doesn't work - I just end up back at the login page - after authenticating. - - - This happens because Tomcat sessions created under HTTPS cannot + I'm using Tomcat and have enabled HTTPS for my login page, + switching back to HTTP afterwards. It doesn't work - I just end up back at + the login page after authenticating. + This happens because Tomcat sessions created under HTTPS cannot subsequently be used under HTTP and any session state is lost (including the security context information). Starting a session in HTTP first should work - as the session cookie won't be marked as secure. - + as the session cookie won't be marked as secure. - - I'm forwarding a request to another URL using the RequestDispatcher, but - my security constraints aren't being applied. - - - Filters are not applied by default to forwards or includes. If you really - want the security filters to be applied to forwards and/or includes, then - you have to configure these explicitly in your web.xml using the + I'm forwarding a request to another URL using the + RequestDispatcher, but my security constraints aren't being applied. + + Filters are not applied by default to forwards or includes. If you + really want the security filters to be applied to forwards and/or includes, + then you have to configure these explicitly in your web.xml using the <dispatcher> element, a child element of <filter-mapping>. - - + - - I'm trying to use the concurrent session-control support but it won't let - me log back in, even if I'm sure I've logged out and haven't exceeded the - allowed sessions. - - - Make sure you have added the listener to your web.xml file. It is + I'm trying to use the concurrent session-control support but it + won't let me log back in, even if I'm sure I've logged out and haven't + exceeded the allowed sessions. + Make sure you have added the listener to your web.xml file. It is essential to make sure that the Spring Security session registry is notified when a session is destroyed. Without it, the session information will not be - removed from the registry. - org.springframework.security.ui.session.HttpSessionEventPublisher ]]> - - + - - I have a user who has definitely been authenticated, but when I try to - access the SecurityContextHolder during some + I have a user who has definitely been authenticated, but when I try + to access the SecurityContextHolder during some requests, the Authentication is null. Why - can't I see the user information? - - - If you have excluded the request from the security filter chain using the - attribute filters='none' in the + can't I see the user information? + If you have excluded the request from the security filter chain using + the attribute filters='none' in the <intercept-url> element that matches the URL pattern, then the SecurityContextHolder will not be populated for that request. Check the debug log to see whether the request is passing through the filter chain. (You are reading the debug log, - right?). - + right?). - I have added Spring Security's <global-method-security> element to my application context but if I add - security annotations to my Spring MVC controller beans (Struts actions etc.) then they don't seem to have an effect. - - - The application context which holds the Spring MVC beans for the dispatcher servlet is a child application context - of the main application context which is loaded using the ContextLoaderListener you define in your - web.xml. The beans in the child context are not visible in the parent context so you need to either - move the <global-method-security> declaration to the web context or moved the beans you want secured into the main - application context. - - Generally we would recommend applying method security at the service layer rather than on individual web - controllers. - + I have added Spring Security's <global-method-security> + element to my application context but if I add security annotations to my + Spring MVC controller beans (Struts actions etc.) then they don't seem to + have an effect. + The application context which holds the Spring MVC beans for the + dispatcher servlet is a child application context of the main application + context which is loaded using the + ContextLoaderListener you define in your + web.xml. The beans in the child context are not + visible in the parent context so you need to either move the + <global-method-security> declaration to the web context or moved the + beans you want secured into the main application context. + Generally we would recommend applying method security at the + service layer rather than on individual web controllers. Spring Security Architecture Questions - - How do I know which package class X is in? - - - The best way of locating classes is by installing the Spring Security + How do I know which package class X is in? + The best way of locating classes is by installing the Spring Security source in your IDE. The distribution includes source jars for each of the modules the project is divided up into. Add these to your project source path and you can navigate directly to Spring Security classes (Ctrl-Shift-T in Eclipse). This also makes debugging easer and allows you to troubleshoot exceptions by looking directly at the - code where they occur to see what's going on there. - + code where they occur to see what's going on there. - - How do the namespace elements map to conventional bean - configurations? - - - There is a general overview of what beans are created by the namespace in - the namespace appendix of the reference guide. If want to know the full + How do the namespace elements map to conventional bean + configurations? + There is a general overview of what beans are created by the namespace + in the namespace appendix of the reference guide. If want to know the full details then the code is in the spring-security-config module within the Spring Security 3.0 distribution. You should probably read the chapters on namespace parsing in the standard Spring Framework reference - documentation first. - + documentation first. Common <quote>Howto</quote> Requests - - I need to login in with more information than just the username. How do I - add support for extra login fields (e.g. a company name)? - - - This question comes up repeatedly in the Spring Security forum so you will - find more information there by searching the archives (or through - google). - The submitted login information is processed by an instance of - UsernamePasswordAuthenticationFilter. You will need to - customize this class to handle the extra data field(s). One option is to use - your own customized authentication token class (rather than the standard - UsernamePasswordAuthenticationToken), another is - simply to concatenate the extra fields with the username (for example, using - a ":" as the separator) and pass them in the username property of - UsernamePasswordAuthenticationToken. - You will also need to customize the actual authentication process. If you - are using a custom authentication token class, for example, you will have to - write an AuthenticationProvider to handle it (or - extend the standard DaoAuthenticationProvider). If - you have concatenated the fields, you can implement your own + I need to login in with more information than just the username. How + do I add support for extra login fields (e.g. a company + name)? + This question comes up repeatedly in the Spring Security forum so you + will find more information there by searching the archives (or through + google). The submitted login information is processed by an + instance of UsernamePasswordAuthenticationFilter. You + will need to customize this class to handle the extra data field(s). One + option is to use your own customized authentication token class (rather than + the standard UsernamePasswordAuthenticationToken), + another is simply to concatenate the extra fields with the username (for + example, using a ":" as the separator) and pass them in the username + property of UsernamePasswordAuthenticationToken. + You will also need to customize the actual authentication + process. If you are using a custom authentication token class, for example, + you will have to write an AuthenticationProvider to + handle it (or extend the standard + DaoAuthenticationProvider). If you have + concatenated the fields, you can implement your own UserDetailsService which splits them up - and loads the appropriate user data for authentication. - + and loads the appropriate user data for authentication. - - How do I define the secured URLs within an application - dynamically? - - - People often ask about how to store the mapping between secured URLs and - security metadata attributes in a database, rather than in the application - context. - The first thing you should ask yourself is if you really need to do this. - If an application requires securing, then it also requires that the security - be tested thoroughly based on a defined policy. It may require auditing and - acceptance testing before being rolled out into a production environment. A - security-conscious organization should be aware that the benefits of their - diligent testing process could be wiped out instantly by allowing the - security settings to be modified at runtime by changing a row or two in a - configuration database. If you have taken this into account (perhaps using - multiple layers of security within your application) then Spring Security - allows you to fully customize the source of security metadata. You can make - it fully dynamic if you choose. - Both method and web security are protected by subclasses of + How do I define the secured URLs within an application + dynamically? + People often ask about how to store the mapping between secured URLs + and security metadata attributes in a database, rather than in the + application context. The first thing you should ask yourself + is if you really need to do this. If an application requires securing, then + it also requires that the security be tested thoroughly based on a defined + policy. It may require auditing and acceptance testing before being rolled + out into a production environment. A security-conscious organization should + be aware that the benefits of their diligent testing process could be wiped + out instantly by allowing the security settings to be modified at runtime by + changing a row or two in a configuration database. If you have taken this + into account (perhaps using multiple layers of security within your + application) then Spring Security allows you to fully customize the source + of security metadata. You can make it fully dynamic if you choose. + Both method and web security are protected by subclasses of AbstractSecurityInterceptor which is configured with a SecurityMetadataSource from which it - obtains the metadata for a particular method or filter invocation - This class previouly went by the rather obscure name of - ObjectDefinitionSource, but has been - renamed in Spring Security 3.0 - . For web security, the interceptor class is - FilterSecurityInterceptor and it uses the marker - interface + obtains the metadata for a particular method or filter invocation + This class previouly went by the rather obscure name + of ObjectDefinitionSource, but has been + renamed in Spring Security 3.0. For web security, + the interceptor class is FilterSecurityInterceptor + and it uses the marker interface FilterInvocationSecurityMetadataSource. The secured object type it operates on is a FilterInvocation. The default implementation @@ -416,20 +341,20 @@ when configuring the interceptor explicitly, stores the list of URL patterns and their corresponding list of configuration attributes (instances of ConfigAttribute) in an - in-memory map. - To load the data from an alternative source, you must be using an - explicitly declared security filter chain (typically Spring Security's - FilterChainProxy) in order to customize the - FilterSecurityInterceptor bean. You can't use the - namespace. You would then implement + in-memory map. To load the data from an alternative source, + you must be using an explicitly declared security filter chain (typically + Spring Security's FilterChainProxy) in order to + customize the FilterSecurityInterceptor bean. You + can't use the namespace. You would then implement FilterInvocationSecurityMetadataSource to load the data as you please for a particular - FilterInvocation - The FilterInvocation object contains the + FilterInvocationThe + FilterInvocation object contains the HttpServletRequest, so you can obtain the URL or any other relevant information on which to base your decision - on what the list of returned attributes will contain. - . A very basic outline would look something like this: . A very basic outline would look something + like this: getAttributes(Object object) { @@ -454,54 +379,46 @@ } ]]> For more information, look at the code for DefaultFilterInvocationSecurityMetadataSource. - - + - - How do I know which dependencies to add to my application to work with - Spring Security? - - - It will depend on what features you are using and what type of application - you are developing. With Spring Security 3.0, the project jars are divided - into clearly distinct areas of functionality, so it is straightforward to - work out which Spring Security jars you need from your application - requirements. All applications will need the + How do I know which dependencies to add to my application to work + with Spring Security? + It will depend on what features you are using and what type of + application you are developing. With Spring Security 3.0, the project jars + are divided into clearly distinct areas of functionality, so it is + straightforward to work out which Spring Security jars you need from your + application requirements. All applications will need the spring-security-core jar. If you're developing a web application, you need the spring-security-web jar. If you're using security namespace configuration you need the spring-security-config jar, for LDAP support you - need the spring-security-ldap jar and so on. - For third-party jars the situation isn't always quite so obvious. A good - starting point is to copy those from one of the pre-built sample - applications WEB-INF/lib directories. For a basic application, you can start - with the tutorial sample. If you want to use LDAP, with an embedded test - server, then use the LDAP sample as a starting point. - If you are building your project with maven, then adding the appropriate - Spring Security modules as dependencies to your pom.xml will automatically - pull in the core jars that the framework requires. Any which are marked as - "optional" in the Spring Security POM files will have to be added to your - own pom.xml file if you need them. - + need the spring-security-ldap jar and so on. + For third-party jars the situation isn't always quite so + obvious. A good starting point is to copy those from one of the pre-built + sample applications WEB-INF/lib directories. For a basic application, you + can start with the tutorial sample. If you want to use LDAP, with an + embedded test server, then use the LDAP sample as a starting point. + If you are building your project with maven, then adding the + appropriate Spring Security modules as dependencies to your pom.xml will + automatically pull in the core jars that the framework requires. Any which + are marked as "optional" in the Spring Security POM files will have to be + added to your own pom.xml file if you need them. - - How do I authenticate against LDAP but load user roles from a - database? - - - The LdapAuthenticationProvider bean (which handles normal - LDAP authentication in Spring Security) is configured with two separate - strategy interfaces, one which performs the authenticatation and one which - loads the user authorities, called + How do I authenticate against LDAP but load user roles from a + database? + The LdapAuthenticationProvider bean (which handles + normal LDAP authentication in Spring Security) is configured with two + separate strategy interfaces, one which performs the authenticatation and + one which loads the user authorities, called LdapAuthenticator and LdapAuthoritiesPopulator respectively. - The DefaultLdapAuthoitiesPopulator loads the user + The DefaultLdapAuthoritiesPopulator loads the user authorities from the LDAP directory and has various configuration parameters - to allow you to specify how these should be retrieved. - To use JDBC instead, you can implement the interface yourself, using - whatever SQL is appropriate for your schema: To use + JDBC instead, you can implement the interface yourself, using whatever SQL + is appropriate for your schema: - + relevant classes and interfaces. diff --git a/docs/manual/classindex.pl b/docs/manual/classindex.pl index e87f6bbaf1..9e6692f5d4 100755 --- a/docs/manual/classindex.pl +++ b/docs/manual/classindex.pl @@ -2,18 +2,22 @@ use strict; -# Get list of links to class src packages -system("curl http://static.springframework.org/spring-security/site/xref/allclasses-frame.html > allclasses-frame.html"); +# Get list of links to class src packages from Javadoc +#system("curl http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/allclasses-frame.html > allclasses-frame.html"); my @all_classes = `cat allclasses-frame.html`; -$#all_classes > 0 || die "No lines in xref"; +$#all_classes > 0 || die "No lines in Javadoc"; +# Src XREF format #AbstractAccessDecisionManager +# Javadoc format +#AbstractAclProvider my %classnames_to_src; while ($_ = pop @all_classes) { - next unless $_ =~ /(([a-zA-Z0-9_]+?))<\/a>/; + next unless $_ =~ /(([a-zA-Z0-9_]+?))<\/A>/; + print "Adding class $1, $2\n"; $classnames_to_src{$2} = $1; } diff --git a/docs/manual/src/docbook/appendix-namespace.xml b/docs/manual/src/docbook/appendix-namespace.xml index 9c49bc1fc4..ee8b808f5a 100644 --- a/docs/manual/src/docbook/appendix-namespace.xml +++ b/docs/manual/src/docbook/appendix-namespace.xml @@ -488,8 +488,8 @@ configuration as web security, but this can be overridden as explained above , using the same attribute.
- The <literal><secured-annotations></literal> and - <literal><jsr250-annotations></literal> Attributes + The <literal>secured-annotations</literal> and + <literal>jsr250-annotations</literal> Attributes Setting these to "true" will enable support for Spring Security's own @Secured annotations and JSR-250 annotations, respectively. They are both disabled by default. Use of JSR-250 annotations also adds a diff --git a/docs/manual/src/docbook/authorization-common.xml b/docs/manual/src/docbook/authorization-common.xml index f44cef4252..6f11b83c62 100644 --- a/docs/manual/src/docbook/authorization-common.xml +++ b/docs/manual/src/docbook/authorization-common.xml @@ -221,12 +221,15 @@ boolean supports(Class clazz); that there is at least one configuration attribute that an AccessDecisionVoter will vote to grant access for. This latter (recommended) approach is usually achieved through a ROLE_USER or - ROLE_AUTHENTICATED configuration attribute + ROLE_AUTHENTICATED configuration attribute. + + + + A common services layer method we've all written at one stage or another looks like this: @@ -279,8 +282,10 @@ boolean supports(Class clazz); requirePermissions. The Contacts sample application demonstrates these two AfterInvocationProviders. -
+ --> + + diff --git a/docs/manual/src/docbook/core-services.xml b/docs/manual/src/docbook/core-services.xml index 0f9d771e86..60b5afa5e6 100644 --- a/docs/manual/src/docbook/core-services.xml +++ b/docs/manual/src/docbook/core-services.xml @@ -97,9 +97,8 @@ returned from the configured UserDetailsService. A SaltSource enables the passwords to be populated with a "salt", which enhances the security of the passwords in the authentication - repository. These will be discussed in more detail in ???. - - + repository. These will be discussed in more detail below.
@@ -203,4 +202,78 @@ -->
+
+ Password Encoding + Spring Security's PasswordEncoder interface is used to + support the use of passwords which are encoded in some way in persistent storage. This + will normally mean that the passwords are hashed using a digest alogirthm + such as MD5 or SHA. +
+ 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 + + 5f4dcc3b5aa765d61d8327deb882cf99 + 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 + 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. 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. Spring Security has a + SaltSource interface which can be used by an + authentication provider to generate a salt value for a particular user. 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). +
+
+ 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 + enocoder is using hexadecimal strings (the default)You can configure + the encoder to use Base 64 instead of hex by setting the + encodeHashAsBase64 property to + true. Check the Javadoc for + MessageDigestPasswordEncoder and its parent + classes for more information.. 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. For + more information on the default method for merging salt and password, see the + Javadoc for BasePasswordEncoder. If you want to generate + encoded passwords directly in Java for storage in your user database, then you can + use the encodePassword method on the + PasswordEncoder. +
+
diff --git a/docs/manual/src/docbook/el-access.xml b/docs/manual/src/docbook/el-access.xml new file mode 100644 index 0000000000..09417c1604 --- /dev/null +++ b/docs/manual/src/docbook/el-access.xml @@ -0,0 +1,48 @@ + + + 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. +
+ Web Security Expressions + To use expressions to secure individual URLs, you would first need to set the + use-expressions attribute in the <http> + element to true. Spring Security will then expect the + access attributes of the <intercept-url> + elements to contain Spring EL expressions. The expressions should evaluate to a boolean, + defining whether access should be allowed or not. For example: + + ... + +]]>Here we have defined that the "admin" area of an application should only be + available to users who have the granted authority admin and whose IP + address matches a local subnet. The expressions hasRole and + hasIpAddress are both built in expressions, which are defined by + the WebSecurityExpressionRoot class, an instance of which is used + as the expression root object when evaluation web-access expressions. See the + documentation for Spring EL in the main Spring Framework reference if you want to know + more about the details of expression evaluation. This object also directly exposed the + HttpServletRequest object under the name + request so you can invoke the request directly in an + expression. + 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 in Spring Security 3.0 are supported through the use of + special annotations which allow pre and post-invocation authorization checks. + Expressions can also be used to filter collections or arrays, based on the permissions + of the principal invoking the method. Values can be removed from a collection argument + prior to the invocation of the method or, post-invocation, a returned collection can be + filtered to remove items to which the user should not have access. +
+
diff --git a/docs/manual/src/docbook/namespace-config.xml b/docs/manual/src/docbook/namespace-config.xml index 6c4e643ab9..e25200d38d 100644 --- a/docs/manual/src/docbook/namespace-config.xml +++ b/docs/manual/src/docbook/namespace-config.xml @@ -461,7 +461,11 @@ ]]> You should be able to login using the myopenid.com site to - authenticate. + authenticate. It is also possible to select a specific + UserDetailsService bean for use OpenID by setting the + user-service-ref attribute on the openid-login + element. See the previous section on authentication + providers for more information.
Adding in Your Own Filters @@ -564,10 +568,11 @@ 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 security as well as - the framework's native @Secured annotation. You can apply security to a - single bean, using the intercept-methods element to decorate the bean - declaration, or you can secure multiple beans across the entire service layer using the - AspectJ style pointcuts. + the framework's original @Secured annotation. From 3.0 you can also make + use of new expression-based annotations. + You can apply security to a single bean, using the + intercept-methods element to decorate the bean declaration, or you can + secure multiple beans across the entire service layer using the AspectJ style pointcuts.
The <literal><global-method-security></literal> Element This element is used to enable annotation-based security in your application (by @@ -581,9 +586,7 @@ Adding an annotation to a method (on an class or interface) would then limit the access to that method accordingly. Spring Security's native annotation support defines a set of attributes for the method. These will be passed to the - AccessDecisionManager for it to make the actual decision. - This example is taken from the tutorial sample, - which is a good starting point if you want to use method security in your application: + AccessDecisionManager for it to make the actual decision: public interface BankService { @@ -597,6 +600,22 @@ public Account post(Account account, double amount); } + To use the new expression-based syntax, you would use + ]]>and the equivalent Java code would + be + public interface BankService { + + @PreAuthorize("isAnonymous()") + public Account readAccount(Long id); + + @PreAuthorize("isAnonymous()") + public Account[] findAccounts(); + + @PreAuthorize("hasAuthority('ROLE_TELLER')") + public Account post(Account account, double amount); + } +
Adding Security Pointcuts using <literal>protect-pointcut</literal> The use of protect-pointcut is particularly powerful, as it allows @@ -642,7 +661,7 @@ ... ]]> - The syntax for web security is the same, but on the http element: The syntax for web security is the same, but on the http element: ... diff --git a/docs/manual/src/docbook/springsecurity.xml b/docs/manual/src/docbook/springsecurity.xml index c94d4596c5..76f10d1a7d 100644 --- a/docs/manual/src/docbook/springsecurity.xml +++ b/docs/manual/src/docbook/springsecurity.xml @@ -159,6 +159,7 @@ + Advanced Topics diff --git a/docs/manual/src/docbook/technical-overview.xml b/docs/manual/src/docbook/technical-overview.xml index f73ae8dd74..9e2a4d8f03 100644 --- a/docs/manual/src/docbook/technical-overview.xml +++ b/docs/manual/src/docbook/technical-overview.xml @@ -111,15 +111,15 @@ if (principal instanceof UserDetails) { On successful authentication, UserDetails is used to build the Authentication object that is stored in the SecurityContextHolder (more on this below). The good news is that we - provide a number of UserDetailsService implementations, - including one that uses an in-memory map (InMemoryDaoImpl) and - another that uses JDBC (JdbcDaoImpl). Most users tend to - write their own, though, with their implementations often simply sitting on top of an - existing Data Access Object (DAO) that represents their employees, customers, or other users - of the application. Remember the advantage that whatever your - UserDetailsService returns can always be obtained from the - SecurityContextHolder using the above code fragment. + xlink:href="#tech-intro-authentication">below). The good news is that we provide a + number of UserDetailsService implementations, including one + that uses an in-memory map (InMemoryDaoImpl) and another that uses + JDBC (JdbcDaoImpl). Most users tend to write their own, though, with + their implementations often simply sitting on top of an existing Data Access Object (DAO) + that represents their employees, customers, or other users of the application. Remember the + advantage that whatever your UserDetailsService returns can + always be obtained from the SecurityContextHolder using the above + code fragment.
GrantedAuthority @@ -189,50 +189,31 @@ if (principal instanceof UserDetails) { own proprietary authentication system.
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. - - - The system (successfully) verifies that the password is correct for the - username. - - - The context information for that user is obtained (their list of roles and so - on). - - - A security context is established for the user - - - The user proceeds, potentially to perform some operation which is potentially - protected by an access control mechanism which checks the required permissions for the - operation against the current security context information. - - The first three items constitute the authentication process so we'll take a - look at how these take place within Spring Security. - - The username and password are obtained and combined into an instance of + Let's consider a standard authentication scenario that everyone is familiar with. + A user is prompted to log in with a username and + password.The system (successfully) verifies that the + password is correct for the username.The context + information for that user is obtained (their list of roles and so + on).A security context is established for the + userThe user proceeds, potentially to perform some + operation which is potentially protected by an access control mechanism which checks + the required permissions for the operation against the current security context + information. The first three items constitute the + authentication process so we'll take a look at how these take place within Spring + Security.The username and password are obtained and + combined into an instance of UsernamePasswordAuthenticationToken (an instance of the Authentication interface, which we saw - earlier). - - - The token is passed to an instance of - AuthenticationManager for validation. - - - The AuthenticationManager returns a fully populated + earlier).The token is passed to an instance of + AuthenticationManager for + validation.The + AuthenticationManager returns a fully populated Authentication instance on successful - authentication. - - - The security context is established by calling - SecurityContextHolder.getContext().setAuthentication(...), passing in - the returned authentication object. - - From that point on, the user is considered to be authenticated. Let's look at - some code as an example. + authentication.The security context is established + by calling SecurityContextHolder.getContext().setAuthentication(...), + passing in the returned authentication object.From + that point on, the user is considered to be authenticated. Let's look at some code as an + example. import org.springframework.security.authentication.*; import org.springframework.security.core.*; import org.springframework.security.core.authority.GrantedAuthorityImpl; @@ -484,29 +465,17 @@ Successfully authenticated. Security context contains: \ Authentication if the principal has been authenticated. AbstractSecurityInterceptor provides a consistent workflow for - handling secure object requests, typically: - - Look up the configuration attributes associated with the present - request - - - Submitting the secure object, current + handling secure object requests, typically: Look up the + configuration attributes associated with the present + requestSubmitting the secure object, current Authentication and configuration attributes to the AccessDecisionManager for an authorization - decision - - - Optionally change the Authentication under which - the invocation takes place - - - Allow the secure object invocation to proceed (assuming access was granted) - - - Call the AfterInvocationManager if configured, once - the invocation has returned. - - + decisionOptionally change the + Authentication under which the invocation takes + placeAllow the secure object invocation to proceed + (assuming access was granted)Call the + AfterInvocationManager if configured, once the + invocation has returned.
What are Configuration Attributes? A configuration attribute can be thought of as a String that has @@ -518,9 +487,9 @@ Successfully authenticated. Security context contains: \ 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 + Configuration attributes will be entered as annotations on secured methods or as access attributes on secured URLs (using the namespace <intercept-url> - syntax). + syntax).
RunAsManager @@ -551,14 +520,10 @@ Successfully authenticated. Security context contains: \ or not change it in any way as it chooses. AbstractSecurityInterceptor and its related objects are shown in .
- Security interceptors and the <quote>secure object</quote> model - - + xml:id="abstract-security-interceptor">Security interceptors and the + <quote>secure object</quote> model - - -
+
Extending the Secure Object Model