Doc updates.

This commit is contained in:
Luke Taylor 2009-11-24 09:29:22 +00:00
parent 46ef4239ca
commit cd6711d21a
9 changed files with 483 additions and 452 deletions

View File

@ -1,19 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<?oxygen RNGSchema="http://www.oasis-open.org/docbook/xml/5.0/rng/docbook.rng" type="xml"?> <?oxygen RNGSchema="http://www.oasis-open.org/docbook/xml/5.0/rng/docbook.rng" type="xml"?>
<article class="faq" xml:id="spring-security-faq" xmlns="http://docbook.org/ns/docbook" <article class="faq" xml:id="spring-security-faq" xmlns="http://docbook.org/ns/docbook"
xmlns:xlink="http://www.w3.org/1999/xlink" version="5.0"><info> xmlns:xlink="http://www.w3.org/1999/xlink" version="5.0"><info><title>Frequently Answered
<title>Frequently Answered Questions (FAQ)</title> Questions (FAQ)</title></info>
</info>
<qandaset> <qandaset>
<qandadiv> <qandadiv>
<title>General</title> <title>General</title>
<qandaentry xml:id="faq-other-concerns"> <qandaentry xml:id="faq-other-concerns">
<question> <question><para>Will Spring Security take care of all my application security
<para>Will Spring Security take care of all my application security requirements?</para></question>
requirements?</para> <answer><para> Spring Security provides you with a very flexible framework for your
</question>
<answer>
<para> Spring Security provides you with a very flexible framework for your
authentication and authorization requirements, but there are many other authentication and authorization requirements, but there are many other
considerations for building a secure application that are outside its scope. considerations for building a secure application that are outside its scope.
Web applications are vulnerable to all kinds of attacks which you should be 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 <link code with them in mind from the beginning. Check out the <link
xlink:href="http://www.owasp.org/">OWASP web site</link> for information xlink:href="http://www.owasp.org/">OWASP web site</link> for information
on the major issues facing web application developers and the on the major issues facing web application developers and the
countermeasures you can use against them.</para> countermeasures you can use against them.</para></answer>
</answer>
</qandaentry> </qandaentry>
<qandaentry xml:id="faq-web-xml"> <qandaentry xml:id="faq-web-xml">
<question> <question><para>Why not just use web.xml security?</para></question>
<para>Why not just use web.xml security?</para> <answer><para>Let's assume you're developing an enterprise application based on
</question> Spring. There are four security concerns you typically need to address:
<answer>
<para>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 authentication, web request security, service layer security (i.e. your
methods that implement business logic), and domain object instance security methods that implement business logic), and domain object instance security
(i.e. different domain objects have different permissions). With these (i.e. different domain objects have different permissions). With these
typical requirements in mind: <orderedlist> typical requirements in mind:
<listitem> <orderedlist><listitem><para><emphasis>Authentication</emphasis>:
<para><emphasis>Authentication</emphasis>: The servlet specification The servlet specification provides an approach to
provides an approach to authentication. However, you will need authentication. However, you will need to configure the
to configure the container to perform authentication which container to perform authentication which typically requires
typically requires editing of container-specific "realm" editing of container-specific "realm" settings. This makes a
settings. This makes a non-portable configuration, and if you non-portable configuration, and if you need to write an actual
need to write an actual Java class to implement the container's Java class to implement the container's authentication
authentication interface, it becomes even more non-portable. interface, it becomes even more non-portable. With Spring
With Spring Security you achieve complete portability - right Security you achieve complete portability - right down to the
down to the WAR level. Also, Spring Security offers a choice of WAR level. Also, Spring Security offers a choice of
production-proven authentication providers and mechanisms, production-proven authentication providers and mechanisms,
meaning you can switch your authentication approaches at meaning you can switch your authentication approaches at
deployment time. This is particularly valuable for software deployment time. This is particularly valuable for software
vendors writing products that need to work in an unknown target vendors writing products that need to work in an unknown target
environment.</para> environment.</para></listitem><listitem><para><emphasis>Web
</listitem> request security:</emphasis> The servlet specification
<listitem> provides an approach to secure your request URIs. However, these
<para><emphasis>Web request security:</emphasis> The servlet URIs can only be expressed in the servlet specification's own
specification provides an approach to secure your request URIs. limited URI path format. Spring Security provides a far more
However, these URIs can only be expressed in the servlet comprehensive approach. For instance, you can use Ant paths or
specification's own limited URI path format. Spring Security regular expressions, you can consider parts of the URI other
provides a far more comprehensive approach. For instance, you than simply the requested page (e.g. you can consider HTTP GET
can use Ant paths or regular expressions, you can consider parts parameters) and you can implement your own runtime source of
of the URI other than simply the requested page (e.g. you can configuration data. This means your web request security can be
consider HTTP GET parameters) and you can implement your own dynamically changed during the actual execution of your
runtime source of configuration data. This means your web webapp.</para></listitem><listitem><para><emphasis>Service layer
request security can be dynamically changed during the actual and domain object security:</emphasis> The absence of
execution of your webapp.</para> support in the servlet specification for services layer security
</listitem> or domain object instance security represent serious limitations
<listitem> for multi-tiered applications. Typically developers either
<para><emphasis>Service layer and domain object security:</emphasis> ignore these requirements, or implement security logic within
The absence of support in the servlet specification for services their MVC controller code (or even worse, inside the views).
layer security or domain object instance security represent There are serious disadvantages with this approach:
serious limitations for multi-tiered applications. Typically <orderedlist><listitem><para><emphasis>Separation
developers either ignore these requirements, or implement of concerns:</emphasis> Authorization is a
security logic within their MVC controller code (or even worse, crosscutting concern and should be implemented as
inside the views). There are serious disadvantages with this such. MVC controllers or views implementing
approach: <orderedlist> authorization code makes it more difficult to test
<listitem> both the controller and authorization logic, more
<para><emphasis>Separation of concerns:</emphasis> difficult to debug, and will often lead to code
Authorization is a crosscutting concern and should duplication.</para></listitem><listitem><para><emphasis>Support
be implemented as such. MVC controllers or views for rich clients and web services:</emphasis> If
implementing authorization code makes it more an additional client type must ultimately be
difficult to test both the controller and supported, any authorization code embedded within
authorization logic, more difficult to debug, and the web layer is non-reusable. It should be
will often lead to code duplication.</para> considered that Spring remoting exporters only
</listitem> export service layer beans (not MVC controllers). As
<listitem> such authorization logic needs to be located in the
<para><emphasis>Support for rich clients and web services layer to support a multitude of client
services:</emphasis> If an additional client type types.</para></listitem><listitem><para><emphasis>Layering
must ultimately be supported, any authorization code issues:</emphasis> An MVC controller or view is
embedded within the web layer is non-reusable. It simply the incorrect architectural layer to
should be considered that Spring remoting exporters implement authorization decisions concerning
only export service layer beans (not MVC services layer methods or domain object instances.
controllers). As such authorization logic needs to Whilst the Principal may be passed to the services
be located in the services layer to support a layer to enable it to make the authorization
multitude of client types.</para> decision, doing so would introduce an additional
</listitem> argument on every services layer method. A more
<listitem> elegant approach is to use a ThreadLocal to hold the
<para><emphasis>Layering issues:</emphasis> An MVC Principal, although this would likely increase
controller or view is simply the incorrect development time to a point where it would become
architectural layer to implement authorization more economical (on a cost-benefit basis) to simply
decisions concerning services layer methods or use a dedicated security
domain object instances. Whilst the Principal may be framework.</para></listitem><listitem><para><emphasis>Authorisation
passed to the services layer to enable it to make code quality:</emphasis> It is often said of web
the authorization decision, doing so would introduce frameworks that they "make it easier to do the right
an additional argument on every services layer things, and harder to do the wrong things". Security
method. A more elegant approach is to use a frameworks are the same, because they are designed
ThreadLocal to hold the Principal, although this in an abstract manner for a wide range of purposes.
would likely increase development time to a point Writing your own authorization code from scratch
where it would become more economical (on a does not provide the "design check" a framework
cost-benefit basis) to simply use a dedicated would offer, and in-house authorization code will
security framework.</para> typically lack the improvements that emerge from
</listitem> widespread deployment, peer review and new versions.
<listitem> </para></listitem></orderedlist></para></listitem></orderedlist></para><para>
<para><emphasis>Authorisation code quality:</emphasis> For simple applications, servlet specification security may just be enough.
It is often said of web frameworks that they "make Although when considered within the context of web container portability,
it easier to do the right things, and harder to do configuration requirements, limited web request security flexibility, and
the wrong things". Security frameworks are the same, non-existent services layer and domain object instance security, it becomes
because they are designed in an abstract manner for clear why developers often look to alternative solutions. </para></answer>
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. </para>
</listitem>
</orderedlist></para>
</listitem>
</orderedlist></para>
<para> 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. </para>
</answer>
</qandaentry> </qandaentry>
<qandaentry xml:id="faq-requirements"> <qandaentry xml:id="faq-requirements">
<question> <question><para>What Java and Spring Framework versions are
<para>What Java and Spring Framework versions are required?</para> required?</para></question>
</question> <answer><para> Spring Security 2.0.x requires a minimum JDK version of 1.4 and is
<answer> built against Spring 2.0.x. It should also be compatible with applications
<para> Spring Security 2.0.x requires a minimum JDK version of 1.4 and is built using Spring 2.5.x. </para><para> Spring Security 3.0 requires JDK 1.5 as a
against Spring 2.0.x. It should also be compatible with applications using minimum and will also require Spring 3.0. </para></answer>
Spring 2.5.x. </para>
<para> Spring Security 3.0 requires JDK 1.5 as a minimum and will also require
Spring 3.0. </para>
</answer>
</qandaentry> </qandaentry>
<qandaentry xml:id="faq-start-simple"> <qandaentry xml:id="faq-start-simple">
<question> <question><para> I'm new to Spring Security and I need to build an application that
<para> 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 supports CAS single sign-on over HTTPS, while allowing Basic authentication
locally for certain URLs, authenticating against multiple back end user locally for certain URLs, authenticating against multiple back end user
information sources (LDAP and JDBC). I've copied some configuration files I information sources (LDAP and JDBC). I've copied some configuration files I
found but it doesn't work. What could be wrong? </para> found but it doesn't work. What could be wrong? </para><para>Or subsititute
<para>Or subsititute an alternative complex scenario...</para> an alternative complex scenario...</para></question>
</question> <answer><para> Realistically, you need an understanding of the technolgies you are
<answer>
<para> Realistically, you need an understanding of the technolgies you are
intending to use before you can successfully build applications with them. intending to use before you can successfully build applications with them.
Security is complicated. Setting up a simple configuration using a login Security is complicated. Setting up a simple configuration using a login
form and some hard-coded users using Spring Security's namespace is 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 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 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 LDAP servers and install SSL certificates properly. So you need to take
things one step at a time. </para> things one step at a time. </para><para> From a Spring Security perspective,
<para> From a Spring Security perspective, the first thing you should do is the first thing you should do is follow the <quote>Getting Started</quote>
follow the <quote>Getting Started</quote> guide on the web site. This will guide on the web site. This will take you through a series of steps to get
take you through a series of steps to get up and running and get some idea up and running and get some idea of how the framework operates. If you are
of how the framework operates. If you are using other technologies which you using other technologies which you aren't familiar with then you should do
aren't familiar with then you should do some research and try to make sure some research and try to make sure you can use them in isolation before
you can use them in isolation before combining them in a complex system. combining them in a complex system. </para></answer>
</para>
</answer>
</qandaentry> </qandaentry>
</qandadiv> </qandadiv>
<qandadiv> <qandadiv>
<title>Common Problems</title> <title>Common Problems</title>
<qandaentry xml:id="faq-login-loop"> <qandaentry xml:id="faq-login-loop">
<question> <question><para>My application goes into an "endless loop" when I try to login,
<para>My application goes into an "endless loop" when I try to login, what's what's going on?</para></question>
going on?</para> <answer><para>A common user problem with infinite loop and redirecting to the login
</question> page is caused by accidently configuring the login page as a "secured"
<answer> resource. Make sure your configuration allows anonymous access to the login
<para>A common user problem with infinite loop and redirecting to the login page page, either by excluding it from the security filter chain or marking it as
is caused by accidently configuring the login page as a "secured" resource. requiring ROLE_ANONYMOUS.</para><para>If your AccessDecisionManager includes
Make sure your configuration allows anonymous access to the login page, an AuthenticatedVoter, you can use the attribute
either by excluding it from the security filter chain or marking it as "IS_AUTHENTICATED_ANONYMOUSLY". This is automatically available if you are
requiring ROLE_ANONYMOUS.</para> using the standard namespace configuration setup. </para><para> From Spring
<para>If your AccessDecisionManager includes an AutheticatedVoter, you can use Security 2.0.1 onwards, when you are using namespace-based configuration, a
the attribute "IS_AUTHENTICATED_ANONYMOUSLY". This is automatically check will be made on loading the application context and a warning message
available if you are using the standard namespace configuration setup. </para> logged if your login page appears to be protected. </para></answer>
<para> 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. </para>
</answer>
</qandaentry> </qandaentry>
<qandaentry xml:id="faq-anon-access-denied"> <qandaentry xml:id="faq-anon-access-denied">
<question> <question><para>I get an exception with the message "Access is denied (user is
<para>I get an exception with the message "Access is denied (user is anonymous);". What's wrong?</para></question>
anonymous);". What's wrong?</para> <answer><para> This is a debug level message which occurs the first time an
</question> anonymous user attempts to access a protected resource.
<answer>
<para> This is a debug level message which occurs the first time an anonymous
user attempts to access a protected resource.
<programlisting> <programlisting>
DEBUG [ExceptionTranslationFilter] - Access is denied (user is anonymous); redirecting to authentication entry point DEBUG [ExceptionTranslationFilter] - Access is denied (user is anonymous); redirecting to authentication entry point
org.springframework.security.AccessDeniedException: Access is denied org.springframework.security.AccessDeniedException: Access is denied
at org.springframework.security.vote.AffirmativeBased.decide(AffirmativeBased.java:68) at org.springframework.security.vote.AffirmativeBased.decide(AffirmativeBased.java:68)
at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:262) at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:262)
</programlisting> </programlisting>
It is normal and shouldn't be anything to worry about. </para> It is normal and shouldn't be anything to worry about. </para></answer>
</answer>
</qandaentry> </qandaentry>
<qandaentry xml:id="faq-cached-secure-page"> <qandaentry xml:id="faq-cached-secure-page">
<question> <question><para>Why can I still see a secured page even after I've logged out of my
<para>Why can I still see a secured page even after I've logged out of my application?</para> application?</para></question>
</question> <answer><para>The most common reason for this is that your browser has cached the
<answer> page and you are seeing a copy which is being retrieved from the browsers
<para>The most common reason for this is that your browser has cached the page and you are seeing a cache. Verify this by checking whether the browser is actually sending the
copy which is being retrieved from the browsers cache. Verify this by checking whether the browser is actually sending request (check your server access logs, the debug log or use a suitable
the request (check your server access logs, the debug log or use a suitable browser debugging plugin such as <quote>Tamper Data</quote> browser debugging plugin such as <quote>Tamper Data</quote> for Firefox).
for Firefox). This has nothing to do with Spring Security and you should configure your application or server to set the This has nothing to do with Spring Security and you should configure your
appropriate <literal>Cache-Control</literal> response headers. Note that SSL requests are never cached.</para> application or server to set the appropriate
</answer> <literal>Cache-Control</literal> response headers. Note that SSL
requests are never cached.</para></answer>
</qandaentry> </qandaentry>
<qandaentry xml:id="auth-exception-credentials-not-found"> <qandaentry xml:id="auth-exception-credentials-not-found">
<question> <question><para>I get an exception with the message "An Authentication object was
<para>I get an exception with the message "An Authentication object was not not found in the SecurityContext". What's wrong?</para></question>
found in the SecurityContext". What's wrong?</para> <answer><para> This is a another debug level message which occurs the first time an
</question>
<answer>
<para> 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 anonymous user attempts to access a protected resource, but when you do not
have an <classname>AnonymousAuthenticationFilter</classname> in your filter chain configuration. have an <classname>AnonymousAuthenticationFilter</classname> in your filter
chain configuration.
<programlisting> <programlisting>
DEBUG [ExceptionTranslationFilter] - Authentication exception occurred; redirecting to authentication entry point DEBUG [ExceptionTranslationFilter] - Authentication exception occurred; redirecting to authentication entry point
org.springframework.security.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext 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.credentialsNotFound(AbstractSecurityInterceptor.java:342)
at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:254) at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:254)
</programlisting> </programlisting>
It is normal and shouldn't be anything to worry about. </para> It is normal and shouldn't be anything to worry about. </para></answer>
</answer>
</qandaentry> </qandaentry>
<qandaentry xml:id="faq-tomcat-https-session"> <qandaentry xml:id="faq-tomcat-https-session">
<question> <question><para> I'm using Tomcat and have enabled HTTPS for my login page,
<para> I'm using Tomcat and have enabled HTTPS for my login page, switching back switching back to HTTP afterwards. It doesn't work - I just end up back at
to HTTP afterwards. It doesn't work - I just end up back at the login page the login page after authenticating. </para></question>
after authenticating. </para> <answer><para> This happens because Tomcat sessions created under HTTPS cannot
</question>
<answer>
<para> This happens because Tomcat sessions created under HTTPS cannot
subsequently be used under HTTP and any session state is lost (including the subsequently be used under HTTP and any session state is lost (including the
security context information). Starting a session in HTTP first should work security context information). Starting a session in HTTP first should work
as the session cookie won't be marked as secure. </para> as the session cookie won't be marked as secure. </para></answer>
</answer>
</qandaentry> </qandaentry>
<qandaentry xml:id="faq-no-security-on-forward"> <qandaentry xml:id="faq-no-security-on-forward">
<question> <question><para> I'm forwarding a request to another URL using the
<para> I'm forwarding a request to another URL using the RequestDispatcher, but RequestDispatcher, but my security constraints aren't being applied.
my security constraints aren't being applied. </para> </para></question>
</question> <answer><para> Filters are not applied by default to forwards or includes. If you
<answer> really want the security filters to be applied to forwards and/or includes,
<para> Filters are not applied by default to forwards or includes. If you really then you have to configure these explicitly in your web.xml using the
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
&lt;dispatcher&gt; element, a child element of &lt;filter-mapping&gt;. &lt;dispatcher&gt; element, a child element of &lt;filter-mapping&gt;.
</para> </para></answer>
</answer>
</qandaentry> </qandaentry>
<qandaentry xml:id="faq-session-listener-missing"> <qandaentry xml:id="faq-session-listener-missing">
<question> <question><para> I'm trying to use the concurrent session-control support but it
<para> I'm trying to use the concurrent session-control support but it won't let won't let me log back in, even if I'm sure I've logged out and haven't
me log back in, even if I'm sure I've logged out and haven't exceeded the exceeded the allowed sessions. </para></question>
allowed sessions. </para> <answer><para>Make sure you have added the listener to your web.xml file. It is
</question>
<answer>
<para>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 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 when a session is destroyed. Without it, the session information will not be
removed from the registry.</para> removed from the registry.</para><programlisting><![CDATA[
<programlisting><![CDATA[
<listener> <listener>
<listener-class>org.springframework.security.ui.session.HttpSessionEventPublisher</listener-class> <listener-class>org.springframework.security.ui.session.HttpSessionEventPublisher</listener-class>
</listener> ]]> </listener> ]]>
</programlisting> </programlisting></answer>
</answer>
</qandaentry> </qandaentry>
<qandaentry xml:id="faq-no-filters-no-context"> <qandaentry xml:id="faq-no-filters-no-context">
<question> <question><para>I have a user who has definitely been authenticated, but when I try
<para>I have a user who has definitely been authenticated, but when I try to to access the <classname>SecurityContextHolder</classname> during some
access the <classname>SecurityContextHolder</classname> during some
requests, the <interfacename>Authentication</interfacename> is null. Why requests, the <interfacename>Authentication</interfacename> is null. Why
can't I see the user information? </para> can't I see the user information? </para></question>
</question> <answer><para>If you have excluded the request from the security filter chain using
<answer> the attribute <literal>filters='none'</literal> in the
<para>If you have excluded the request from the security filter chain using the
attribute <literal>filters='none'</literal> in the
<literal>&lt;intercept-url></literal> element that matches the URL <literal>&lt;intercept-url></literal> element that matches the URL
pattern, then the <classname>SecurityContextHolder</classname> will not be pattern, then the <classname>SecurityContextHolder</classname> will not be
populated for that request. Check the debug log to see whether the request 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, is passing through the filter chain. (You are reading the debug log,
right?).</para> right?).</para></answer>
</answer>
</qandaentry> </qandaentry>
<qandaentry xml:id="faq-method-security-in-web-context"> <qandaentry xml:id="faq-method-security-in-web-context">
<question><para>I have added Spring Security's &lt;global-method-security&gt; element to my application context but if I add <question><para>I have added Spring Security's &lt;global-method-security&gt;
security annotations to my Spring MVC controller beans (Struts actions etc.) then they don't seem to have an effect.</para> element to my application context but if I add security annotations to my
</question> Spring MVC controller beans (Struts actions etc.) then they don't seem to
<answer><para> have an effect.</para></question>
The application context which holds the Spring MVC beans for the dispatcher servlet is a child application context <answer><para> The application context which holds the Spring MVC beans for the
of the main application context which is loaded using the <classname>ContextLoaderListener</classname> you define in your dispatcher servlet is a child application context of the main application
<filename>web.xml</filename>. The beans in the child context are not visible in the parent context so you need to either context which is loaded using the
move the &lt;global-method-security&gt; declaration to the web context or moved the beans you want secured into the main <classname>ContextLoaderListener</classname> you define in your
application context. <filename>web.xml</filename>. The beans in the child context are not
</para> visible in the parent context so you need to either move the
<para>Generally we would recommend applying method security at the service layer rather than on individual web &lt;global-method-security&gt; declaration to the web context or moved the
controllers.</para> beans you want secured into the main application context.
</answer> </para><para>Generally we would recommend applying method security at the
service layer rather than on individual web controllers.</para></answer>
</qandaentry> </qandaentry>
</qandadiv> </qandadiv>
<qandadiv> <qandadiv>
<title>Spring Security Architecture Questions</title> <title>Spring Security Architecture Questions</title>
<qandaentry xml:id="faq-where-is-class-x"> <qandaentry xml:id="faq-where-is-class-x">
<question> <question><para>How do I know which package class X is in?</para></question>
<para>How do I know which package class X is in?</para> <answer><para>The best way of locating classes is by installing the Spring Security
</question>
<answer>
<para>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 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 modules the project is divided up into. Add these to your project source
path and you can navigate directly to Spring Security classes path and you can navigate directly to Spring Security classes
(<command>Ctrl-Shift-T</command> in Eclipse). This also makes debugging (<command>Ctrl-Shift-T</command> in Eclipse). This also makes debugging
easer and allows you to troubleshoot exceptions by looking directly at the easer and allows you to troubleshoot exceptions by looking directly at the
code where they occur to see what's going on there. </para> code where they occur to see what's going on there. </para></answer>
</answer>
</qandaentry> </qandaentry>
<qandaentry xml:id="faq-namespace-to-bean-mapping"> <qandaentry xml:id="faq-namespace-to-bean-mapping">
<question> <question><para>How do the namespace elements map to conventional bean
<para>How do the namespace elements map to conventional bean configurations?</para></question>
configurations?</para> <answer><para>There is a general overview of what beans are created by the namespace
</question> in the namespace appendix of the reference guide. If want to know the full
<answer>
<para>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 <filename>spring-security-config</filename> details then the code is in the <filename>spring-security-config</filename>
module within the Spring Security 3.0 distribution. You should probably read module within the Spring Security 3.0 distribution. You should probably read
the chapters on namespace parsing in the standard Spring Framework reference the chapters on namespace parsing in the standard Spring Framework reference
documentation first. </para> documentation first. </para></answer>
</answer>
</qandaentry> </qandaentry>
</qandadiv> </qandadiv>
<qandadiv> <qandadiv>
<title>Common <quote>Howto</quote> Requests</title> <title>Common <quote>Howto</quote> Requests</title>
<qandaentry xml:id="faq-extra-login-fields"> <qandaentry xml:id="faq-extra-login-fields">
<question> <question><para>I need to login in with more information than just the username. How
<para>I need to login in with more information than just the username. How do I do I add support for extra login fields (e.g. a company
add support for extra login fields (e.g. a company name)?</para> name)?</para></question>
</question> <answer><para>This question comes up repeatedly in the Spring Security forum so you
<answer> will find more information there by searching the archives (or through
<para>This question comes up repeatedly in the Spring Security forum so you will google).</para><para> The submitted login information is processed by an
find more information there by searching the archives (or through instance of <classname>UsernamePasswordAuthenticationFilter</classname>. You
google).</para> will need to customize this class to handle the extra data field(s). One
<para> The submitted login information is processed by an instance of option is to use your own customized authentication token class (rather than
<classname>UsernamePasswordAuthenticationFilter</classname>. You will need to the standard <classname>UsernamePasswordAuthenticationToken</classname>),
customize this class to handle the extra data field(s). One option is to use another is simply to concatenate the extra fields with the username (for
your own customized authentication token class (rather than the standard example, using a ":" as the separator) and pass them in the username
<classname>UsernamePasswordAuthenticationToken</classname>), another is property of <classname>UsernamePasswordAuthenticationToken</classname>.
simply to concatenate the extra fields with the username (for example, using </para><para> You will also need to customize the actual authentication
a ":" as the separator) and pass them in the username property of process. If you are using a custom authentication token class, for example,
<classname>UsernamePasswordAuthenticationToken</classname>. </para> you will have to write an <classname>AuthenticationProvider</classname> to
<para> You will also need to customize the actual authentication process. If you handle it (or extend the standard
are using a custom authentication token class, for example, you will have to <classname>DaoAuthenticationProvider</classname>). If you have
write an <classname>AuthenticationProvider</classname> to handle it (or concatenated the fields, you can implement your own
extend the standard <classname>DaoAuthenticationProvider</classname>). If
you have concatenated the fields, you can implement your own
<interfacename>UserDetailsService</interfacename> which splits them up <interfacename>UserDetailsService</interfacename> which splits them up
and loads the appropriate user data for authentication. </para> and loads the appropriate user data for authentication. </para></answer>
</answer>
</qandaentry> </qandaentry>
<qandaentry xml:id="faq-dynamic-url-metadata"> <qandaentry xml:id="faq-dynamic-url-metadata">
<question> <question><para>How do I define the secured URLs within an application
<para>How do I define the secured URLs within an application dynamically?</para></question>
dynamically?</para> <answer><para>People often ask about how to store the mapping between secured URLs
</question> and security metadata attributes in a database, rather than in the
<answer> application context. </para><para> The first thing you should ask yourself
<para>People often ask about how to store the mapping between secured URLs and is if you really need to do this. If an application requires securing, then
security metadata attributes in a database, rather than in the application it also requires that the security be tested thoroughly based on a defined
context. </para> policy. It may require auditing and acceptance testing before being rolled
<para> The first thing you should ask yourself is if you really need to do this. out into a production environment. A security-conscious organization should
If an application requires securing, then it also requires that the security be aware that the benefits of their diligent testing process could be wiped
be tested thoroughly based on a defined policy. It may require auditing and out instantly by allowing the security settings to be modified at runtime by
acceptance testing before being rolled out into a production environment. A changing a row or two in a configuration database. If you have taken this
security-conscious organization should be aware that the benefits of their into account (perhaps using multiple layers of security within your
diligent testing process could be wiped out instantly by allowing the application) then Spring Security allows you to fully customize the source
security settings to be modified at runtime by changing a row or two in a of security metadata. You can make it fully dynamic if you choose.
configuration database. If you have taken this into account (perhaps using </para><para> Both method and web security are protected by subclasses of
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. </para>
<para> Both method and web security are protected by subclasses of
<classname>AbstractSecurityInterceptor</classname> which is configured <classname>AbstractSecurityInterceptor</classname> which is configured
with a <interfacename>SecurityMetadataSource</interfacename> from which it with a <interfacename>SecurityMetadataSource</interfacename> from which it
obtains the metadata for a particular method or filter invocation <footnote> obtains the metadata for a particular method or filter invocation
<para>This class previouly went by the rather obscure name of <footnote><para>This class previouly went by the rather obscure name
<classname>ObjectDefinitionSource</classname>, but has been of <classname>ObjectDefinitionSource</classname>, but has been
renamed in Spring Security 3.0</para> renamed in Spring Security 3.0</para></footnote>. For web security,
</footnote>. For web security, the interceptor class is the interceptor class is <classname>FilterSecurityInterceptor</classname>
<classname>FilterSecurityInterceptor</classname> and it uses the marker and it uses the marker interface
interface
<interfacename>FilterInvocationSecurityMetadataSource</interfacename>. <interfacename>FilterInvocationSecurityMetadataSource</interfacename>.
The <quote>secured object</quote> type it operates on is a The <quote>secured object</quote> type it operates on is a
<classname>FilterInvocation</classname>. The default implementation <classname>FilterInvocation</classname>. The default implementation
@ -416,20 +341,20 @@
when configuring the interceptor explicitly, stores the list of URL patterns when configuring the interceptor explicitly, stores the list of URL patterns
and their corresponding list of <quote>configuration attributes</quote> and their corresponding list of <quote>configuration attributes</quote>
(instances of <interfacename>ConfigAttribute</interfacename>) in an (instances of <interfacename>ConfigAttribute</interfacename>) in an
in-memory map. </para> in-memory map. </para><para> To load the data from an alternative source,
<para> To load the data from an alternative source, you must be using an you must be using an explicitly declared security filter chain (typically
explicitly declared security filter chain (typically Spring Security's Spring Security's <classname>FilterChainProxy</classname>) in order to
<classname>FilterChainProxy</classname>) in order to customize the customize the <classname>FilterSecurityInterceptor</classname> bean. You
<classname>FilterSecurityInterceptor</classname> bean. You can't use the can't use the namespace. You would then implement
namespace. You would then implement
<interfacename>FilterInvocationSecurityMetadataSource</interfacename> to <interfacename>FilterInvocationSecurityMetadataSource</interfacename> to
load the data as you please for a particular load the data as you please for a particular
<classname>FilterInvocation</classname><footnote> <classname>FilterInvocation</classname><footnote><para>The
<para>The <classname>FilterInvocation</classname> object contains the <classname>FilterInvocation</classname> object contains the
<classname>HttpServletRequest</classname>, so you can obtain the <classname>HttpServletRequest</classname>, so you can obtain the
URL or any other relevant information on which to base your decision URL or any other relevant information on which to base your decision
on what the list of returned attributes will contain.</para> on what the list of returned attributes will
</footnote>. A very basic outline would look something like this: <programlisting language="java"><![CDATA[ contain.</para></footnote>. A very basic outline would look something
like this: <programlisting language="java"><![CDATA[
public class MyFilterSecurityMetadataSource implements FilterInvocationSecurityMetadataSource { public class MyFilterSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
public List<ConfigAttribute> getAttributes(Object object) { public List<ConfigAttribute> getAttributes(Object object) {
@ -454,54 +379,46 @@
} }
]]></programlisting> For more information, look at the code for ]]></programlisting> For more information, look at the code for
<classname>DefaultFilterInvocationSecurityMetadataSource</classname>. <classname>DefaultFilterInvocationSecurityMetadataSource</classname>.
</para> </para></answer>
</answer>
</qandaentry> </qandaentry>
<qandaentry xml:id="faq-what-dependencies"> <qandaentry xml:id="faq-what-dependencies">
<question> <question><para>How do I know which dependencies to add to my application to work
<para>How do I know which dependencies to add to my application to work with with Spring Security?</para></question>
Spring Security?</para> <answer><para>It will depend on what features you are using and what type of
</question> application you are developing. With Spring Security 3.0, the project jars
<answer> are divided into clearly distinct areas of functionality, so it is
<para>It will depend on what features you are using and what type of application straightforward to work out which Spring Security jars you need from your
you are developing. With Spring Security 3.0, the project jars are divided application requirements. All applications will need the
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
<filename>spring-security-core</filename> jar. If you're developing a <filename>spring-security-core</filename> jar. If you're developing a
web application, you need the <filename>spring-security-web</filename> jar. web application, you need the <filename>spring-security-web</filename> jar.
If you're using security namespace configuration you need the If you're using security namespace configuration you need the
<filename>spring-security-config</filename> jar, for LDAP support you <filename>spring-security-config</filename> jar, for LDAP support you
need the <filename>spring-security-ldap</filename> jar and so on. </para> need the <filename>spring-security-ldap</filename> jar and so on.
<para> For third-party jars the situation isn't always quite so obvious. A good </para><para> For third-party jars the situation isn't always quite so
starting point is to copy those from one of the pre-built sample obvious. A good starting point is to copy those from one of the pre-built
applications WEB-INF/lib directories. For a basic application, you can start sample applications WEB-INF/lib directories. For a basic application, you
with the tutorial sample. If you want to use LDAP, with an embedded test can start with the tutorial sample. If you want to use LDAP, with an
server, then use the LDAP sample as a starting point. </para> embedded test server, then use the LDAP sample as a starting point.
<para> If you are building your project with maven, then adding the appropriate </para><para> If you are building your project with maven, then adding the
Spring Security modules as dependencies to your pom.xml will automatically appropriate Spring Security modules as dependencies to your pom.xml will
pull in the core jars that the framework requires. Any which are marked as automatically pull in the core jars that the framework requires. Any which
"optional" in the Spring Security POM files will have to be added to your are marked as "optional" in the Spring Security POM files will have to be
own pom.xml file if you need them. </para> added to your own pom.xml file if you need them. </para></answer>
</answer>
</qandaentry> </qandaentry>
<qandaentry xml:id="faq-ldap-authorities"> <qandaentry xml:id="faq-ldap-authorities">
<question> <question><para>How do I authenticate against LDAP but load user roles from a
<para>How do I authenticate against LDAP but load user roles from a database?</para></question>
database?</para> <answer><para> The <code>LdapAuthenticationProvider</code> bean (which handles
</question> normal LDAP authentication in Spring Security) is configured with two
<answer> separate strategy interfaces, one which performs the authenticatation and
<para> The <code>LdapAuthenticationProvider</code> bean (which handles normal one which loads the user authorities, called
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
<interfacename>LdapAuthenticator</interfacename> and <interfacename>LdapAuthenticator</interfacename> and
<interfacename>LdapAuthoritiesPopulator</interfacename> respectively. <interfacename>LdapAuthoritiesPopulator</interfacename> respectively.
The <classname>DefaultLdapAuthoitiesPopulator</classname> loads the user The <classname>DefaultLdapAuthoritiesPopulator</classname> loads the user
authorities from the LDAP directory and has various configuration parameters authorities from the LDAP directory and has various configuration parameters
to allow you to specify how these should be retrieved. </para> to allow you to specify how these should be retrieved. </para><para> To use
<para> To use JDBC instead, you can implement the interface yourself, using JDBC instead, you can implement the interface yourself, using whatever SQL
whatever SQL is appropriate for your schema: <programlisting language="java"><![CDATA[ is appropriate for your schema: <programlisting language="java"><![CDATA[
public class MyAuthoritiesPopulator implements LdapAuthoritiesPopulator { public class MyAuthoritiesPopulator implements LdapAuthoritiesPopulator {
@Autowired @Autowired
JdbcTemplate template; JdbcTemplate template;
@ -523,8 +440,7 @@
section on configuring LDAP using explicit Spring beans in the LDAP chapter section on configuring LDAP using explicit Spring beans in the LDAP chapter
of the reference manual. Note that you can't use the namespace for of the reference manual. Note that you can't use the namespace for
configuration in this case. You should also consult the Javadoc for the configuration in this case. You should also consult the Javadoc for the
relevant classes and interfaces. </para> relevant classes and interfaces. </para></answer>
</answer>
</qandaentry> </qandaentry>
</qandadiv> </qandadiv>
</qandaset> </qandaset>

View File

@ -2,18 +2,22 @@
use strict; use strict;
# Get list of links to class src packages # Get list of links to class src packages from Javadoc
system("curl http://static.springframework.org/spring-security/site/xref/allclasses-frame.html > allclasses-frame.html"); #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`; 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
#<a href="org/springframework/security/vote/AbstractAccessDecisionManager.html" target="classFrame">AbstractAccessDecisionManager</a> #<a href="org/springframework/security/vote/AbstractAccessDecisionManager.html" target="classFrame">AbstractAccessDecisionManager</a>
# Javadoc format
#<A HREF="org/springframework/security/acls/afterinvocation/AbstractAclProvider.html" title="class in org.springframework.security.acls.afterinvocation" target="classFrame">AbstractAclProvider</A>
my %classnames_to_src; my %classnames_to_src;
while ($_ = pop @all_classes) { while ($_ = pop @all_classes) {
next unless $_ =~ /<a href="(.*)" target="classFrame">(([a-zA-Z0-9_]+?))<\/a>/; next unless $_ =~ /<A HREF="(.*)" title.*>(([a-zA-Z0-9_]+?))<\/A>/;
print "Adding class $1, $2\n";
$classnames_to_src{$2} = $1; $classnames_to_src{$2} = $1;
} }

View File

@ -488,8 +488,8 @@
configuration as web security, but this can be overridden as explained above <xref configuration as web security, but this can be overridden as explained above <xref
xlink:href="#nsa-access-decision-manager-ref"/>, using the same attribute. </para> xlink:href="#nsa-access-decision-manager-ref"/>, using the same attribute. </para>
<section> <section>
<title>The <literal>&lt;secured-annotations&gt;</literal> and <title>The <literal>secured-annotations</literal> and
<literal>&lt;jsr250-annotations&gt;</literal> Attributes</title> <literal>jsr250-annotations</literal> Attributes</title>
<para> Setting these to "true" will enable support for Spring Security's own <para> Setting these to "true" will enable support for Spring Security's own
<literal>@Secured</literal> annotations and JSR-250 annotations, respectively. They are <literal>@Secured</literal> annotations and JSR-250 annotations, respectively. They are
both disabled by default. Use of JSR-250 annotations also adds a both disabled by default. Use of JSR-250 annotations also adds a

View File

@ -221,12 +221,15 @@ boolean supports(Class clazz);
that there is at least one configuration attribute that an that there is at least one configuration attribute that an
<interfacename>AccessDecisionVoter</interfacename> will vote to grant access for. This <interfacename>AccessDecisionVoter</interfacename> will vote to grant access for. This
latter (recommended) approach is usually achieved through a <literal>ROLE_USER</literal> or latter (recommended) approach is usually achieved through a <literal>ROLE_USER</literal> or
<literal>ROLE_AUTHENTICATED</literal> configuration attribute</para> <literal>ROLE_AUTHENTICATED</literal> configuration attribute.</para>
<!-- TODO: Move to ACL section and add reference here -->
<!--
<section xml:id="after-invocation-acl-aware"> <section xml:id="after-invocation-acl-aware">
<info> <info>
<title>ACL-Aware AfterInvocationProviders</title> <title>ACL-Aware AfterInvocationProviders</title>
</info> </info>
<!-- TODO: Move to ACL section and add reference here -->
<para>A common services layer method we've all written at one stage or another looks like <para>A common services layer method we've all written at one stage or another looks like
this:</para> this:</para>
<para> <para>
@ -279,8 +282,10 @@ boolean supports(Class clazz);
<literal>requirePermission</literal>s.</para> <literal>requirePermission</literal>s.</para>
<para>The Contacts sample application demonstrates these two <para>The Contacts sample application demonstrates these two
<literal>AfterInvocationProvider</literal>s.</para> <literal>AfterInvocationProvider</literal>s.</para>
</section> </section> -->
</section> </section>
<!-- TODO: Move taglibs to a separate chapter which describes them all
<section xml:id="authorization-taglibs"> <section xml:id="authorization-taglibs">
<info> <info>
<title>Authorization Tag Libraries</title> <title>Authorization Tag Libraries</title>
@ -350,5 +355,5 @@ boolean supports(Class clazz);
<para><literal>AclTag</literal> is part of the old ACL module and should be considered <para><literal>AclTag</literal> is part of the old ACL module and should be considered
deprecated. For the sake of historical reference, works exactly the samae as deprecated. For the sake of historical reference, works exactly the samae as
<literal>AccessControlListTag</literal>.</para> <literal>AccessControlListTag</literal>.</para>
</section> </section> -->
</chapter> </chapter>

View File

@ -97,9 +97,8 @@
returned from the configured <interfacename>UserDetailsService</interfacename>. A returned from the configured <interfacename>UserDetailsService</interfacename>. A
<interfacename>SaltSource</interfacename> enables the passwords to be populated <interfacename>SaltSource</interfacename> enables the passwords to be populated
with a "salt", which enhances the security of the passwords in the authentication 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 <link
<!-- TODO: Add sections on password encoding and user caching to advaced topics --> xlink:href="core-services-password-encodin">below</link>. </para>
</para>
</section> </section>
</section> </section>
<section> <section>
@ -203,4 +202,78 @@
--> -->
</section> </section>
</section> </section>
<section xml:id="core-services-password-encoding">
<title>Password Encoding</title>
<para>Spring Security's <interfacename>PasswordEncoder</interfacename> 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 <quote>hashed</quote> using a digest alogirthm
such as MD5 or SHA.</para>
<section>
<title>What is a hash?</title>
<para>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 <quote>password</quote> (in hexadecimal) is
<programlisting>
5f4dcc3b5aa765d61d8327deb882cf99
</programlisting> A hash is
<quote>one-way</quote> 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.</para>
</section>
<section>
<title>Adding Salt to a Hash</title>
<para> 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
<literal>5f4dcc3b5aa765d61d8327deb882cf99</literal> using google, you will
quickly find the original word <quote>password</quote>. 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 <quote>salt</quote> 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
<interfacename>SaltSource</interfacename> 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).</para>
</section>
<section>
<title> Hashing and Authentication</title>
<para>When an authentication provider (such as Spring Security's
<classname>DaoAuthenticationProvider</classname> 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
<classname>Md5PasswordEncoder</classname>, 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)<footnote><para>You can configure
the encoder to use Base 64 instead of hex by setting the
<literal>encodeHashAsBase64</literal> property to
<literal>true</literal>. Check the Javadoc for
<classname>MessageDigestPasswordEncoder</classname> and its parent
classes for more information.</para></footnote>. 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 <classname>BasePasswordEncoder</classname>. If you want to generate
encoded passwords directly in Java for storage in your user database, then you can
use the <methodname>encodePassword</methodname> method on the
<interfacename>PasswordEncoder</interfacename>.</para>
</section>
</section>
</chapter> </chapter>

View File

@ -0,0 +1,48 @@
<?xml version="1.0" encoding="UTF-8"?>
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="el-access"
xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Expression-Based Access Control</title>
<para> 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. </para>
<section xml:id="el-access-web">
<title>Web Security Expressions</title>
<para> To use expressions to secure individual URLs, you would first need to set the
<literal>use-expressions</literal> attribute in the <literal>&lt;http></literal>
element to <literal>true</literal>. Spring Security will then expect the
<literal>access</literal> attributes of the <literal>&lt;intercept-url></literal>
elements to contain Spring EL expressions. The expressions should evaluate to a boolean,
defining whether access should be allowed or not. For example:<programlisting><![CDATA[
<http use-expressions="true">
<intercept-url pattern="/admin*"
access="hasRole('admin') and hasIpAddress('192.168.1.0/24')"/>
...
</http>
]]></programlisting>Here we have defined that the "admin" area of an application should only be
available to users who have the granted authority <quote>admin</quote> and whose IP
address matches a local subnet. The expressions <literal>hasRole</literal> and
<literal>hasIpAddress</literal> are both built in expressions, which are defined by
the <classname>WebSecurityExpressionRoot</classname> 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
<interfacename>HttpServletRequest</interfacename> object under the name
<quote>request</quote> so you can invoke the request directly in an
expression.</para>
<para>If expressions are being used, a <classname>WebExpressionVoter</classname> will be
added to the <interfacename>AccessDecisionManager</interfacename> 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.</para>
</section>
<section>
<title>Method Security Expressions</title>
<para>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.</para>
</section>
</chapter>

View File

@ -461,7 +461,11 @@
<user name="http://jimi.hendrix.myopenid.com/" password="notused" <user name="http://jimi.hendrix.myopenid.com/" password="notused"
authorities="ROLE_USER" /> authorities="ROLE_USER" />
]]></programlisting> You should be able to login using the <literal>myopenid.com</literal> site to ]]></programlisting> You should be able to login using the <literal>myopenid.com</literal> site to
authenticate. </para> authenticate. It is also possible to select a specific
<interfacename>UserDetailsService</interfacename> bean for use OpenID by setting the
<literal>user-service-ref</literal> attribute on the <literal>openid-login</literal>
element. See the previous section on <link xlink:href="#ns-auth-providers">authentication
providers</link> for more information. </para>
</section> </section>
<section xml:id="ns-custom-filters"> <section xml:id="ns-custom-filters">
<title>Adding in Your Own Filters</title> <title>Adding in Your Own Filters</title>
@ -564,10 +568,11 @@
<title>Method Security</title> <title>Method Security</title>
<para>From version 2.0 onwards Spring Security has improved support substantially for adding <para>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 security to your service layer methods. It provides support for JSR-250 security as well as
the framework's native <literal>@Secured</literal> annotation. You can apply security to a the framework's original <literal>@Secured</literal> annotation. From 3.0 you can also make
single bean, using the <literal>intercept-methods</literal> element to decorate the bean use of new <link xlink:href="el-access">expression-based annotations</link>.
declaration, or you can secure multiple beans across the entire service layer using the You can apply security to a single bean, using the
AspectJ style pointcuts. </para> <literal>intercept-methods</literal> element to decorate the bean declaration, or you can
secure multiple beans across the entire service layer using the AspectJ style pointcuts. </para>
<section xml:id="ns-global-method"> <section xml:id="ns-global-method">
<title>The <literal>&lt;global-method-security&gt;</literal> Element</title> <title>The <literal>&lt;global-method-security&gt;</literal> Element</title>
<para> This element is used to enable annotation-based security in your application (by <para> This element is used to enable annotation-based security in your application (by
@ -581,9 +586,7 @@
</programlisting> Adding an annotation to a method (on an class or interface) would then limit </programlisting> 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 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 set of attributes for the method. These will be passed to the
<interfacename>AccessDecisionManager</interfacename> for it to make the actual decision. <interfacename>AccessDecisionManager</interfacename> for it to make the actual decision:
This example is taken from the <link xlink:href="#tutorial-sample">tutorial sample</link>,
which is a good starting point if you want to use method security in your application:
<programlisting language="java"> <programlisting language="java">
public interface BankService { public interface BankService {
@ -597,6 +600,22 @@
public Account post(Account account, double amount); public Account post(Account account, double amount);
} }
</programlisting></para> </programlisting></para>
<para>To use the new expression-based syntax, you would use <programlisting><![CDATA[
<global-method-security pre-post-annotations="enabled" />
]]></programlisting>and the equivalent Java code would
be<programlisting language="java">
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);
}
</programlisting></para>
<section xml:id="ns-protect-pointcut"> <section xml:id="ns-protect-pointcut">
<title>Adding Security Pointcuts using <literal>protect-pointcut</literal></title> <title>Adding Security Pointcuts using <literal>protect-pointcut</literal></title>
<para> The use of <literal>protect-pointcut</literal> is particularly powerful, as it allows <para> The use of <literal>protect-pointcut</literal> is particularly powerful, as it allows
@ -642,7 +661,7 @@
... ...
</global-method-security> </global-method-security>
]]></programlisting></para> ]]></programlisting></para>
<para> The syntax for web security is the same, but on the <literal>http</literal> element: <programlisting language="xml"><![CDATA[ <para> The syntax for web security is the same, but on the <literal>http</literal> element: <programlisting language="xml"><![CDATA[
<http access-decision-manager-ref="myAccessDecisionManagerBean"> <http access-decision-manager-ref="myAccessDecisionManagerBean">
... ...
</http> </http>

View File

@ -159,6 +159,7 @@
</partintro> </partintro>
<xi:include href="authorization-common.xml"/> <xi:include href="authorization-common.xml"/>
<xi:include href="secured-objects.xml"/> <xi:include href="secured-objects.xml"/>
<xi:include href="el-access.xml"/>
</part> </part>
<part xml:id="advanced-topics"> <part xml:id="advanced-topics">
<title>Advanced Topics</title> <title>Advanced Topics</title>

View File

@ -111,15 +111,15 @@ if (principal instanceof UserDetails) {
<para> On successful authentication, <interfacename>UserDetails</interfacename> is used to <para> On successful authentication, <interfacename>UserDetails</interfacename> is used to
build the <interfacename>Authentication</interfacename> object that is stored in the build the <interfacename>Authentication</interfacename> object that is stored in the
<classname>SecurityContextHolder</classname> (more on this <link <classname>SecurityContextHolder</classname> (more on this <link
xlink:href="#tech-intro-authentication">below</link>). The good news is that we xlink:href="#tech-intro-authentication">below</link>). The good news is that we provide a
provide a number of <interfacename>UserDetailsService</interfacename> implementations, number of <interfacename>UserDetailsService</interfacename> implementations, including one
including one that uses an in-memory map (<classname>InMemoryDaoImpl</classname>) and that uses an in-memory map (<classname>InMemoryDaoImpl</classname>) and another that uses
another that uses JDBC (<classname>JdbcDaoImpl</classname>). Most users tend to JDBC (<classname>JdbcDaoImpl</classname>). Most users tend to write their own, though, with
write their own, though, with their implementations often simply sitting on top of an their implementations often simply sitting on top of an existing Data Access Object (DAO)
existing Data Access Object (DAO) that represents their employees, customers, or other users that represents their employees, customers, or other users of the application. Remember the
of the application. Remember the advantage that whatever your advantage that whatever your <interfacename>UserDetailsService</interfacename> returns can
<interfacename>UserDetailsService</interfacename> returns can always be obtained from the always be obtained from the <classname>SecurityContextHolder</classname> using the above
<classname>SecurityContextHolder</classname> using the above code fragment. </para> code fragment. </para>
</section> </section>
<section xml:id="tech-granted-authority"> <section xml:id="tech-granted-authority">
<title>GrantedAuthority</title> <title>GrantedAuthority</title>
@ -189,50 +189,31 @@ if (principal instanceof UserDetails) {
own proprietary authentication system. </para> own proprietary authentication system. </para>
<section> <section>
<title>What is authentication in Spring Security?</title> <title>What is authentication in Spring Security?</title>
<para> Let's consider a standard authentication scenario that everyone is familiar with. <orderedlist> <para> Let's consider a standard authentication scenario that everyone is familiar with.
<listitem> <orderedlist><listitem><para>A user is prompted to log in with a username and
<para>A user is prompted to log in with a username and password.</para> password.</para></listitem><listitem><para>The system (successfully) verifies that the
</listitem> password is correct for the username.</para></listitem><listitem><para>The context
<listitem> information for that user is obtained (their list of roles and so
<para>The system (successfully) verifies that the password is correct for the on).</para></listitem><listitem><para>A security context is established for the
username.</para> user</para></listitem><listitem><para>The user proceeds, potentially to perform some
</listitem> operation which is potentially protected by an access control mechanism which checks
<listitem> the required permissions for the operation against the current security context
<para>The context information for that user is obtained (their list of roles and so information. </para></listitem></orderedlist> The first three items constitute the
on).</para> authentication process so we'll take a look at how these take place within Spring
</listitem> Security.<orderedlist><listitem><para>The username and password are obtained and
<listitem> combined into an instance of
<para>A security context is established for the user</para>
</listitem>
<listitem>
<para>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. </para>
</listitem>
</orderedlist> The first three items constitute the authentication process so we'll take a
look at how these take place within Spring Security.<orderedlist>
<listitem>
<para>The username and password are obtained and combined into an instance of
<classname>UsernamePasswordAuthenticationToken</classname> (an instance of the <classname>UsernamePasswordAuthenticationToken</classname> (an instance of the
<interfacename>Authentication</interfacename> interface, which we saw <interfacename>Authentication</interfacename> interface, which we saw
earlier).</para> earlier).</para></listitem><listitem><para>The token is passed to an instance of
</listitem> <interfacename>AuthenticationManager</interfacename> for
<listitem> validation.</para></listitem><listitem><para>The
<para>The token is passed to an instance of <interfacename>AuthenticationManager</interfacename> returns a fully populated
<interfacename>AuthenticationManager</interfacename> for validation.</para>
</listitem>
<listitem>
<para>The <interfacename>AuthenticationManager</interfacename> returns a fully populated
<interfacename>Authentication</interfacename> instance on successful <interfacename>Authentication</interfacename> instance on successful
authentication.</para> authentication.</para></listitem><listitem><para>The security context is established
</listitem> by calling <code>SecurityContextHolder.getContext().setAuthentication(...)</code>,
<listitem> passing in the returned authentication object.</para></listitem></orderedlist>From
<para>The security context is established by calling that point on, the user is considered to be authenticated. Let's look at some code as an
<code>SecurityContextHolder.getContext().setAuthentication(...)</code>, passing in example.
the returned authentication object.</para>
</listitem>
</orderedlist>From that point on, the user is considered to be authenticated. Let's look at
some code as an example.
<programlisting language="java">import org.springframework.security.authentication.*; <programlisting language="java">import org.springframework.security.authentication.*;
import org.springframework.security.core.*; import org.springframework.security.core.*;
import org.springframework.security.core.authority.GrantedAuthorityImpl; import org.springframework.security.core.authority.GrantedAuthorityImpl;
@ -484,29 +465,17 @@ Successfully authenticated. Security context contains: \
<interfacename>Authentication</interfacename> if the principal has been <interfacename>Authentication</interfacename> if the principal has been
authenticated.</para> authenticated.</para>
<para><classname>AbstractSecurityInterceptor</classname> provides a consistent workflow for <para><classname>AbstractSecurityInterceptor</classname> provides a consistent workflow for
handling secure object requests, typically: <orderedlist> handling secure object requests, typically: <orderedlist><listitem><para>Look up the
<listitem> <quote>configuration attributes</quote> associated with the present
<para>Look up the <quote>configuration attributes</quote> associated with the present request</para></listitem><listitem><para>Submitting the secure object, current
request</para>
</listitem>
<listitem>
<para>Submitting the secure object, current
<interfacename>Authentication</interfacename> and configuration attributes to the <interfacename>Authentication</interfacename> and configuration attributes to the
<interfacename>AccessDecisionManager</interfacename> for an authorization <interfacename>AccessDecisionManager</interfacename> for an authorization
decision</para> decision</para></listitem><listitem><para>Optionally change the
</listitem> <interfacename>Authentication</interfacename> under which the invocation takes
<listitem> place</para></listitem><listitem><para>Allow the secure object invocation to proceed
<para>Optionally change the <interfacename>Authentication</interfacename> under which (assuming access was granted)</para></listitem><listitem><para>Call the
the invocation takes place</para> <interfacename>AfterInvocationManager</interfacename> if configured, once the
</listitem> invocation has returned.</para></listitem></orderedlist></para>
<listitem>
<para>Allow the secure object invocation to proceed (assuming access was granted)</para>
</listitem>
<listitem>
<para>Call the <interfacename>AfterInvocationManager</interfacename> if configured, once
the invocation has returned.</para>
</listitem>
</orderedlist></para>
<section xml:id="tech-intro-config-attributes"> <section xml:id="tech-intro-config-attributes">
<title>What are Configuration Attributes?</title> <title>What are Configuration Attributes?</title>
<para> A <quote>configuration attribute</quote> can be thought of as a String that has <para> A <quote>configuration attribute</quote> can be thought of as a String that has
@ -518,9 +487,9 @@ Successfully authenticated. Security context contains: \
<classname>AbstractSecurityInterceptor</classname> is configured with a <classname>AbstractSecurityInterceptor</classname> is configured with a
<interfacename>SecurityMetadataSource</interfacename> which it uses to look up the <interfacename>SecurityMetadataSource</interfacename> which it uses to look up the
attributes for a secure object. Usually this configuration will be hidden from the user. 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 <literal>&lt;intercept-url&gt;</literal> attributes on secured URLs (using the namespace <literal>&lt;intercept-url&gt;</literal>
syntax). </para> syntax).</para>
</section> </section>
<section> <section>
<title>RunAsManager</title> <title>RunAsManager</title>
@ -551,14 +520,10 @@ Successfully authenticated. Security context contains: \
or not change it in any way as it chooses.</para> or not change it in any way as it chooses.</para>
<para><classname>AbstractSecurityInterceptor</classname> and its related objects are shown <para><classname>AbstractSecurityInterceptor</classname> and its related objects are shown
in <xref linkend="abstract-security-interceptor"/>. <figure in <xref linkend="abstract-security-interceptor"/>. <figure
xml:id="abstract-security-interceptor"> xml:id="abstract-security-interceptor"><title>Security interceptors and the
<title>Security interceptors and the <quote>secure object</quote> model</title> <quote>secure object</quote> model</title><mediaobject><imageobject>
<mediaobject>
<imageobject>
<imagedata align="center" fileref="images/security-interception.png" format="PNG"/> <imagedata align="center" fileref="images/security-interception.png" format="PNG"/>
</imageobject> </imageobject></mediaobject></figure></para>
</mediaobject>
</figure></para>
</section> </section>
<section> <section>
<title>Extending the Secure Object Model</title> <title>Extending the Secure Object Model</title>