namespace-config.xml 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="ns-config"
  3. xmlns:xlink="http://www.w3.org/1999/xlink">
  4. <info>
  5. <title>Security Namespace Configuration</title>
  6. </info>
  7. <section>
  8. <title>Introduction</title>
  9. <para> Namespace configuration has been available since version 2.0 of the Spring framework. It
  10. allows you to supplement the traditional Spring beans application context syntax with elements
  11. from additional XML schema. You can find more information in the Spring <link
  12. xlink:href="http://static.springframework.org/spring/docs/2.5.x/reference/xsd-config.html">
  13. Reference Documentation</link>. A namespace element can be used simply to allow a more
  14. concise way of configuring an individual bean or, more powerfully, to define an alternative
  15. configuration syntax which more closely matches the problem domain and hides the underlying
  16. complexity from the user. A simple element may conceal the fact that multiple beans and
  17. processing steps are being added to the application context. For example, adding the following
  18. element from the security namespace to an application context will start up an embedded LDAP
  19. server for testing use within the application: <programlisting><![CDATA[
  20. <security:ldap-server />
  21. ]]></programlisting> This is much simpler than wiring up the equivalent Apache Directory Server
  22. beans. The most common alternative configuration requirements are supported by attributes on
  23. the <literal>ldap-server</literal> element and the user is isolated from worrying about which
  24. beans they need create and what the bean property names are. <footnote><para>You can find out
  25. more about the use of the <literal>ldap-server</literal> element in the chapter on <link
  26. xlink:href="#ldap">LDAP</link>.</para></footnote>. Use of a good XML editor while
  27. editing the application context file should provide information on the attributes and elements
  28. that are available. We would recommend that you try out the <link
  29. xlink:href="http://www.springsource.com/products/sts">SpringSource Tool Suite</link> as it
  30. has special features for working with standard Spring namespaces. </para>
  31. <para> To start using the security namespace in your application context, all you need to do is
  32. add the schema declaration to your application context file: <programlisting language="xml">
  33. <![CDATA[
  34. <beans xmlns="http://www.springframework.org/schema/beans"
  35. xmlns:security="http://www.springframework.org/schema/security"
  36. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  37. xsi:schemaLocation="http://www.springframework.org/schema/beans
  38. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  39. http://www.springframework.org/schema/security
  40. http://www.springframework.org/schema/security/spring-security-3.0.xsd">
  41. ...
  42. </beans>
  43. ]]></programlisting> In many of the examples you will see (and in the sample) applications, we
  44. will often use "security" as the default namespace rather than "beans", which means we can
  45. omit the prefix on all the security namespace elements, making the content easier to read. You
  46. may also want to do this if you have your application context divided up into separate files
  47. and have most of your security configuration in one of them. Your security application context
  48. file would then start like this <programlisting language="xml"><![CDATA[
  49. <beans:beans xmlns="http://www.springframework.org/schema/security"
  50. xmlns:beans="http://www.springframework.org/schema/beans"
  51. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  52. xsi:schemaLocation="http://www.springframework.org/schema/beans
  53. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  54. http://www.springframework.org/schema/security
  55. http://www.springframework.org/schema/security/spring-security-3.0.xsd">
  56. ...
  57. </beans:beans>
  58. ]]></programlisting> We'll assume this syntax is being used from now on in this chapter. </para>
  59. <section>
  60. <title>Design of the Namespace</title>
  61. <para> The namespace is designed to capture the most common uses of the framework and provide
  62. a simplified and concise syntax for enabling them within an application. The design is based
  63. around the large-scale dependencies within the framework, and can be divided up into the
  64. following areas: <itemizedlist><listitem><para>
  65. <emphasis>Web/HTTP Security</emphasis> - the most complex part. Sets up the filters
  66. and related service beans used to apply the framework authentication mechanisms, to
  67. secure URLs, render login and error pages and much
  68. more.</para></listitem><listitem><para>
  69. <emphasis>Business Object (Method) Security</emphasis> - options for securing the
  70. service layer.</para></listitem><listitem><para>
  71. <emphasis>AuthenticationManager</emphasis> - handles authentication requests from
  72. other parts of the framework.</para></listitem><listitem><para>
  73. <emphasis>AccessDecisionManager</emphasis> - provides access decisions for web and
  74. method security. A default one will be registered, but you can also choose to use a
  75. custom one, declared using normal Spring bean
  76. syntax.</para></listitem><listitem><para>
  77. <emphasis>AuthenticationProvider</emphasis>s - mechanisms against which the
  78. authentication manager authenticates users. The namespace provides supports for
  79. several standard options and also a means of adding custom beans declared using a
  80. traditional syntax. </para></listitem><listitem><para>
  81. <emphasis>UserDetailsService</emphasis> - closely related to authentication providers,
  82. but often also required by other beans.</para></listitem>
  83. <!-- todo: diagram and link to other sections which describe the interfaces -->
  84. </itemizedlist></para>
  85. <para>We'll see how these work together in the following sections.</para>
  86. </section>
  87. </section>
  88. <section xml:id="ns-getting-started">
  89. <title>Getting Started with Security Namespace Configuration</title>
  90. <para> In this section, we'll look at how you can build up a namespace configuration to use some
  91. of the main features of the framework. Let's assume you initially want to get up and running
  92. as quickly as possible and add authentication support and access control to an existing web
  93. application, with a few test logins. Then we'll look at how to change over to authenticating
  94. against a database or other security information repository. In later sections we'll introduce
  95. more advanced namespace configuration options. </para>
  96. <section xml:id="ns-web-xml">
  97. <title><literal>web.xml</literal> Configuration</title>
  98. <para> The first thing you need to do is add the following filter declaration to your
  99. <literal>web.xml</literal> file: <programlisting language="xml"><![CDATA[
  100. <filter>
  101. <filter-name>springSecurityFilterChain</filter-name>
  102. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  103. </filter>
  104. <filter-mapping>
  105. <filter-name>springSecurityFilterChain</filter-name>
  106. <url-pattern>/*</url-pattern>
  107. </filter-mapping>]]>
  108. </programlisting> This provides a hook into the Spring Security web
  109. infrastructure. <classname>DelegatingFilterProxy</classname> is a Spring Framework class
  110. which delegates to a filter implementation which is defined as a Spring bean in your
  111. application context. In this case, the bean is named
  112. <quote>springSecurityFilterChain</quote>, which is an internal infrastructure bean created
  113. by the namespace to handle web security. Note that you should not use this bean name
  114. yourself. Once you've added this to your <filename>web.xml</filename>, you're ready to start
  115. editing your application context file. Web security services are configured using the
  116. <literal>&lt;http&gt;</literal> element. </para>
  117. </section>
  118. <section xml:id="ns-minimal">
  119. <title>A Minimal <literal>&lt;http&gt;</literal> Configuration</title>
  120. <para> All you need to enable web security to begin with is <programlisting language="xml"><![CDATA[
  121. <http auto-config='true'>
  122. <intercept-url pattern="/**" access="ROLE_USER" />
  123. </http>
  124. ]]>
  125. </programlisting> Which says that we want all URLs within our application to be secured,
  126. requiring the role <literal>ROLE_USER</literal> to access them.</para>
  127. <note>
  128. <para>You can use multiple <literal>&lt;intercept-url&gt;</literal> elements to define
  129. different access requirements for different sets of URLs, but they will be evaluated in
  130. the order listed and the first match will be used. So you must put the most specific
  131. matches at the top.</para>
  132. </note>
  133. <para> To add some users, you can define a set of test data directly in the namespace: <programlisting language="xml"><![CDATA[
  134. <authentication-manager>
  135. <authentication-provider>
  136. <user-service>
  137. <user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
  138. <user name="bob" password="bobspassword" authorities="ROLE_USER" />
  139. </user-service>
  140. </authentication-provider>
  141. </authentication-manager>
  142. ]]>
  143. </programlisting></para>
  144. <sidebar>
  145. <para>If you are familiar with pre-namespace versions of the framework, you can probably
  146. already guess roughly what's going on here. The &lt;http&gt; element is responsible for
  147. creating a <classname>FilterChainProxy</classname> and the filter beans which it uses.
  148. Common issues like incorrect filter ordering are no longer an issue as the filter
  149. positions are predefined.</para>
  150. <para>The <literal>&lt;authentication-provider&gt;</literal> element creates a
  151. <classname>DaoAuthenticationProvider</classname> bean and the
  152. <literal>&lt;user-service&gt;</literal> element creates an
  153. <classname>InMemoryDaoImpl</classname>. All <literal>authentication-provider</literal>
  154. elements must be within the <literal>authentication-manager</literal> element, which
  155. creates a <classname>ProviderManager</classname> and registers the authentication
  156. providers with it. You can find more detailed information on the beans that are created in
  157. the <link xlink:href="#appendix-namespace">namespace appendix</link>. It's worth
  158. cross-checking this if you want to start understanding what the important classes in the
  159. framework are and how they are used, particularly if you want to customise things
  160. later.</para>
  161. </sidebar>
  162. <para> The configuration above defines two users, their passwords and their roles within the
  163. application (which will be used for access control). It is also possible to load user
  164. information from a standard properties file using the <literal>properties</literal>
  165. attribute on <literal>user-service</literal>. See the section on <link
  166. xlink:href="#core-services-in-memory-service">in-memory authentication</link> for more
  167. details on the file format. Using the <literal>&lt;authentication-provider&gt;</literal>
  168. element means that the user information will be used by the authentication manager to
  169. process authentication requests. You can have multiple
  170. <literal>&lt;authentication-provider&gt;</literal> elements to define different
  171. authentication sources and each will be consulted in turn.</para>
  172. <para> At this point you should be able to start up your application and you will be required
  173. to log in to proceed. Try it out, or try experimenting with the <quote>tutorial</quote>
  174. sample application that comes with the project. The above configuration actually adds quite
  175. a few services to the application because we have used the <literal>auto-config</literal>
  176. attribute. For example, form-based login processing is automatically enabled. </para>
  177. <section xml:id="ns-auto-config">
  178. <title>What does <literal>auto-config</literal> Include?</title>
  179. <para> The <literal>auto-config</literal> attribute, as we have used it above, is just a
  180. shorthand syntax for: <programlisting language="xml"><![CDATA[
  181. <http>
  182. <form-login />
  183. <http-basic />
  184. <logout />
  185. </http>
  186. ]]></programlisting> These other elements are responsible for setting up form-login, basic
  187. authentication and logout handling services respectively <footnote><para>In versions prior
  188. to 3.0, this list also included remember-me functionality. This could cause some
  189. confusing errors with some configurations and was removed in 3.0. In 3.0, the addition
  190. of an <classname>AnonymousAuthenticationFilter</classname> is part of the default
  191. <literal>&lt;http></literal> configuration, so the <literal>&lt;anonymous
  192. /></literal> element is added regardless of whether <literal>auto-config</literal>
  193. is enabled.</para></footnote> . They each have attributes which can be used to alter
  194. their behaviour. </para>
  195. </section>
  196. <section xml:id="ns-form-and-basic">
  197. <title>Form and Basic Login Options</title>
  198. <para> You might be wondering where the login form came from when you were prompted to log
  199. in, since we made no mention of any HTML files or JSPs. In fact, since we didn't
  200. explicitly set a URL for the login page, Spring Security generates one automatically,
  201. based on the features that are enabled and using standard values for the URL which
  202. processes the submitted login, the default target URL the user will be sent to after
  203. loggin in and so on. However, the namespace offers plenty of support to allow you to
  204. customize these options. For example, if you want to supply your own login page, you could
  205. use: <programlisting language="xml"><![CDATA[
  206. <http auto-config='true'>
  207. <intercept-url pattern="/login.jsp*" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
  208. <intercept-url pattern="/**" access="ROLE_USER" />
  209. <form-login login-page='/login.jsp'/>
  210. </http>
  211. ]]>
  212. </programlisting> Note that you can still use <literal>auto-config</literal>. The
  213. <literal>form-login</literal> element just overrides the default settings. Also note
  214. that we've added an extra <literal>intercept-url</literal> element to say that any
  215. requests for the login page should be available to anonymous users <footnote><para>See the
  216. chapter on <link xlink:href="#anonymous">anonymous authentication</link> for more
  217. details.</para></footnote>. Otherwise the request would be matched by the pattern
  218. <literal>/**</literal> and it wouldn't be possible to access the login page itself! This
  219. is a common configuration error and will result in an infinite loop in the application.
  220. Spring Security will emit a warning in the log if your login page appears to be secured.
  221. It is also possible to have all requests matching a particular pattern bypass the security
  222. filter chain completely: <programlisting language="xml"><![CDATA[
  223. <http auto-config='true'>
  224. <intercept-url pattern="/css/**" filters="none"/>
  225. <intercept-url pattern="/login.jsp*" filters="none"/>
  226. <intercept-url pattern="/**" access="ROLE_USER" />
  227. <form-login login-page='/login.jsp'/>
  228. </http>
  229. ]]>
  230. </programlisting> Note that these requests will be completely oblivious to Spring
  231. Security, so you will not be able to access information on the current user or call
  232. secured methods during the request. </para>
  233. <para>If you want to use basic authentication instead of form login, then change the
  234. configuration to <programlisting language="xml"><![CDATA[
  235. <http auto-config='true'>
  236. <intercept-url pattern="/**" access="ROLE_USER" />
  237. <http-basic />
  238. </http>
  239. ]]>
  240. </programlisting> Basic authentication will then take precedence and will be used to
  241. prompt for a login when a user attempts to access a protected resource. Form login is
  242. still available in this configuration if you wish to use it, for example through a login
  243. form embedded in another web page. </para>
  244. <section xml:id="ns-form-target">
  245. <title>Setting a Default Post-Login Destination</title>
  246. <para> If a form login isn't prompted by an attempt to access a protected resource, the
  247. <literal>default-target-url</literal> option comes into play. This is the URL the user
  248. will be taken to after logging in, and defaults to "/". You can also configure things so
  249. that they user <emphasis>always</emphasis> ends up at this page (regardless of whether
  250. the login was "on-demand" or they explicitly chose to log in) by setting the
  251. <literal>always-use-default-target</literal> attribute to "true". This is useful if
  252. your application always requires that the user starts at a "home" page, for example: <programlisting language="xml"><![CDATA[
  253. <http>
  254. <intercept-url pattern='/login.htm*' filters='none'/>
  255. <intercept-url pattern='/**' access='ROLE_USER' />
  256. <form-login login-page='/login.htm' default-target-url='/home.htm'
  257. always-use-default-target='true' />
  258. </http>
  259. ]]>
  260. </programlisting></para>
  261. </section>
  262. </section>
  263. </section>
  264. <section xml:id="ns-auth-providers">
  265. <title>Using other Authentication Providers</title>
  266. <para> In practice you will need a more scalable source of user information than a few names
  267. added to the application context file. Most likely you will want to store your user
  268. information in something like a database or an LDAP server. LDAP namespace configuration is
  269. dealt with in the <link xlink:href="#ldap">LDAP chapter</link>, so we won't cover it here.
  270. If you have a custom implementation of Spring Security's
  271. <classname>UserDetailsService</classname>, called "myUserDetailsService" in your
  272. application context, then you can authenticate against this using <programlisting language="xml"><![CDATA[
  273. <authentication-manager>
  274. <authentication-provider user-service-ref='myUserDetailsService'/>
  275. </authentication-manager>
  276. ]]>
  277. </programlisting> If you want to use a database, then you can use <programlisting language="xml"><![CDATA[
  278. <authentication-manager>
  279. <authentication-provider>
  280. <jdbc-user-service data-source-ref="securityDataSource"/>
  281. </authentication-provider>
  282. </authentication-manager>
  283. ]]>
  284. </programlisting> Where "securityDataSource" is the name of a
  285. <classname>DataSource</classname> bean in the application context, pointing at a database
  286. containing the standard Spring Security <link xlink:href="#db_schema_users_authorities">user
  287. data tables</link>. Alternatively, you could configure a Spring Security
  288. <classname>JdbcDaoImpl</classname> bean and point at that using the
  289. <literal>user-service-ref</literal> attribute: <programlisting language="xml"><![CDATA[
  290. <authentication-manager>
  291. <authentication-provider user-service-ref='myUserDetailsService'/>
  292. </authentication-manager>
  293. <beans:bean id="myUserDetailsService"
  294. class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">
  295. <beans:property name="dataSource" ref="dataSource"/>
  296. </beans:bean>
  297. ]]>
  298. </programlisting> You can also use standard
  299. <interfacename>AuthenticationProvider</interfacename> beans as follows <programlisting language="xml"><![CDATA[
  300. <authentication-manager>
  301. <authentication-provider ref='myAuthenticationProvider'/>
  302. </authentication-manager>
  303. ]]>
  304. </programlisting> where <literal>myAuthenticationProvider</literal> is the name of a
  305. bean in your application context which implements
  306. <interfacename>AuthenticationProvider</interfacename>. See <xref linkend="ns-auth-manager"
  307. /> for more on information on how the Spring Security
  308. <interfacename>AuthenticationManager</interfacename> is configured using the namespace. </para>
  309. <section xml:id="ns-password-encoder">
  310. <title>Adding a Password Encoder</title>
  311. <para> Often your password data will be encoded using a hashing algorithm. This is supported
  312. by the <literal>&lt;password-encoder&gt;</literal> element. With SHA encoded passwords,
  313. the original authentication provider configuration would look like this: <programlisting language="xml"><![CDATA[
  314. <authentication-manager>
  315. <authentication-provider>
  316. <password-encoder hash="sha"/>
  317. <user-service>
  318. <user name="jimi" password="d7e6351eaa13189a5a3641bab846c8e8c69ba39f"
  319. authorities="ROLE_USER, ROLE_ADMIN" />
  320. <user name="bob" password="4e7421b1b8765d8f9406d87e7cc6aa784c4ab97f"
  321. authorities="ROLE_USER" />
  322. </user-service>
  323. </authentication-provider>
  324. </authentication-manager>
  325. ]]>
  326. </programlisting></para>
  327. <para> When using hashed passwords, it's also a good idea to use a salt value to protect
  328. against dictionary attacks and Spring Security supports this too. Ideally you would want
  329. to use a randomly generated salt value for each user, but you can use any property of the
  330. <classname>UserDetails</classname> object which is loaded by your
  331. <classname>UserDetailsService</classname>. For example, to use the
  332. <literal>username</literal> property, you would use <programlisting><![CDATA[
  333. <password-encoder hash="sha">
  334. <salt-source user-property="username"/>
  335. </password-encoder>
  336. ]]></programlisting> You can use a custom password encoder bean by using the
  337. <literal>ref</literal> attribute of <literal>password-encoder</literal>. This should
  338. contain the name of a bean in the application context which is an instance of Spring
  339. Security's <interfacename>PasswordEncoder</interfacename> interface. </para>
  340. </section>
  341. </section>
  342. </section>
  343. <section xml:id="ns-web-advanced">
  344. <title>Advanced Web Features</title>
  345. <section xml:id="ns-remember-me">
  346. <title>Remember-Me Authentication</title>
  347. <para>See the separate <link xlink:href="#remember-me">Remember-Me chapter</link> for
  348. information on remember-me namespace configuration.</para>
  349. </section>
  350. <section xml:id="ns-requires-channel">
  351. <title>Adding HTTP/HTTPS Channel Security</title>
  352. <para>If your application supports both HTTP and HTTPS, and you require that particular URLs
  353. can only be accessed over HTTPS, then this is directly supported using the
  354. <literal>requires-channel</literal> attribute on <literal>&lt;intercept-url&gt;</literal>: <programlisting language="xml"><![CDATA[
  355. <http>
  356. <intercept-url pattern="/secure/**" access="ROLE_USER" requires-channel="https"/>
  357. <intercept-url pattern="/**" access="ROLE_USER" requires-channel="any"/>
  358. ...
  359. </http>]]>
  360. </programlisting>With this configuration in place, if a user attempts to access
  361. anything matching the "/secure/**" pattern using HTTP, they will first be redirected to an
  362. HTTPS URL. The available options are "http", "https" or "any". Using the value "any" means
  363. that either HTTP or HTTPS can be used. </para>
  364. <para>If your application uses non-standard ports for HTTP and/or HTTPS, you can specify a
  365. list of port mappings as follows: <programlisting><![CDATA[
  366. <http>
  367. ...
  368. <port-mappings>
  369. <port-mapping http="9080" https="9443"/>
  370. </port-mappings>
  371. </http>]]>
  372. </programlisting><!--You can find a more in-depth discussion of channel security
  373. in <xref xlink:href="#channel-security"/--></para>
  374. </section>
  375. <section xml:id="ns-session-mgmt">
  376. <title>Session Management</title>
  377. <section>
  378. <title>Detecting Timeouts</title>
  379. <para> You can configure Spring Security to detect the submission of an invalid session ID
  380. and redirect the user to an appropriate URL. This is achieved through the
  381. <literal>session-management</literal> element:<![CDATA[
  382. <http>
  383. ...
  384. <session-management invalid-session-url="/sessionTimeout.htm" />
  385. </http>]]></para>
  386. </section>
  387. <section xml:id="ns-concurrent-sessions">
  388. <title>Concurrent Session Control</title>
  389. <para>If you wish to place constraints on a single user's ability to log in to your
  390. application, Spring Security supports this out of the box with the following simple
  391. additions. First you need to add the following listener to your
  392. <filename>web.xml</filename> file to keep Spring Security updated about session
  393. lifecycle events: <![CDATA[
  394. <listener>
  395. <listener-class>
  396. org.springframework.security.web.session.HttpSessionEventPublisher
  397. </listener-class>
  398. </listener>
  399. ]]> Then add the following lines to your application context: <programlisting language="xml"><![CDATA[
  400. <http>
  401. ...
  402. <session-management>
  403. <concurrency-control max-sessions="1" />
  404. </session-management>
  405. </http>]]>
  406. </programlisting> This will prevent a user from logging in multiple times - a
  407. second login will cause the first to be invalidated. Often you would prefer to prevent a
  408. second login, in which case you can use <programlisting language="xml"><![CDATA[
  409. <http>
  410. ...
  411. <session-management>
  412. <concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
  413. </session-management>
  414. </http>]]>
  415. </programlisting>The second login will then be rejected. By
  416. <quote>rejected</quote>, we mean that the user will be sent to the
  417. <literal>authentication-failure-url</literal> if form-based login is being used. If the
  418. second authentication takes place through another non-interactive mechanism, such as
  419. <quote>remember-me</quote>, an <quote>unauthorized</quote> (402) error will be sent to
  420. the client. If instead you want to use an error page, you can add the attribute
  421. <literal>session-authentication-error-url</literal> to the
  422. <literal>session-management</literal> element. </para>
  423. <para>If you are using a customized authentication filter for form-based login, then you
  424. have to configure concurrent session control support explicitly. More details can be found
  425. in the <link xlink:href="#session-mgmt">Session Management chapter</link>. </para>
  426. </section>
  427. <section xml:id="ns-session-fixation">
  428. <title>Session Fixation Attack Protection</title>
  429. <para>
  430. <link xlink:href="http://en.wikipedia.org/wiki/Session_fixation">Session fixation</link>
  431. attacks are a potential risk where it is possible for a malicious attacker to create a
  432. session by accessing a site, then persuade another user to log in with the same session
  433. (by sending them a link containing the session identifier as a parameter, for example).
  434. Spring Security protects against this automatically by creating a new session when a user
  435. logs in. If you don't require this protection, or it conflicts with some other
  436. requirement, you can control the behaviour using the
  437. <literal>session-fixation-protection</literal> attribute on
  438. <literal>&lt;session-management&gt;</literal>, which has three options
  439. <itemizedlist><listitem><para><literal>migrateSession</literal> - creates a new
  440. session and copies the existing session attributes to the new session. This is the
  441. default.</para></listitem><listitem><para><literal>none</literal> - Don't do
  442. anything. The original session will be
  443. retained.</para></listitem><listitem><para><literal>newSession</literal> - Create
  444. a new "clean" session, without copying the existing session
  445. data.</para></listitem></itemizedlist></para>
  446. </section>
  447. </section>
  448. <section xml:id="ns-openid">
  449. <title>OpenID Login</title>
  450. <para>The namespace supports <link xlink:href="http://openid.net/">OpenID</link> login either
  451. instead of, or in addition to normal form-based login, with a simple change: <programlisting language="xml"><![CDATA[
  452. <http>
  453. <intercept-url pattern="/**" access="ROLE_USER" />
  454. <openid-login />
  455. </http>
  456. ]]></programlisting> You should then register yourself with an OpenID provider (such as
  457. myopenid.com), and add the user information to your in-memory
  458. <literal>&lt;user-service&gt;</literal>: <programlisting><![CDATA[
  459. <user name="http://jimi.hendrix.myopenid.com/" password="notused"
  460. authorities="ROLE_USER" />
  461. ]]></programlisting> You should be able to login using the <literal>myopenid.com</literal> site to
  462. authenticate. It is also possible to select a specific
  463. <interfacename>UserDetailsService</interfacename> bean for use OpenID by setting the
  464. <literal>user-service-ref</literal> attribute on the <literal>openid-login</literal>
  465. element. See the previous section on <link xlink:href="#ns-auth-providers">authentication
  466. providers</link> for more information. </para>
  467. </section>
  468. <section xml:id="ns-custom-filters">
  469. <title>Adding in Your Own Filters</title>
  470. <para>If you've used Spring Security before, you'll know that the framework maintains a chain
  471. of filters in order to apply its services. You may want to add your own filters to the stack
  472. at particular locations or use a Spring Security filter for which there isn't currently a
  473. namespace configuration option (CAS, for example). Or you might want to use a customized
  474. version of a standard namespace filter, such as the
  475. <literal>UsernamePasswordAuthenticationFilter</literal> which is created by the
  476. <literal>&lt;form-login&gt;</literal> element, taking advantage of some of the extra
  477. configuration options which are available by using the bean explicitly. How can you do this
  478. with namespace configuration, since the filter chain is not directly exposed? </para>
  479. <para>The order of the filters is always strictly enforced when using the namespace. When the
  480. application context is being created, the filter beans are sorted by the namespace handling
  481. code and the standard Spring Security filters each have an alias in the namespace and a
  482. well-known position.<note><para>In previous versions, the sorting took place after the
  483. filter instances had been created, during post-processing of the application context. In
  484. version 3.0+ the sorting is now done at the bean metadata level, before the classes have
  485. been instantiated. This has implications for how you add your own filters to the stack
  486. as the entire filter list must be known during the parsing of the
  487. <literal>&lt;http></literal> element, so the syntax has changed slightly in
  488. 3.0.</para></note>The filters, aliases and namespace elements/attributes which create
  489. the filters are shown in <xref linkend="filter-stack"/>. The filters are listed in the order
  490. in which they occur in the filter chain. <table xml:id="filter-stack"><title>Standard Filter
  491. Aliases and Ordering</title><tgroup cols="3" align="left"><thead><row><entry
  492. align="center">Alias</entry><entry align="center">Filter Class</entry><entry
  493. align="center">Namespace Element or
  494. Attribute</entry></row></thead><tbody><row><entry>
  495. CHANNEL_FILTER</entry><entry><literal>ChannelProcessingFilter</literal></entry><entry><literal>http/intercept-url@requires-channel</literal></entry></row><row><entry>
  496. CONCURRENT_SESSION_FILTER</entry><entry><literal>ConcurrentSessionFilter</literal>
  497. </entry><entry><literal>session-management/concurrency-control</literal></entry></row><row><entry>
  498. SECURITY_CONTEXT_FILTER</entry><entry><classname>SecurityContextPersistenceFilter</classname></entry><entry><literal>http</literal></entry></row><row><entry>
  499. LOGOUT_FILTER
  500. </entry><entry><literal>LogoutFilter</literal></entry><entry><literal>http/logout</literal></entry></row><row><entry>
  501. X509_FILTER
  502. </entry><entry><literal>X509AuthenticationFilter</literal></entry><entry><literal>http/x509</literal></entry></row><row><entry>
  503. PRE_AUTH_FILTER
  504. </entry><entry><literal>AstractPreAuthenticatedProcessingFilter</literal>
  505. Subclasses</entry><entry>N/A</entry></row><row><entry> CAS_FILTER
  506. </entry><entry><literal>CasAuthenticationFilter</literal></entry><entry>N/A</entry></row><row><entry>
  507. FORM_LOGIN_FILTER
  508. </entry><entry><literal>UsernamePasswordAuthenticationFilter</literal></entry><entry><literal>http/form-login</literal></entry></row><row><entry>
  509. BASIC_AUTH_FILTER
  510. </entry><entry><literal>BasicAuthenticationFilter</literal></entry><entry><literal>http/http-basic</literal></entry></row><row><entry>
  511. SERVLET_API_SUPPORT_FILTER</entry><entry><literal>SecurityContextHolderAwareFilter</literal></entry><entry><literal>http/@servlet-api-provision</literal></entry></row><row><entry>
  512. REMEMBER_ME_FILTER
  513. </entry><entry><classname>RememberMeAuthenticationFilter</classname></entry><entry><literal>http/remember-me</literal></entry></row><row><entry>
  514. ANONYMOUS_FILTER
  515. </entry><entry><literal>AnonymousAuthenticationFilter</literal></entry><entry><literal>http/anonymous</literal></entry></row><row><entry>
  516. SESSION_MANAGEMENT_FILTER</entry><entry><literal>SessionManagementFilter</literal></entry><entry><literal>session-management</literal></entry></row><row><entry>EXCEPTION_TRANSLATION_FILTER
  517. </entry><entry><classname>ExceptionTranslationFilter</classname></entry><entry><literal>http</literal></entry></row><row><entry>
  518. FILTER_SECURITY_INTERCEPTOR
  519. </entry><entry><classname>FilterSecurityInterceptor</classname></entry><entry><literal>http</literal></entry></row><row><entry>
  520. SWITCH_USER_FILTER
  521. </entry><entry><literal>SwitchUserFilter</literal></entry><entry>N/A</entry></row></tbody></tgroup></table>
  522. You can add your own filter to the stack, using the <literal>custom-filter</literal> element
  523. and one of these names to specify the position your filter should appear at: <programlisting language="xml"><![CDATA[
  524. <http>
  525. <custom-filter position="FORM_LOGIN_FILTER" ref="myFilter" />
  526. </http>
  527. <beans:bean id="myFilter" class="com.mycompany.MySpecialAuthenticationFilter"/>
  528. ]]>
  529. </programlisting> You can also use the <literal>after</literal> or <literal>before</literal>
  530. attributes if you want your filter to be inserted before or after another filter in the
  531. stack. The names "FIRST" and "LAST" can be used with the <literal>position</literal>
  532. attribute to indicate that you want your filter to appear before or after the entire stack,
  533. respectively. </para>
  534. <tip>
  535. <title>Avoiding filter position conflicts</title>
  536. <para> If you are inserting a custom filter which may occupy the same position as one of the
  537. standard filters created by the namespace then it's important that you don't include the
  538. namespace versions by mistake. Avoid using the <literal>auto-config</literal> attribute
  539. and remove any elements which create filters whose functionality you want to replace. </para>
  540. <para> Note that you can't replace filters which are created by the use of the
  541. <literal>&lt;http&gt;</literal> element itself -
  542. <classname>SecurityContextPersistenceFilter</classname>,
  543. <classname>ExceptionTranslationFilter</classname> or
  544. <classname>FilterSecurityInterceptor</classname>. </para>
  545. </tip>
  546. <para> If you're replacing a namespace filter which requires an authentication entry point
  547. (i.e. where the authentication process is triggered by an attempt by an unauthenticated user
  548. to access to a secured resource), you will need to add a custom entry point bean too. </para>
  549. <section xml:id="ns-entry-point-ref">
  550. <title>Setting a Custom <interfacename>AuthenticationEntryPoint</interfacename></title>
  551. <para> If you aren't using form login, OpenID or basic authentication through the namespace,
  552. you may want to define an authentication filter and entry point using a traditional bean
  553. syntax and link them into the namespace, as we've just seen. The corresponding
  554. <interfacename>AuthenticationEntryPoint</interfacename> can be set using the
  555. <literal>entry-point-ref</literal> attribute on the <literal>&lt;http&gt;</literal>
  556. element. </para>
  557. <para> The CAS sample application is a good example of the use of custom beans with the
  558. namespace, including this syntax. If you aren't familiar with authentication entry points,
  559. they are discussed in the <link xlink:href="#tech-intro-auth-entry-point">technical
  560. overview</link> chapter. </para>
  561. </section>
  562. </section>
  563. </section>
  564. <section xml:id="ns-method-security">
  565. <title>Method Security</title>
  566. <para>From version 2.0 onwards Spring Security has improved support substantially for adding
  567. security to your service layer methods. It provides support for JSR-250 security as well as
  568. the framework's original <literal>@Secured</literal> annotation. From 3.0 you can also make
  569. use of new <link xlink:href="el-access">expression-based annotations</link>.
  570. You can apply security to a single bean, using the
  571. <literal>intercept-methods</literal> element to decorate the bean declaration, or you can
  572. secure multiple beans across the entire service layer using the AspectJ style pointcuts. </para>
  573. <section xml:id="ns-global-method">
  574. <title>The <literal>&lt;global-method-security&gt;</literal> Element</title>
  575. <para> This element is used to enable annotation-based security in your application (by
  576. setting the appropriate attributes on the element), and also to group together security
  577. pointcut declarations which will be applied across your entire application context. You
  578. should only declare one <literal>&lt;global-method-security&gt;</literal> element. The
  579. following declaration would enable support for both Spring Security's
  580. <literal>@Secured</literal>, and JSR-250 annotations: <programlisting><![CDATA[
  581. <global-method-security secured-annotations="enabled" jsr250-annotations="enabled"/>
  582. ]]>
  583. </programlisting> Adding an annotation to a method (on an class or interface) would then limit
  584. the access to that method accordingly. Spring Security's native annotation support defines a
  585. set of attributes for the method. These will be passed to the
  586. <interfacename>AccessDecisionManager</interfacename> for it to make the actual decision:
  587. <programlisting language="java">
  588. public interface BankService {
  589. @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
  590. public Account readAccount(Long id);
  591. @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
  592. public Account[] findAccounts();
  593. @Secured("ROLE_TELLER")
  594. public Account post(Account account, double amount);
  595. }
  596. </programlisting></para>
  597. <para>To use the new expression-based syntax, you would use <programlisting><![CDATA[
  598. <global-method-security pre-post-annotations="enabled" />
  599. ]]></programlisting>and the equivalent Java code would
  600. be<programlisting language="java">
  601. public interface BankService {
  602. @PreAuthorize("isAnonymous()")
  603. public Account readAccount(Long id);
  604. @PreAuthorize("isAnonymous()")
  605. public Account[] findAccounts();
  606. @PreAuthorize("hasAuthority('ROLE_TELLER')")
  607. public Account post(Account account, double amount);
  608. }
  609. </programlisting></para>
  610. <section xml:id="ns-protect-pointcut">
  611. <title>Adding Security Pointcuts using <literal>protect-pointcut</literal></title>
  612. <para> The use of <literal>protect-pointcut</literal> is particularly powerful, as it allows
  613. you to apply security to many beans with only a simple declaration. Consider the following
  614. example: <programlisting language="xml"><![CDATA[
  615. <global-method-security>
  616. <protect-pointcut expression="execution(* com.mycompany.*Service.*(..))"
  617. access="ROLE_USER"/>
  618. </global-method-security>
  619. ]]>
  620. </programlisting> This will protect all methods on beans declared in the application
  621. context whose classes are in the <literal>com.mycompany</literal> package and whose class
  622. names end in "Service". Only users with the <literal>ROLE_USER</literal> role will be able
  623. to invoke these methods. As with URL matching, the most specific matches must come first
  624. in the list of pointcuts, as the first matching expression will be used. </para>
  625. </section>
  626. </section>
  627. </section>
  628. <section xml:id="ns-access-manager">
  629. <title>The Default AccessDecisionManager</title>
  630. <para> This section assumes you have some knowledge of the underlying architecture for
  631. access-control within Spring Security. If you don't you can skip it and come back to it later,
  632. as this section is only really relevant for people who need to do some customization in order
  633. to use more than simple role based security. </para>
  634. <para> When you use a namespace configuration, a default instance of
  635. <interfacename>AccessDecisionManager</interfacename> is automatically registered for you and
  636. will be used for making access decisions for method invocations and web URL access, based on
  637. the access attributes you specify in your <literal>intercept-url</literal> and
  638. <literal>protect-pointcut</literal> declarations (and in annotations if you are using
  639. annotation secured methods). </para>
  640. <para> The default strategy is to use an <classname>AffirmativeBased</classname>
  641. <interfacename>AccessDecisionManager</interfacename> with a <classname>RoleVoter</classname>
  642. and an <classname>AuthenticatedVoter</classname>. </para>
  643. <section xml:id="ns-custom-access-mgr">
  644. <title>Customizing the AccessDecisionManager</title>
  645. <para> If you need to use a more complicated access control strategy then it is easy to set an
  646. alternative for both method and web security. </para>
  647. <para> For method security, you do this by setting the
  648. <literal>access-decision-manager-ref</literal> attribute on
  649. <literal>global-method-security</literal> to the Id of the appropriate
  650. <interfacename>AccessDecisionManager</interfacename> bean in the application context: <programlisting language="xml"><![CDATA[
  651. <global-method-security access-decision-manager-ref="myAccessDecisionManagerBean">
  652. ...
  653. </global-method-security>
  654. ]]></programlisting></para>
  655. <para> The syntax for web security is the same, but on the <literal>http</literal> element: <programlisting language="xml"><![CDATA[
  656. <http access-decision-manager-ref="myAccessDecisionManagerBean">
  657. ...
  658. </http>
  659. ]]></programlisting></para>
  660. </section>
  661. </section>
  662. <section xml:id="ns-auth-manager">
  663. <title>The Authentication Manager and the Namespace</title>
  664. <para> The main interface which provides authentication services in Spring Security is the
  665. <interfacename>AuthenticationManager</interfacename>. This is usually an instance of Spring
  666. Security's <classname>ProviderManager</classname> class, which you may already be familiar
  667. with if you've used the framework before. If not, it will be covered later, in <link
  668. xlink:href="#tech-intro-authentication"/>. The bean instance is registered using the
  669. <literal>authentication-manager</literal> namespace element. You can't use a custom
  670. <classname>AuthenticationManager</classname> if you are using either HTTP or method security
  671. through the namespace, but this should not be a problem as you have full control over the
  672. <classname>AuthenticationProvider</classname>s that are used.</para>
  673. <para> You may want to register additional <classname>AuthenticationProvider</classname> beans
  674. with the <classname>ProviderManager</classname> and you can do this using the
  675. <literal>&lt;authentication-provider&gt;</literal> element with the <literal>ref</literal>
  676. attribute, where the value of the attribute is the name of the provider bean you want to add.
  677. For example: <programlisting language="xml"><![CDATA[
  678. <authentication-manager>
  679. <authentication-provider ref="casAuthenticationProvider"/>
  680. </authentication-manager>
  681. <bean id="casAuthenticationProvider"
  682. class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
  683. <security:custom-authentication-provider />
  684. ...
  685. </bean>
  686. ]]></programlisting></para>
  687. <para> Another common requirement is that another bean in the context may require a reference to
  688. the <interfacename>AuthenticationManager</interfacename>. There is a special element which
  689. lets you register an alias for the <interfacename>AuthenticationManager</interfacename> and
  690. you can then use this name elsewhere in your application context. <programlisting language="xml"><![CDATA[
  691. <security:authentication-manager alias="authenticationManager">
  692. ...
  693. </security:authentication-manager>
  694. <bean id="customizedFormLoginFilter"
  695. class="com.somecompany.security.web.CustomFormLoginFilter">
  696. <property name="authenticationManager" ref="authenticationManager"/>
  697. ...
  698. </bean>
  699. ]]></programlisting></para>
  700. </section>
  701. </chapter>