technical-overview.xml 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  1. <chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="technical-overview"
  2. xmlns:xlink="http://www.w3.org/1999/xlink">
  3. <info>
  4. <title>Technical Overview</title>
  5. </info>
  6. <section xml:id="runtime-environment">
  7. <info>
  8. <title>Runtime Environment</title>
  9. </info>
  10. <para>Spring Security 3.0 requires a Java 5.0 Runtime Environment or higher. As Spring
  11. Security aims to operate in a self-contained manner, there is no need to place any
  12. special configuration files into your Java Runtime Environment. In particular, there is
  13. no need to configure a special Java Authentication and Authorization Service (JAAS)
  14. policy file or place Spring Security into common classpath locations.</para>
  15. <para>Similarly, if you are using an EJB Container or Servlet Container there is no need to
  16. put any special configuration files anywhere, nor include Spring Security in a server
  17. classloader. All the required files will be contained within your application.</para>
  18. <para>This design offers maximum deployment time flexibility, as you can simply copy your
  19. target artifact (be it a JAR, WAR or EAR) from one system to another and it will
  20. immediately work.</para>
  21. </section>
  22. <section xml:id="core-components">
  23. <info>
  24. <title>Core Components</title>
  25. </info>
  26. <para>In Spring Security 3.0, the contents of the <filename>spring-security-core</filename>
  27. jar were stripped down to the bare minimum. It no longer contains any code related to
  28. web-application security, LDAP or namespace configuration. We'll take a look here at
  29. some of the Java types that you'll find in the core module. They represent the building
  30. blocks of the the framework, so if you ever need to go beyond a simple namespace
  31. configuration then it's important that you understand what they are, even if you don't
  32. actually need to interact with them directly.</para>
  33. <section>
  34. <title> SecurityContextHolder, SecurityContext and Authentication Objects </title>
  35. <para>The most fundamental object is <classname>SecurityContextHolder</classname>. This
  36. is where we store details of the present security context of the application, which
  37. includes details of the principal currently using the application. By default the
  38. <classname>SecurityContextHolder</classname> uses a <literal>ThreadLocal</literal>
  39. to store these details, which means that the security context is always available to
  40. methods in the same thread of execution, even if the security context is not
  41. explicitly passed around as an argument to those methods. Using a
  42. <literal>ThreadLocal</literal> in this way is quite safe if care is taken to clear
  43. the thread after the present principal's request is processed. Of course, Spring
  44. Security takes care of this for you automatically so there is no need to worry about
  45. it.</para>
  46. <para>Some applications aren't entirely suitable for using a
  47. <literal>ThreadLocal</literal>, because of the specific way they work with threads.
  48. For example, a Swing client might want all threads in a Java Virtual Machine to use
  49. the same security context. <classname>SecurityContextHolder</classname> can be
  50. configured with a strategy on startup to specify how you would like the context to
  51. be stored. For a standalone application you would use the
  52. <literal>SecurityContextHolder.MODE_GLOBAL</literal> strategy. Other applications
  53. might want to have threads spawned by the secure thread also assume the same
  54. security identity. This is achieved by using
  55. <literal>SecurityContextHolder.MODE_INHERITABLETHREADLOCAL</literal>. You can change
  56. the mode from the default <literal>SecurityContextHolder.MODE_THREADLOCAL</literal>
  57. in two ways. The first is to set a system property, the second is to call a static
  58. method on <classname>SecurityContextHolder</classname>. Most applications won't need
  59. to change from the default, but if you do, take a look at the JavaDocs for
  60. <classname>SecurityContextHolder</classname> to learn more.</para>
  61. <section>
  62. <title>Obtaining information about the current user</title>
  63. <para>Inside the <classname>SecurityContextHolder</classname> we store details of
  64. the principal currently interacting with the application. Spring Security uses
  65. an <interfacename>Authentication</interfacename> object to represent this
  66. information. You won't normally need to create an
  67. <interfacename>Authentication</interfacename> object yourself, but it is fairly
  68. common for users to query the <interfacename>Authentication</interfacename>
  69. object. You can use the following code block - from anywhere in your application
  70. - to obtain the name of the currently authenticated user, for example:</para>
  71. <programlisting language="java">
  72. Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
  73. if (principal instanceof UserDetails) {
  74. String username = ((UserDetails)principal).getUsername();
  75. } else {
  76. String username = principal.toString();
  77. }</programlisting>
  78. <para>The object returned by the call to <methodname>getContext()</methodname> is an
  79. instance of the <interfacename>SecurityContext</interfacename> interface. This
  80. is the object that is kept in thread-local storage. As we'll see below, most
  81. authentication mechanisms withing Spring Security return an instance of
  82. <interfacename>UserDetails</interfacename> as the principal. </para>
  83. </section>
  84. </section>
  85. <section xml:id="tech-userdetailsservice">
  86. <title>The UserDetailsService</title>
  87. <para>Another item to note from the above code fragment is that you can obtain a
  88. principal from the <interfacename>Authentication</interfacename> object. The
  89. principal is just an <literal>Object</literal>. Most of the time this can be cast
  90. into a <interfacename>UserDetails</interfacename> object.
  91. <interfacename>UserDetails</interfacename> is a core interface in Spring
  92. Security. It represents a principal, but in an extensible and application-specific
  93. way. Think of <interfacename>UserDetails</interfacename> as the adapter between your
  94. own user database and what Spring Security needs inside the
  95. <classname>SecurityContextHolder</classname>. Being a representation of something
  96. from your own user database, quite often you will cast the
  97. <interfacename>UserDetails</interfacename> to the original object that your
  98. application provided, so you can call business-specific methods (like
  99. <literal>getEmail()</literal>, <literal>getEmployeeNumber()</literal> and so
  100. on).</para>
  101. <para>By now you're probably wondering, so when do I provide a
  102. <interfacename>UserDetails</interfacename> object? How do I do that? I thought you
  103. said this thing was declarative and I didn't need to write any Java code - what
  104. gives? The short answer is that there is a special interface called
  105. <interfacename>UserDetailsService</interfacename>. The only method on this interface
  106. accepts a <literal>String</literal>-based username argument and returns a
  107. <interfacename>UserDetails</interfacename>:
  108. <programlisting language="java">
  109. UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
  110. </programlisting>
  111. This is the most common approach to loading information for a user within Spring
  112. Security and you will see it used throughout the framework whenever information on a
  113. user is required.</para>
  114. <para> On successful authentication, <interfacename>UserDetails</interfacename> is used
  115. to build the <interfacename>Authentication</interfacename> object that is stored in
  116. the <classname>SecurityContextHolder</classname> (more on this <link
  117. linkend="tech-intro-authentication">below</link>). The good news is that we
  118. provide a number of <interfacename>UserDetailsService</interfacename>
  119. implementations, including one that uses an in-memory map
  120. (<classname>InMemoryDaoImpl</classname>) and another that uses JDBC
  121. (<classname>JdbcDaoImpl</classname>). Most users tend to write their own, though,
  122. with their implementations often simply sitting on top of an existing Data Access
  123. Object (DAO) that represents their employees, customers, or other users of the
  124. application. Remember the advantage that whatever your
  125. <interfacename>UserDetailsService</interfacename> returns can always be obtained
  126. from the <classname>SecurityContextHolder</classname> using the above code fragment.
  127. </para>
  128. <note>
  129. <para>There is often some confusion about <interfacename>UserDetailsService</interfacename>.
  130. It is purely a DAO for user data and performs no other function other than to supply that data
  131. to other components within the framework. In particular, it <emphasis>does not</emphasis>
  132. authenticate the user, which is done by the <interfacename>AuthenticationManager</interfacename>.
  133. In many cases it makes more sense to
  134. <link linkend="core-services-authentication-manager">implement <interfacename>AuthenticationProvider</interfacename></link>
  135. directly if you require a custom authentication process.
  136. </para>
  137. </note>
  138. </section>
  139. <section xml:id="tech-granted-authority">
  140. <title>GrantedAuthority</title>
  141. <para>Besides the principal, another important method provided by
  142. <interfacename>Authentication</interfacename> is
  143. <literal>getAuthorities(</literal>). This method provides an array of
  144. <interfacename>GrantedAuthority</interfacename> objects. A
  145. <interfacename>GrantedAuthority</interfacename> is, not surprisingly, an authority
  146. that is granted to the principal. Such authorities are usually <quote>roles</quote>,
  147. such as <literal>ROLE_ADMINISTRATOR</literal> or
  148. <literal>ROLE_HR_SUPERVISOR</literal>. These roles are later on configured for web
  149. authorization, method authorization and domain object authorization. Other parts of
  150. Spring Security are capable of interpreting these authorities, and expect them to be
  151. present. <interfacename>GrantedAuthority</interfacename> objects are usually loaded
  152. by the <interfacename>UserDetailsService</interfacename>.</para>
  153. <para>Usually the <interfacename>GrantedAuthority</interfacename> objects are
  154. application-wide permissions. They are not specific to a given domain object. Thus,
  155. you wouldn't likely have a <interfacename>GrantedAuthority</interfacename> to
  156. represent a permission to <literal>Employee</literal> object number 54, because if
  157. there are thousands of such authorities you would quickly run out of memory (or, at
  158. the very least, cause the application to take a long time to authenticate a user).
  159. Of course, Spring Security is expressly designed to handle this common requirement,
  160. but you'd instead use the project's domain object security capabilities for this
  161. purpose.</para>
  162. </section>
  163. <section>
  164. <title>Summary</title>
  165. <para>Just to recap, the major building blocks of Spring Security that we've seen so far
  166. are:</para>
  167. <itemizedlist spacing="compact">
  168. <listitem>
  169. <para><classname>SecurityContextHolder</classname>, to provide access to the
  170. <interfacename>SecurityContext</interfacename>.</para>
  171. </listitem>
  172. <listitem>
  173. <para><interfacename>SecurityContext</interfacename>, to hold the
  174. <interfacename>Authentication</interfacename> and possibly request-specific
  175. security information.</para>
  176. </listitem>
  177. <listitem>
  178. <para><interfacename>Authentication</interfacename>, to represent the principal
  179. in a Spring Security-specific manner.</para>
  180. </listitem>
  181. <listitem>
  182. <para><interfacename>GrantedAuthority</interfacename>, to reflect the
  183. application-wide permissions granted to a principal.</para>
  184. </listitem>
  185. <listitem>
  186. <para><interfacename>UserDetails</interfacename>, to provide the necessary
  187. information to build an Authentication object from your application's DAOs
  188. or other source of security data.</para>
  189. </listitem>
  190. <listitem>
  191. <para><interfacename>UserDetailsService</interfacename>, to create a
  192. <interfacename>UserDetails</interfacename> when passed in a
  193. <literal>String</literal>-based username (or certificate ID or the
  194. like).</para>
  195. </listitem>
  196. </itemizedlist>
  197. <para>Now that you've gained an understanding of these repeatedly-used components, let's
  198. take a closer look at the process of authentication.</para>
  199. </section>
  200. </section>
  201. <section xml:id="tech-intro-authentication">
  202. <info>
  203. <title>Authentication</title>
  204. </info>
  205. <para>Spring Security can participate in many different authentication environments. While
  206. we recommend people use Spring Security for authentication and not integrate with
  207. existing Container Managed Authentication, it is nevertheless supported - as is
  208. integrating with your own proprietary authentication system. </para>
  209. <section>
  210. <title>What is authentication in Spring Security?</title>
  211. <para> Let's consider a standard authentication scenario that everyone is familiar with. <orderedlist>
  212. <listitem>
  213. <para>A user is prompted to log in with a username and password.</para>
  214. </listitem>
  215. <listitem>
  216. <para>The system (successfully) verifies that the password is correct for the
  217. username.</para>
  218. </listitem>
  219. <listitem>
  220. <para>The context information for that user is obtained (their list of roles and
  221. so on).</para>
  222. </listitem>
  223. <listitem>
  224. <para>A security context is established for the user</para>
  225. </listitem>
  226. <listitem>
  227. <para>The user proceeds, potentially to perform some operation which is
  228. potentially protected by an access control mechanism which checks the
  229. required permissions for the operation against the current security context
  230. information. </para>
  231. </listitem>
  232. </orderedlist> The first three items constitute the authentication process so we'll
  233. take a look at how these take place within Spring Security.<orderedlist>
  234. <listitem>
  235. <para>The username and password are obtained and combined into an instance of
  236. <classname>UsernamePasswordAuthenticationToken</classname> (an instance of
  237. the <interfacename>Authentication</interfacename> interface, which we saw
  238. earlier).</para>
  239. </listitem>
  240. <listitem>
  241. <para>The token is passed to an instance of
  242. <interfacename>AuthenticationManager</interfacename> for validation.</para>
  243. </listitem>
  244. <listitem>
  245. <para>The <interfacename>AuthenticationManager</interfacename> returns a fully
  246. populated <interfacename>Authentication</interfacename> instance on
  247. successful authentication.</para>
  248. </listitem>
  249. <listitem>
  250. <para>The security context is established by calling
  251. <code>SecurityContextHolder.getContext().setAuthentication(...)</code>,
  252. passing in the returned authentication object.</para>
  253. </listitem>
  254. </orderedlist>From that point on, the user is considered to be authenticated. Let's
  255. look at some code as an example.
  256. <programlisting language="java">import org.springframework.security.authentication.*;
  257. import org.springframework.security.core.*;
  258. import org.springframework.security.core.authority.SimpleGrantedAuthority;
  259. import org.springframework.security.core.context.SecurityContextHolder;
  260. public class AuthenticationExample {
  261. private static AuthenticationManager am = new SampleAuthenticationManager();
  262. public static void main(String[] args) throws Exception {
  263. BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  264. while(true) {
  265. System.out.println("Please enter your username:");
  266. String name = in.readLine();
  267. System.out.println("Please enter your password:");
  268. String password = in.readLine();
  269. try {
  270. Authentication request = new UsernamePasswordAuthenticationToken(name, password);
  271. Authentication result = am.authenticate(request);
  272. SecurityContextHolder.getContext().setAuthentication(result);
  273. break;
  274. } catch(AuthenticationException e) {
  275. System.out.println("Authentication failed: " + e.getMessage());
  276. }
  277. }
  278. System.out.println("Successfully authenticated. Security context contains: " +
  279. SecurityContextHolder.getContext().getAuthentication());
  280. }
  281. }
  282. class SampleAuthenticationManager implements AuthenticationManager {
  283. static final List&lt;GrantedAuthority> AUTHORITIES = new ArrayList&lt;GrantedAuthority>();
  284. static {
  285. AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_USER"));
  286. }
  287. public Authentication authenticate(Authentication auth) throws AuthenticationException {
  288. if (auth.getName().equals(auth.getCredentials())) {
  289. return new UsernamePasswordAuthenticationToken(auth.getName(),
  290. auth.getCredentials(), AUTHORITIES);
  291. }
  292. throw new BadCredentialsException("Bad Credentials");
  293. }
  294. }</programlisting>Here
  295. we have written a little program that asks the user to enter a username and password
  296. and performs the above sequence. The
  297. <interfacename>AuthenticationManager</interfacename> which we've implemented here
  298. will authenticate any user whose username and password are the same. It assigns a
  299. single role to every user. The output from the above will be something
  300. like:<programlisting language="txt">
  301. Please enter your username:
  302. bob
  303. Please enter your password:
  304. password
  305. Authentication failed: Bad Credentials
  306. Please enter your username:
  307. bob
  308. Please enter your password:
  309. bob
  310. Successfully authenticated. Security context contains: \
  311. org.springframework.security.authentication.UsernamePasswordAuthenticationToken@441d0230: \
  312. Principal: bob; Password: [PROTECTED]; \
  313. Authenticated: true; Details: null; \
  314. Granted Authorities: ROLE_USER
  315. </programlisting></para>
  316. <para>Note that you don't normally need to write any code like this. The process will
  317. normally occur internally, in a web authentication filter for example. We've just
  318. included the code here to show that the question of what actually constitutes
  319. authentication in Spring Security has quite a simple answer. A user is authenticated
  320. when the <classname>SecurityContextHolder</classname> contains a fully populated
  321. <interfacename>Authentication</interfacename> object.</para>
  322. </section>
  323. <section>
  324. <title>Setting the SecurityContextHolder Contents Directly</title>
  325. <para>In fact, Spring Security doesn't mind how you put the
  326. <interfacename>Authentication</interfacename> object inside the
  327. <classname>SecurityContextHolder</classname>. The only critical requirement is that
  328. the <classname>SecurityContextHolder</classname> contains an
  329. <interfacename>Authentication</interfacename> which represents a principal before
  330. the <classname>AbstractSecurityInterceptor</classname> (which we'll see more about
  331. later) needs to authorize a user operation.</para>
  332. <para>You can (and many users do) write their own filters or MVC controllers to provide
  333. interoperability with authentication systems that are not based on Spring Security.
  334. For example, you might be using Container-Managed Authentication which makes the
  335. current user available from a ThreadLocal or JNDI location. Or you might work for a
  336. company that has a legacy proprietary authentication system, which is a corporate
  337. "standard" over which you have little control. In situations like this it's quite
  338. easy to get Spring Security to work, and still provide authorization capabilities.
  339. All you need to do is write a filter (or equivalent) that reads the third-party user
  340. information from a location, build a Spring Security-specific
  341. <interfacename>Authentication</interfacename> object, and put it into the
  342. <classname>SecurityContextHolder</classname>. In this case you also need to think
  343. about things which are normally taken care of automatically by the built-in authentication
  344. infrastructure. For example, you might need to pre-emptively create an HTTP session to
  345. <link xlink:href="tech-intro-sec-context-persistence">cache the context between requests</link>,
  346. before you write the response to the client<footnote><para>It isn't possible to create a session once the
  347. response has been committed.</para></footnote>.
  348. </para>
  349. <para> If you're wondering how the <interfacename>AuthenticationManager</interfacename>
  350. is implemented in a real world example, we'll look at that in the <link
  351. linkend="core-services-authentication-manager">core services
  352. chapter</link>.</para>
  353. </section>
  354. </section>
  355. <section xml:id="tech-intro-web-authentication">
  356. <title>Authentication in a Web Application</title>
  357. <para> Now let's explore the situation where you are using Spring Security in a web
  358. application (without <filename>web.xml</filename> security enabled). How is a user
  359. authenticated and the security context established?</para>
  360. <para>Consider a typical web application's authentication process:</para>
  361. <orderedlist inheritnum="ignore" continuation="restarts">
  362. <listitem>
  363. <para>You visit the home page, and click on a link.</para>
  364. </listitem>
  365. <listitem>
  366. <para>A request goes to the server, and the server decides that you've asked for a
  367. protected resource.</para>
  368. </listitem>
  369. <listitem>
  370. <para>As you're not presently authenticated, the server sends back a response
  371. indicating that you must authenticate. The response will either be an HTTP
  372. response code, or a redirect to a particular web page.</para>
  373. </listitem>
  374. <listitem>
  375. <para>Depending on the authentication mechanism, your browser will either redirect
  376. to the specific web page so that you can fill out the form, or the browser will
  377. somehow retrieve your identity (via a BASIC authentication dialogue box, a
  378. cookie, a X.509 certificate etc.).</para>
  379. </listitem>
  380. <listitem>
  381. <para>The browser will send back a response to the server. This will either be an
  382. HTTP POST containing the contents of the form that you filled out, or an HTTP
  383. header containing your authentication details.</para>
  384. </listitem>
  385. <listitem>
  386. <para>Next the server will decide whether or not the presented credentials are
  387. valid. If they're valid, the next step will happen. If they're invalid, usually
  388. your browser will be asked to try again (so you return to step two
  389. above).</para>
  390. </listitem>
  391. <listitem>
  392. <para>The original request that you made to cause the authentication process will be
  393. retried. Hopefully you've authenticated with sufficient granted authorities to
  394. access the protected resource. If you have sufficient access, the request will
  395. be successful. Otherwise, you'll receive back an HTTP error code 403, which
  396. means "forbidden".</para>
  397. </listitem>
  398. </orderedlist>
  399. <para>Spring Security has distinct classes responsible for most of the steps described
  400. above. The main participants (in the order that they are used) are the
  401. <classname>ExceptionTranslationFilter</classname>, an
  402. <interfacename>AuthenticationEntryPoint</interfacename> and an <quote>authentication
  403. mechanism</quote>, which is responsible for calling the
  404. <classname>AuthenticationManager</classname> which we saw in the previous
  405. section.</para>
  406. <section>
  407. <title>ExceptionTranslationFilter</title>
  408. <para><classname>ExceptionTranslationFilter</classname> is a Spring Security filter that
  409. has responsibility for detecting any Spring Security exceptions that are thrown.
  410. Such exceptions will generally be thrown by an
  411. <classname>AbstractSecurityInterceptor</classname>, which is the main provider of
  412. authorization services. We will discuss
  413. <classname>AbstractSecurityInterceptor</classname> in the next section, but for now
  414. we just need to know that it produces Java exceptions and knows nothing about HTTP
  415. or how to go about authenticating a principal. Instead the
  416. <classname>ExceptionTranslationFilter</classname> offers this service, with specific
  417. responsibility for either returning error code 403 (if the principal has been
  418. authenticated and therefore simply lacks sufficient access - as per step seven
  419. above), or launching an <interfacename>AuthenticationEntryPoint</interfacename> (if
  420. the principal has not been authenticated and therefore we need to go commence step
  421. three).</para>
  422. </section>
  423. <section xml:id="tech-intro-auth-entry-point">
  424. <title>AuthenticationEntryPoint</title>
  425. <para>The <interfacename>AuthenticationEntryPoint</interfacename> is responsible for
  426. step three in the above list. As you can imagine, each web application will have a
  427. default authentication strategy (well, this can be configured like nearly everything
  428. else in Spring Security, but let's keep it simple for now). Each major
  429. authentication system will have its own
  430. <interfacename>AuthenticationEntryPoint</interfacename> implementation, which
  431. typically performs one of the actions described in step 3.</para>
  432. </section>
  433. <section>
  434. <title>Authentication Mechanism</title>
  435. <para>Once your browser submits your authentication credentials (either as an HTTP form
  436. post or HTTP header) there needs to be something on the server that
  437. <quote>collects</quote> these authentication details. By now we're at step six in
  438. the above list. In Spring Security we have a special name for the function of
  439. collecting authentication details from a user agent (usually a web browser),
  440. referring to it as the <quote>authentication mechanism</quote>. Examples are
  441. form-base login and Basic authentication. Once the authentication details have been
  442. collected from the user agent, an <interfacename>Authentication</interfacename>
  443. <quote>request</quote> object is built and then presented to the
  444. <interfacename>AuthenticationManager</interfacename>.</para>
  445. <para>After the authentication mechanism receives back the fully-populated
  446. <interfacename>Authentication</interfacename> object, it will deem the request
  447. valid, put the <interfacename>Authentication</interfacename> into the
  448. <classname>SecurityContextHolder</classname>, and cause the original request to be
  449. retried (step seven above). If, on the other hand, the
  450. <classname>AuthenticationManager</classname> rejected the request, the
  451. authentication mechanism will ask the user agent to retry (step two above).</para>
  452. </section>
  453. <section xml:id="tech-intro-sec-context-persistence">
  454. <title>Storing the <interfacename>SecurityContext</interfacename> between
  455. requests</title>
  456. <para>Depending on the type of application, there may need to be a strategy in place to
  457. store the security context between user operations. In a typical web application, a
  458. user logs in once and is subsequently identified by their session Id. The server
  459. caches the principal information for the duration session. In Spring Security, the
  460. responsibility for storing the <interfacename>SecurityContext</interfacename>
  461. between requests falls to the
  462. <classname>SecurityContextPersistenceFilter</classname>, which by default stores the
  463. context as an <literal>HttpSession</literal> attribute between HTTP requests. It
  464. restores the context to the <classname>SecurityContextHolder</classname> for each
  465. request and, crucially, clears the <classname>SecurityContextHolder</classname> when
  466. the request completes. You shouldn't interact directly with the
  467. <literal>HttpSession</literal> for security purposes. There is simply no
  468. justification for doing so - always use the
  469. <classname>SecurityContextHolder</classname> instead. </para>
  470. <para> Many other types of application (for example, a stateless RESTful web service) do
  471. not use HTTP sessions and will re-authenticate on every request. However, it is
  472. still important that the <classname>SecurityContextPersistenceFilter</classname> is
  473. included in the chain to make sure that the
  474. <classname>SecurityContextHolder</classname> is cleared after each request.</para>
  475. <note>
  476. <para>In an application which receives concurrent requests in a single session, the
  477. same <interfacename>SecurityContext</interfacename> instance will be shared
  478. between threads. Even though a <classname>ThreadLocal</classname> is being used,
  479. it is the same instance that is retrieved from the
  480. <interfacename>HttpSession</interfacename> for each thread. This has
  481. implications if you wish to temporarily change the context under which a thread
  482. is running. If you just use <code>SecurityContextHolder.getContext()</code>, and
  483. call <code>setAuthentication(anAuthentication)</code> on the returned context
  484. object, then the <interfacename>Authentication</interfacename> object will
  485. change in <emphasis>all</emphasis> concurrent threads which share the same
  486. <interfacename>SecurityContext</interfacename> instance. You can customize the
  487. behaviour of <classname>SecurityContextPersistenceFilter</classname> to create a
  488. completely new <interfacename>SecurityContext</interfacename> for each request,
  489. preventing changes in one thread from affecting another. Alternatively you can
  490. create a new instance just at the point where you temporarily change the
  491. context. The method <code>SecurityContextHolder.createEmptyContext()</code>
  492. always returns a new context instance.</para>
  493. </note>
  494. </section>
  495. </section>
  496. <section xml:id="tech-intro-access-control">
  497. <title>Access-Control (Authorization) in Spring Security</title>
  498. <para> The main interface responsible for making access-control decisions in Spring Security
  499. is the <interfacename>AccessDecisionManager</interfacename>. It has a
  500. <methodname>decide</methodname> method which takes an
  501. <interfacename>Authentication</interfacename> object representing the principal
  502. requesting access, a <quote>secure object</quote> (see below) and a list of security
  503. metadata attributes which apply for the object (such as a list of roles which are
  504. required for access to be granted). </para>
  505. <section>
  506. <title>Security and AOP Advice</title>
  507. <para>If you're familiar with AOP, you'd be aware there are different types of advice
  508. available: before, after, throws and around. An around advice is very useful,
  509. because an advisor can elect whether or not to proceed with a method invocation,
  510. whether or not to modify the response, and whether or not to throw an exception.
  511. Spring Security provides an around advice for method invocations as well as web
  512. requests. We achieve an around advice for method invocations using Spring's standard
  513. AOP support and we achieve an around advice for web requests using a standard
  514. Filter.</para>
  515. <para>For those not familiar with AOP, the key point to understand is that Spring
  516. Security can help you protect method invocations as well as web requests. Most
  517. people are interested in securing method invocations on their services layer. This
  518. is because the services layer is where most business logic resides in
  519. current-generation J2EE applications. If you just need to secure method invocations
  520. in the services layer, Spring's standard AOP will be adequate. If you need to secure
  521. domain objects directly, you will likely find that AspectJ is worth
  522. considering.</para>
  523. <para>You can elect to perform method authorization using AspectJ or Spring AOP, or you
  524. can elect to perform web request authorization using filters. You can use zero, one,
  525. two or three of these approaches together. The mainstream usage pattern is to
  526. perform some web request authorization, coupled with some Spring AOP method
  527. invocation authorization on the services layer.</para>
  528. </section>
  529. <section xml:id="secure-objects">
  530. <title>Secure Objects and the <classname>AbstractSecurityInterceptor</classname></title>
  531. <para>So what <emphasis>is</emphasis> a <quote>secure object</quote> anyway? Spring
  532. Security uses the term to refer to any object that can have security (such as an
  533. authorization decision) applied to it. The most common examples are method
  534. invocations and web requests.</para>
  535. <para>Each supported secure object type has its own interceptor class, which is a
  536. subclass of <classname>AbstractSecurityInterceptor</classname>. Importantly, by the
  537. time the <classname>AbstractSecurityInterceptor</classname> is called, the
  538. <classname>SecurityContextHolder</classname> will contain a valid
  539. <interfacename>Authentication</interfacename> if the principal has been
  540. authenticated.</para>
  541. <para><classname>AbstractSecurityInterceptor</classname> provides a consistent workflow
  542. for handling secure object requests, typically: <orderedlist>
  543. <listitem>
  544. <para>Look up the <quote>configuration attributes</quote> associated with the
  545. present request</para>
  546. </listitem>
  547. <listitem>
  548. <para>Submitting the secure object, current
  549. <interfacename>Authentication</interfacename> and configuration attributes
  550. to the <interfacename>AccessDecisionManager</interfacename> for an
  551. authorization decision</para>
  552. </listitem>
  553. <listitem>
  554. <para>Optionally change the <interfacename>Authentication</interfacename> under
  555. which the invocation takes place</para>
  556. </listitem>
  557. <listitem>
  558. <para>Allow the secure object invocation to proceed (assuming access was
  559. granted)</para>
  560. </listitem>
  561. <listitem>
  562. <para>Call the <interfacename>AfterInvocationManager</interfacename> if
  563. configured, once the invocation has returned. If the invocation raised an
  564. exception, the <interfacename>AfterInvocationManager</interfacename>
  565. will not be invoked.</para>
  566. </listitem>
  567. </orderedlist></para>
  568. <section xml:id="tech-intro-config-attributes">
  569. <title>What are Configuration Attributes?</title>
  570. <para> A <quote>configuration attribute</quote> can be thought of as a String that
  571. has special meaning to the classes used by
  572. <classname>AbstractSecurityInterceptor</classname>. They are represented by the
  573. interface <interfacename>ConfigAttribute</interfacename> within the framework.
  574. They may be simple role names or have more complex meaning, depending on the how
  575. sophisticated the <interfacename>AccessDecisionManager</interfacename>
  576. implementation is. The <classname>AbstractSecurityInterceptor</classname> is
  577. configured with a <interfacename>SecurityMetadataSource</interfacename> which it
  578. uses to look up the attributes for a secure object. Usually this configuration
  579. will be hidden from the user. Configuration attributes will be entered as
  580. annotations on secured methods or as access attributes on secured URLs. For
  581. example, when we saw something like <literal>&lt;intercept-url
  582. pattern='/secure/**' access='ROLE_A,ROLE_B'/></literal> in the namespace
  583. introduction, this is saying that the configuration attributes
  584. <literal>ROLE_A</literal> and <literal>ROLE_B</literal> apply to web requests
  585. matching the given pattern. In practice, with the default
  586. <interfacename>AccessDecisionManager</interfacename> configuration, this means
  587. that anyone who has a <interfacename>GrantedAuthority</interfacename> matching
  588. either of these two attributes will be allowed access. Strictly speaking though,
  589. they are just attributes and the interpretation is dependent on the
  590. <interfacename>AccessDecisionManager</interfacename> implementation. The use of
  591. the prefix <literal>ROLE_</literal> is a marker to indicate that these
  592. attributes are roles and should be consumed by Spring Security's
  593. <classname>RoleVoter</classname>. This is only relevant when a voter-based
  594. <interfacename>AccessDecisionManager</interfacename> is in use. We'll see how
  595. the <interfacename>AccessDecisionManager</interfacename> is implemented in the
  596. <link linkend="authz-arch">authorization chapter</link>.</para>
  597. </section>
  598. <section>
  599. <title>RunAsManager</title>
  600. <para>Assuming <interfacename>AccessDecisionManager</interfacename> decides to allow
  601. the request, the <classname>AbstractSecurityInterceptor</classname> will
  602. normally just proceed with the request. Having said that, on rare occasions
  603. users may want to replace the <interfacename>Authentication</interfacename>
  604. inside the <interfacename>SecurityContext</interfacename> with a different
  605. <interfacename>Authentication</interfacename>, which is handled by the
  606. <interfacename>AccessDecisionManager</interfacename> calling a
  607. <literal>RunAsManager</literal>. This might be useful in reasonably unusual
  608. situations, such as if a services layer method needs to call a remote system and
  609. present a different identity. Because Spring Security automatically propagates
  610. security identity from one server to another (assuming you're using a
  611. properly-configured RMI or HttpInvoker remoting protocol client), this may be
  612. useful.</para>
  613. </section>
  614. <section>
  615. <title>AfterInvocationManager</title>
  616. <para>Following the secure object invocation proceeding and then returning - which may mean a
  617. method invocation completing or a filter chain proceeding - the
  618. <classname>AbstractSecurityInterceptor</classname> gets one final chance to
  619. handle the invocation. At this stage the
  620. <classname>AbstractSecurityInterceptor</classname> is interested in possibly
  621. modifying the return object. We might want this to happen because an
  622. authorization decision couldn't be made <quote>on the way in</quote> to a secure
  623. object invocation. Being highly pluggable,
  624. <classname>AbstractSecurityInterceptor</classname> will pass control to an
  625. <literal>AfterInvocationManager</literal> to actually modify the object if
  626. needed. This class can even entirely replace the object, or throw an exception,
  627. or not change it in any way as it chooses. The after-invocation checks will only
  628. be executed if the invocation is successful. If an exception occurs, the additional
  629. checks will be skipped.
  630. </para>
  631. <para><classname>AbstractSecurityInterceptor</classname> and its related objects are
  632. shown in <xref linkend="abstract-security-interceptor"/>. <figure
  633. xml:id="abstract-security-interceptor">
  634. <title>Security interceptors and the <quote>secure object</quote> model</title>
  635. <mediaobject>
  636. <imageobject>
  637. <imagedata align="center" fileref="images/security-interception.png"
  638. format="PNG" scale="75"/>
  639. </imageobject>
  640. </mediaobject>
  641. </figure></para>
  642. </section>
  643. <section>
  644. <title>Extending the Secure Object Model</title>
  645. <para>Only developers contemplating an entirely new way of intercepting and
  646. authorizing requests would need to use secure objects directly. For example, it
  647. would be possible to build a new secure object to secure calls to a messaging
  648. system. Anything that requires security and also provides a way of intercepting
  649. a call (like the AOP around advice semantics) is capable of being made into a
  650. secure object. Having said that, most Spring applications will simply use the
  651. three currently supported secure object types (AOP Alliance
  652. <classname>MethodInvocation</classname>, AspectJ
  653. <classname>JoinPoint</classname> and web request
  654. <classname>FilterInvocation</classname>) with complete transparency.</para>
  655. </section>
  656. </section>
  657. </section>
  658. <section xml:id="localization">
  659. <title>Localization</title>
  660. <para>Spring Security supports localization of exception messages that end users are likely
  661. to see. If your application is designed for English-speaking users, you don't need to do
  662. anything as by default all Security Security messages are in English. If you need to
  663. support other locales, everything you need to know is contained in this section.</para>
  664. <para>All exception messages can be localized, including messages related to authentication
  665. failures and access being denied (authorization failures). Exceptions and logging
  666. messages that are focused on developers or system deployers (including incorrect
  667. attributes, interface contract violations, using incorrect constructors, startup time
  668. validation, debug-level logging) are not localized and instead are hard-coded in English
  669. within Spring Security's code.</para>
  670. <para>Shipping in the <literal>spring-security-core-xx.jar</literal> you will find an
  671. <literal>org.springframework.security</literal> package that in turn contains a
  672. <literal>messages.properties</literal> file, as well as localized versions for some
  673. common languages. This should be referred to by your
  674. <literal>ApplicationContext</literal>, as Spring Security classes implement Spring's
  675. <literal>MessageSourceAware</literal> interface and expect the message resolver to be
  676. dependency injected at application context startup time. Usually all you need to do is
  677. register a bean inside your application context to refer to the messages. An example is
  678. shown below:</para>
  679. <para>
  680. <programlisting language="xml"><![CDATA[
  681. <bean id="messageSource"
  682. class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
  683. <property name="basename" value="classpath:org/springframework/security/messages"/>
  684. </bean>
  685. ]]></programlisting>
  686. </para>
  687. <para>The <literal>messages.properties</literal> is named in accordance with standard
  688. resource bundles and represents the default language supported by Spring Security
  689. messages. This default file is in English. </para>
  690. <para>If you wish to customize the <literal>messages.properties</literal> file, or support
  691. other languages, you should copy the file, rename it accordingly, and register it inside
  692. the above bean definition. There are not a large number of message keys inside this
  693. file, so localization should not be considered a major initiative. If you do perform
  694. localization of this file, please consider sharing your work with the community by
  695. logging a JIRA task and attaching your appropriately-named localized version of
  696. <literal>messages.properties</literal>.</para>
  697. <para>Spring Security relies on Spring's localization support in order to actually lookup
  698. the appropriate message. In order for this to work, you have to make sure that the
  699. locale from the incoming request is stored in Spring's
  700. <classname>org.springframework.context.i18n.LocaleContextHolder</classname>. Spring
  701. MVC's <classname>DispatcherServlet</classname> does this for your application
  702. automatically, but since Spring Security's filters are invoked before this, the
  703. <classname>LocaleContextHolder</classname> needs to be set up to contain the correct
  704. <literal>Locale</literal> before the filters are called. You can either do this in a
  705. filter yourself (which must come before the Spring Security filters in
  706. <filename>web.xml</filename>) or you can use Spring's
  707. <classname>RequestContextFilter</classname>. Please refer to the Spring Framework
  708. documentation for further details on using localization with Spring. </para>
  709. <para>The <quote>contacts</quote> sample application is set up to use localized messages.
  710. </para>
  711. </section>
  712. </chapter>