technical-overview.xml 48 KB

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