shiro-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From bdem...@apache.org
Subject [20/23] shiro-site git commit: more html to md
Date Mon, 24 Oct 2016 14:33:13 GMT
http://git-wip-us.apache.org/repos/asf/shiro-site/blob/f37b5848/realm.html.vtl
----------------------------------------------------------------------
diff --git a/realm.html.vtl b/realm.html.vtl
deleted file mode 100644
index 7d69af4..0000000
--- a/realm.html.vtl
+++ /dev/null
@@ -1,218 +0,0 @@
-<h1><a name="Realm-ApacheShiroRealms"></a>Apache Shiro Realms</h1>
-
-<div class="toc">
-<ul><li><a href="#Realm-RealmConfiguration">Realm Configuration</a></li><ul><li><a href="#Realm-ExplicitAssignment">Explicit Assignment</a></li><li><a href="#Realm-ImplicitAssignment">Implicit Assignment</a></li></ul><li><a href="#Realm-RealmAuthentication">Realm Authentication</a></li><ul><li><a href="#Realm-Supporting%7B%7BAuthenticationTokens%7D%7D">Supporting <tt>AuthenticationTokens</tt></a></li><li><a href="#Realm-Handlingsupported%7B%7BAuthenticationTokens%7D%7D">Handling supported <tt>AuthenticationTokens</tt></a></li><li><a href="#Realm-CredentialsMatching">Credentials Matching</a></li><ul><li><a href="#Realm-SimpleEqualityCheck">Simple Equality Check</a></li><li><a href="#Realm-HashingCredentials">Hashing Credentials</a></li><ul><li><a href="#Realm-HashingandCorrespondingMatchers">Hashing and Corresponding Matchers</a></li><ul><li><a href="#Realm-%7B%7BSaltedAuthenticationInfo%7D%7D"> <tt>SaltedAuthenticationInfo</tt></a></li></ul></ul></ul><li><a href="#Realm-DisablingAut
 hentication">Disabling Authentication</a></li></ul><li><a href="#Realm-RealmAuthorization">Realm Authorization</a></li><li><a href="#Realm-Lendahandwithdocumentation">Lend a hand with documentation</a></li></ul></div>
-
-<p>A <tt>Realm</tt> is a component that can access application-specific security data such as users, roles, and permissions.  The <tt>Realm</tt> translates this application-specific data into a format that Shiro understands so Shiro can in turn provide a single easy-to-understand <a href="subject.html" title="Subject">Subject</a> programming API no matter how many data sources exist or how application-specific your data might be.</p>
-
-<p>Realms usually have a 1-to-1 correlation with a data source such as a relational database, LDAP directory, file system, or other similar resource.  As such, implementations of the <tt>Realm</tt> interface use data source-specific APIs to discover authorization data (roles, permissions, etc), such as JDBC, File IO, Hibernate or JPA, or any other Data Access API.  </p>
-
-#tip('Tip', 'A Realm is essentially a security-specific <a class="external-link" href="https://en.wikipedia.org/wiki/Data_Access_Object" rel="nofollow">DAO</a>')
-
-<p>Because most of these data sources usually store both authentication data (credentials such as passwords) as well as authorization data (such as roles or permissions), every Shiro <tt>Realm</tt> can perform <em>both</em> authentication and authorization operations.</p>
-
-<h2><a name="Realm-RealmConfiguration"></a>Realm Configuration</h2>
-
-<p>If using Shiro's INI configuration, you define and reference <tt>Realms</tt> like any other object in the <tt>[main]</tt> section, but they are configured on the <tt>securityManager</tt> in one of two ways: explicitly or implicitly.</p>
-
-<h3><a name="Realm-ExplicitAssignment"></a>Explicit Assignment</h3>
-
-<p>Based on knowledge of INI configuration thus far, this is an obvious configuration approach.  After defining one or more Realms, you set them as a collection property on the <tt>securityManager</tt> object.</p>
-
-<p>For example:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-fooRealm = com.company.foo.Realm
-barRealm = com.company.another.Realm
-bazRealm = com.company.baz.Realm
-
-securityManager.realms = $fooRealm, $barRealm, $bazRealm
-</pre>
-</div></div>
-
-<p>Explicit assignment is deterministic - you control exactly which realms are used as well as <em>the order</em> that they will be used for authentication and authorization. Realm ordering effects are described in detail in the Authentication chapter's <a href="authentication.html#[[#]]#Authentication-sequence">Authentication Sequence</a> section. </p>
-
-<h3><a name="Realm-ImplicitAssignment"></a>Implicit Assignment</h3>
-
-#danger('Not Preferred', 'Implicit assignment can cause unexpected behavior if you change the order in which realms are defined.  It is recommended that you avoid this approach and use Explicit Assignment, which has deterministic behavior.  It is likely Implicit Assignment will be deprecated/removed from a future Shiro release.')
-
-<p>If for some reason you don't want to explicitly configure the <tt>securityManager.realms</tt> property, you can allow Shiro to detect all configured realms and assign them to the <tt>securityManager</tt> directly.</p>
-
-<p>Using this approach, realms are assigned to the <tt>securityManager</tt> instance in the <em>order that they are defined</em>.</p>
-
-<p>That is, for the following <tt>shiro.ini</tt> example:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-blahRealm = com.company.blah.Realm
-fooRealm = com.company.foo.Realm
-barRealm = com.company.another.Realm
-
-# no securityManager.realms assignment here
-</pre>
-</div></div>
-
-<p>basically has the same effect as if the following line were appended:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-securityManager.realms = $blahRealm, $fooRealm, $barRealm
-</pre>
-</div></div>
-
-<p>However, realize that with implicit assignment, just the order that the realms are defined directly affects how they are consulted during authentication and authorization attempts.  If you change their definition order, you will change how the master <tt>Authenticator</tt>'s <a href="authentication.html#[[#]]#Authentication-sequence">Authentication Sequence</a> functions.</p>
-
-<p>For this reason, and to ensure deterministic behavior, we recommend using Explicit Assignment instead of Implicit Assignment. <br clear="none">
-<a name="Realm-authentication"></a></p>
-<h2><a name="Realm-RealmAuthentication"></a>Realm Authentication</h2>
-
-<p>Once you understand Shiro's master <a href="authentication.html#[[#]]#Authentication-sequence">Authentication workflow</a>, it is important to know exactly what happens when the <tt>Authenticator</tt> interacts with a <tt>Realm</tt> during an authentication attempt.</p>
-
-<h3><a name="Realm-Supporting%7B%7BAuthenticationTokens%7D%7D"></a>Supporting <tt>AuthenticationTokens</tt></h3>
-
-<p>As mentioned in the <a href="authentication.html#[[#]]#Authentication-sequence">authentication sequence</a>, just before a <tt>Realm</tt> is consulted to perform an authentication attempt, its <tt><a class="external-link" href="static/current/apidocs/org/apache/shiro/realm/Realm.html#[[#]]#supports(org.apache.shiro.authc.AuthenticationToken)">supports</a></tt> method is called.  If the return value is <tt>true</tt>, only then will its <tt>getAuthenticationInfo(token)</tt> method be invoked.</p>
-
-<p>Typically a realm will check the type (interface or class) of the submitted token to see if it can process it.  For example, a Realm that processes biometric data may not understand <tt>UsernamePasswordTokens</tt> at all, in which case it would return <tt>false</tt> from the <tt>supports</tt> method.</p>
-
-<h3><a name="Realm-Handlingsupported%7B%7BAuthenticationTokens%7D%7D"></a>Handling supported <tt>AuthenticationTokens</tt></h3>
-
-<p>If a <tt>Realm</tt> <tt>supports</tt> a submitted <tt>AuthenticationToken</tt>, the <tt>Authenticator</tt> will call the Realm's  <a class="external-link" href="static/current/apidocs/org/apache/shiro/realm/Realm.html#[[#]]#getAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)">getAuthenticationInfo(token)</a> method.  This effectively represents an authentication attempt with the <tt>Realm's</tt> backing data source.  The method, in order:</p>
-
-<ol><li>Inspects the <tt>token</tt> for the identifying principal (account identifying information)</li><li>Based on the <tt>principal</tt>, looks up corresponding account data in the data source</li><li>Ensures that the token's supplied <tt>credentials</tt> matches those stored in the data store</li><li>If the credentials match, an <a class="external-link" href="static/current/apidocs/org/apache/shiro/authc/AuthenticationInfo.html">AuthenticationInfo</a> instance is returned that encapsulates the account data in a format Shiro understands</li><li>If the credentials DO NOT match, an <a class="external-link" href="static/current/apidocs/org/apache/shiro/authc/AuthenticationException.html">AuthenticationException</a> is thrown</li></ol>
-
-
-<p>This is the highest-level workflow for all Realm <tt>getAuthenticationInfo</tt> implementations.  Realms are free to do whatever they want during this method, such as record the attempt in an audit log, update data records, or anything else that makes sense for the authentication attempt for that data store.</p>
-
-<p>The only thing required is that, if the credentials match for the given principal(s), that a non-null <tt>AuthenticationInfo</tt> instance is returned that represents Subject account information from that data source.</p>
-
-#info('Save Time', 'Implementing <tt><a class="external-link" href="static/current/apidocs/org/apache/shiro/realm/Realm.html">Realm</a></tt> interface directly might be time consuming and error prone.  Most people choose to subclass the <a class="external-link" href="static/current/apidocs/org/apache/shiro/realm/AuthorizingRealm.html">AuthorizingRealm</a> abstract class instead of starting from scratch.  This class implements common authentication and authorization workflow to save you time and effort.')
-
-<h3><a name="Realm-CredentialsMatching"></a>Credentials Matching</h3>
-
-<p>In the above realm authentication workflow, a Realm has to verify that the <a href="subject.html" title="Subject">Subject</a>'s submitted credentials (e.g. password) must match the credentials stored in the data store.  If they match, authentication is considered successful, and the system has verified the end-user's identity.</p>
-
-#warning('Realm Credentials Matching', 'It is each Realm''s responsibility to match submitted credentials with those stored in the Realm''s backing data store, and not the <tt>Authenticator''s</tt> responsibility.  Each <tt>Realm</tt> has intimate knowledge of credentials format and storage and can perform detailed credentials matching, whereas the <tt>Authenticator</tt> is a generic workflow component.')
-
-<p>The credentials matching process is nearly identical in all applications and usually only differs by the data compared.  To ensure this process is pluggable and customizable if necessary, the <a class="external-link" href="static/current/apidocs/org/apache/shiro/realm/AuthenticatingRealm.html">AuthenticatingRealm</a> and its subclasses support the concept of a <a class="external-link" href="static/current/apidocs/org/apache/shiro/authc/credential/CredentialsMatcher.html">CredentialsMatcher</a> to perform the credentials comparison.</p>
-
-<p>After discovering account data, it and the submitted <tt>AuthenticationToken</tt> are presented to a <tt>CredentialsMatcher</tt> to see if what was submitted matches what is stored in the data store. </p>
-
-<p>Shiro has some <tt>CredentialsMatcher</tt> implementations to get you started out of the box, such as the <a class="external-link" href="static/current/apidocs/org/apache/shiro/authc/credential/SimpleCredentialsMatcher.html">SimpleCredentialsMatcher</a> and <a class="external-link" href="static/current/apidocs/org/apache/shiro/authc/credential/HashedCredentialsMatcher.html">HashedCredentialsMatcher</a> implementations, but if you wanted to configure a custom implementation for custom matching logic, you could do so directly:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-Realm myRealm = <span class="code-keyword">new</span> com.company.shiro.realm.MyRealm();
-CredentialsMatcher customMatcher = <span class="code-keyword">new</span> com.company.shiro.realm.CustomCredentialsMatcher();
-myRealm.setCredentialsMatcher(customMatcher);
-</pre>
-</div></div>
-
-<p>Or, if using Shiro's INI <a href="configuration.html" title="Configuration">configuration</a>:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-[main]
-...
-customMatcher = com.company.shiro.realm.CustomCredentialsMatcher
-myRealm = com.company.shiro.realm.MyRealm
-myRealm.credentialsMatcher = $customMatcher
-...
-</pre>
-</div></div>
-
-
-<h4><a name="Realm-SimpleEqualityCheck"></a>Simple Equality Check</h4>
-
-<p>All of Shiro's out-of-the-box <tt>Realm</tt> implementations default to using a <a class="external-link" href="static/current/apidocs/org/apache/shiro/authc/credential/SimpleCredentialsMatcher.html">SimpleCredentialsMatcher</a>.  The <tt>SimpleCredentialsMatcher</tt> performs a plain direct equality check of the stored account credentials with what was submitted in the <tt>AuthenticationToken</tt>.</p>
-
-<p>For example, if a <a class="external-link" href="static/current/apidocs/org/apache/shiro/authc/UsernamePasswordToken.html">UsernamePasswordToken</a> was submitted, the <tt>SimpleCredentialsMatcher</tt> verifies that the password submitted is exactly equal to the password stored in the database.</p>
-
-<p>The <tt>SimpleCredentialsMatcher</tt> performs direct equality comparisons for more than just Strings though.  It can work with most common byte sources, such as Strings, character arrays, byte arrays, Files and InputStreams.  See its JavaDoc for more.</p>
-
-<h4><a name="Realm-HashingCredentials"></a>Hashing Credentials</h4>
-
-<p>Instead of storing credentials in their raw form and performing raw/plain comparisons, a much more secure way of storing end-user's credentials (e.g. passwords) is to one-way hash them first before storing them in the data store.  </p>
-
-<p>This ensures that end-users' credentials are never stored in their raw form and that no one can know the original/raw value.  This is a much more secure mechanism than plain-text or raw comparisons, and all security-conscious applications should favor this approach over non-hashed storage.</p>
-
-<p>To support these preferred cryptographic hashing strategies, Shiro provides <a class="external-link" href="static/current/apidocs/org/apache/shiro/authc/credential/HashedCredentialsMatcher.html">HashedCredentialsMatcher</a> implementations to be configured on realms instead of the aforementioned <tt>SimpleCredentialsMatcher</tt>.</p>
-
-<p>Hashing credentials and the benefits of salting and multiple hash iterations are outside the scope of this <tt>Realm</tt> documentation, but definitely read the <a class="external-link" href="static/current/apidocs/org/apache/shiro/authc/credential/HashedCredentialsMatcher.html">HashedCredentialsMatcher JavaDoc</a> which covers these principles in detail.</p>
-
-<h5><a name="Realm-HashingandCorrespondingMatchers"></a>Hashing and Corresponding Matchers</h5>
-
-<p>So how do you configure a Shiro-enabled application to do this easily?</p>
-
-<p>Shiro provides multiple <tt>HashedCredentialsMatcher</tt> subclass implementations.  You must configure the specific implementation on your realm to match the hashing algorithm you use to hash your users' credentials.</p>
-
-<p>For example, let's say your application uses username/password pairs for authentication.  And due to the benefits of hashing credentials described above, let's say you want to one-way hash a user's password using the <a class="external-link" href="https://en.wikipedia.org/wiki/SHA_hash_functions" rel="nofollow">SHA-256</a> algorithm when you create a user account.  You would hash the user's entered plain-text password and save that value:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-<span class="code-keyword">import</span> org.apache.shiro.crypto.hash.Sha256Hash;
-<span class="code-keyword">import</span> org.apache.shiro.crypto.RandomNumberGenerator;
-<span class="code-keyword">import</span> org.apache.shiro.crypto.SecureRandomNumberGenerator;
-...
-
-<span class="code-comment">//We'll use a Random <span class="code-object">Number</span> Generator to generate salts.  This
-</span><span class="code-comment">//is much more secure than using a username as a salt or not
-</span><span class="code-comment">//having a salt at all.  Shiro makes <span class="code-keyword">this</span> easy.
-</span><span class="code-comment">//
-</span><span class="code-comment">//Note that a normal app would reference an attribute rather
-</span><span class="code-comment">//than create a <span class="code-keyword">new</span> RNG every time:
-</span>RandomNumberGenerator rng = <span class="code-keyword">new</span> SecureRandomNumberGenerator();
-<span class="code-object">Object</span> salt = rng.nextBytes();
-
-<span class="code-comment">//Now hash the plain-text password with the random salt and multiple
-</span><span class="code-comment">//iterations and then Base64-encode the value (requires less space than Hex):
-</span><span class="code-object">String</span> hashedPasswordBase64 = <span class="code-keyword">new</span> Sha256Hash(plainTextPassword, salt, 1024).toBase64();
-
-User user = <span class="code-keyword">new</span> User(username, hashedPasswordBase64);
-<span class="code-comment">//save the salt with the <span class="code-keyword">new</span> account.  The HashedCredentialsMatcher
-</span><span class="code-comment">//will need it later when handling login attempts:
-</span>user.setPasswordSalt(salt);
-userDAO.create(user);
-</pre>
-</div></div>
-
-<p>Since you're <tt>SHA-256</tt> hashing your user's passwords, you need to tell Shiro to use the appropriate <tt>HashedCredentialsMatcher</tt> to match your hashing preferences.  In this example, we create a random salt and perform 1024 hash iterations for strong security (see the <tt>HashedCredentialsMatcher</tt> JavaDoc for why).  Here is the Shiro INI configuration to make this work:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-[main]
-...
-credentialsMatcher = org.apache.shiro.authc.credential.Sha256CredentialsMatcher
-# base64 encoding, not hex in <span class="code-keyword">this</span> example:
-credentialsMatcher.storedCredentialsHexEncoded = <span class="code-keyword">false</span>
-credentialsMatcher.hashIterations = 1024
-# This next property is only needed in Shiro 1.0.  Remove it in 1.1 and later:
-credentialsMatcher.hashSalted = <span class="code-keyword">true</span>
-
-...
-myRealm = com.company.....
-myRealm.credentialsMatcher = $credentialsMatcher
-...
-</pre>
-</div></div>
-
-<h6><a name="Realm-%7B%7BSaltedAuthenticationInfo%7D%7D"></a><tt>SaltedAuthenticationInfo</tt></h6>
-
-<p>The last thing to do to ensure this works is that your <tt>Realm</tt> implementation must return a <a class="external-link" href="static/current/apidocs/org/apache/shiro/authc/SaltedAuthenticationInfo.html">SaltedAuthenticationInfo</a> instance instead of a normal <tt>AuthenticationInfo</tt> one.  The <tt>SaltedAuthenticationInfo</tt> interface ensures that the salt that you used when you created the user account (e.g. the <tt>user.setPasswordSalt(salt);</tt> call above) can be referenced by the <tt>HashedCredentialsMatcher</tt>.</p>
-
-<p>The <tt>HashedCredentialsMatcher</tt> needs the salt in order to perform the same hashing technique on the submitted <tt>AuthenticationToken</tt> to see if the token matches what you saved in the data store.  So if you use salting for user passwords (and you should!!!), ensure your <tt>Realm</tt> implementation represents that by returning <tt>SaltedAuthenticationInfo</tt> instances.</p>
-
-<h3><a name="Realm-DisablingAuthentication"></a>Disabling Authentication</h3>
-
-<p>If for some reason, you don't want a Realm to perform authentication for a data source (maybe because you only want the Realm to perform authorization), you can disable a Realm's support for authentication entirely by always returning <tt>false</tt> from the Realm's <tt>supports</tt> method.  Then your realm will never be consulted during an authentication attempt.  </p>
-
-<p>Of course at least one configured <tt>Realm</tt> needs to be able to support AuthenticationTokens if you want to authenticate Subjects. </p>
-
-<h2><a name="Realm-RealmAuthorization"></a>Realm Authorization</h2>
-<p>TBD</p>
-
-<h2><a name="Realm-Lendahandwithdocumentation"></a>Lend a hand with documentation </h2>
-
-<p>While we hope this documentation helps you with the work you're doing with Apache Shiro, the community is improving and expanding the documentation all the time.  If you'd like to help the Shiro project, please consider corrected, expanding, or adding documentation where you see a need. Every little bit of help you provide expands the community and in turn improves Shiro. </p>
-
-<p>The easiest way to contribute your documentation is to send it to the <a class="external-link" href="http://shiro-user.582556.n2.nabble.com/" rel="nofollow">User Forum</a> or the <a href="mailing-lists.html" title="Mailing Lists">User Mailing List</a>.</p>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/shiro-site/blob/f37b5848/realm.md.vtl
----------------------------------------------------------------------
diff --git a/realm.md.vtl b/realm.md.vtl
new file mode 100644
index 0000000..5714b66
--- /dev/null
+++ b/realm.md.vtl
@@ -0,0 +1,246 @@
+# <a name="Realm-ApacheShiroRealms"></a>Apache Shiro Realms
+
+*   [Realm Configuration](#Realm-RealmConfiguration)
+
+    *   [Explicit Assignment](#Realm-ExplicitAssignment)
+    *   [Implicit Assignment](#Realm-ImplicitAssignment)
+
+*   [Realm Authentication](#Realm-RealmAuthentication)
+
+    *   [Supporting `AuthenticationTokens`](#Realm-Supporting%7B%7BAuthenticationTokens%7D%7D)
+    *   [Handling supported `AuthenticationTokens`](#Realm-Handlingsupported%7B%7BAuthenticationTokens%7D%7D)
+    *   [Credentials Matching](#Realm-CredentialsMatching)
+
+        *   [Simple Equality Check](#Realm-SimpleEqualityCheck)
+        *   [Hashing Credentials](#Realm-HashingCredentials)
+
+            *   [Hashing and Corresponding Matchers](#Realm-HashingandCorrespondingMatchers)
+
+                *   [`SaltedAuthenticationInfo`](#Realm-%7B%7BSaltedAuthenticationInfo%7D%7D)
+
+    *   [Disabling Authentication](#Realm-DisablingAuthentication)
+
+*   [Realm Authorization](#Realm-RealmAuthorization)
+*   [Lend a hand with documentation](#Realm-Lendahandwithdocumentation)
+
+A `Realm` is a component that can access application-specific security data such as users, roles, and permissions. The `Realm` translates this application-specific data into a format that Shiro understands so Shiro can in turn provide a single easy-to-understand [Subject](subject.html "Subject") programming API no matter how many data sources exist or how application-specific your data might be.
+
+Realms usually have a 1-to-1 correlation with a data source such as a relational database, LDAP directory, file system, or other similar resource. As such, implementations of the `Realm` interface use data source-specific APIs to discover authorization data (roles, permissions, etc), such as JDBC, File IO, Hibernate or JPA, or any other Data Access API.
+
+#tip('Tip', 'A Realm is essentially a security-specific <a class="external-link" href="http://en.wikipedia.org/wiki/Data_Access_Object" rel="nofollow">DAO</a>')
+
+Because most of these data sources usually store both authentication data (credentials such as passwords) as well as authorization data (such as roles or permissions), every Shiro `Realm` can perform _both_ authentication and authorization operations.
+
+<a name="Realm-RealmConfiguration"></a>
+Realm Configuration
+-------------------
+
+If using Shiro's INI configuration, you define and reference `Realms` like any other object in the `[main]` section, but they are configured on the `securityManager` in one of two ways: explicitly or implicitly.
+
+<a name="Realm-ExplicitAssignment"></a>
+#[[###Explicit Assignment]]#
+
+Based on knowledge of INI configuration thus far, this is an obvious configuration approach. After defining one or more Realms, you set them as a collection property on the `securityManager` object.
+
+For example:
+
+``` ini
+fooRealm = com.company.foo.Realm
+barRealm = com.company.another.Realm
+bazRealm = com.company.baz.Realm
+
+securityManager.realms = $fooRealm, $barRealm, $bazRealm
+```
+
+Explicit assignment is deterministic - you control exactly which realms are used as well as _the order_ that they will be used for authentication and authorization. Realm ordering effects are described in detail in the Authentication chapter's [Authentication Sequence](authentication.html#[[#]]#Authentication-sequence) section.
+
+<a name="Realm-ImplicitAssignment"></a>
+#[[###Implicit Assignment]]#
+
+#danger('Not Preferred', 'Implicit assignment can cause unexpected behavior if you change the order in which realms are defined.  It is recommended that you avoid this approach and use Explicit Assignment, which has deterministic behavior.  It is likely Implicit Assignment will be deprecated/removed from a future Shiro release.')
+
+If for some reason you don't want to explicitly configure the `securityManager.realms` property, you can allow Shiro to detect all configured realms and assign them to the `securityManager` directly.
+
+Using this approach, realms are assigned to the `securityManager` instance in the _order that they are defined_.
+
+That is, for the following `shiro.ini` example:
+
+``` ini
+blahRealm = com.company.blah.Realm
+fooRealm = com.company.foo.Realm
+barRealm = com.company.another.Realm
+
+# no securityManager.realms assignment here
+```
+
+basically has the same effect as if the following line were appended:
+
+``` java
+securityManager.realms = $blahRealm, $fooRealm, $barRealm
+```
+
+However, realize that with implicit assignment, just the order that the realms are defined directly affects how they are consulted during authentication and authorization attempts. If you change their definition order, you will change how the master `Authenticator`'s [Authentication Sequence](authentication.html#[[#]]#Authentication-sequence) functions.
+
+For this reason, and to ensure deterministic behavior, we recommend using Explicit Assignment instead of Implicit Assignment.
+
+<a name="Realm-authentication"></a>
+<a name="Realm-RealmAuthentication"></a>
+Realm Authentication
+--------------------
+
+Once you understand Shiro's master [Authentication workflow](authentication.html#[[#]]#Authentication-sequence), it is important to know exactly what happens when the `Authenticator` interacts with a `Realm` during an authentication attempt.
+
+<a name="Realm-Supporting%7B%7BAuthenticationTokens%7D%7D"></a>
+#[[###Supporting `AuthenticationTokens`]]#
+
+As mentioned in the [authentication sequence](authentication.html#[[#]]#Authentication-sequence), just before a `Realm` is consulted to perform an authentication attempt, its [`supports`](static/current/apidocs/org/apache/shiro/realm/Realm.html#[[#]]#supports-org.apache.shiro.authc.AuthenticationToken-) method is called. If the return value is `true`, only then will its `getAuthenticationInfo(token)` method be invoked.
+
+Typically a realm will check the type (interface or class) of the submitted token to see if it can process it. For example, a Realm that processes biometric data may not understand `UsernamePasswordTokens` at all, in which case it would return `false` from the `supports` method.
+
+<a name="Realm-Handlingsupported%7B%7BAuthenticationTokens%7D%7D"></a>
+#[[###Handling supported `AuthenticationTokens`]]#
+
+If a `Realm` `supports` a submitted `AuthenticationToken`, the `Authenticator` will call the Realm's [getAuthenticationInfo(token)](static/current/apidocs/org/apache/shiro/realm/Realm.html#[[#]]#getAuthenticationInfo-org.apache.shiro.authc.AuthenticationToken-) method. This effectively represents an authentication attempt with the `Realm's` backing data source. The method, in order:
+
+1.  Inspects the `token` for the identifying principal (account identifying information)
+2.  Based on the `principal`, looks up corresponding account data in the data source
+3.  Ensures that the token's supplied `credentials` matches those stored in the data store
+4.  If the credentials match, an [AuthenticationInfo](static/current/apidocs/org/apache/shiro/authc/AuthenticationInfo.html) instance is returned that encapsulates the account data in a format Shiro understands
+5.  If the credentials DO NOT match, an [AuthenticationException](static/current/apidocs/org/apache/shiro/authc/AuthenticationException.html) is thrown
+
+This is the highest-level workflow for all Realm `getAuthenticationInfo` implementations. Realms are free to do whatever they want during this method, such as record the attempt in an audit log, update data records, or anything else that makes sense for the authentication attempt for that data store.
+
+The only thing required is that, if the credentials match for the given principal(s), that a non-null `AuthenticationInfo` instance is returned that represents Subject account information from that data source.
+
+#info('Save Time', 'Implementing `<a class="external-link" href="static/current/apidocs/org/apache/shiro/realm/Realm.html">Realm</a>` interface directly might be time consuming and error prone.  Most people choose to subclass the <a class="external-link" href="static/current/apidocs/org/apache/shiro/realm/AuthorizingRealm.html">AuthorizingRealm</a> abstract class instead of starting from scratch.  This class implements common authentication and authorization workflow to save you time and effort.')
+
+<a name="Realm-CredentialsMatching"></a>
+#[[###Credentials Matching]]#
+
+In the above realm authentication workflow, a Realm has to verify that the [Subject](subject.html "Subject")'s submitted credentials (e.g. password) must match the credentials stored in the data store. If they match, authentication is considered successful, and the system has verified the end-user's identity.
+
+#warning('Realm Credentials Matching', 'It is each Realm''s responsibility to match submitted credentials with those stored in the Realm''s backing data store, and not the `Authenticator''s` responsibility.  Each `Realm` has intimate knowledge of credentials format and storage and can perform detailed credentials matching, whereas the `Authenticator` is a generic workflow component.')
+
+The credentials matching process is nearly identical in all applications and usually only differs by the data compared. To ensure this process is pluggable and customizable if necessary, the [AuthenticatingRealm](static/current/apidocs/org/apache/shiro/realm/AuthenticatingRealm.html) and its subclasses support the concept of a [CredentialsMatcher](static/current/apidocs/org/apache/shiro/authc/credential/CredentialsMatcher.html) to perform the credentials comparison.
+
+After discovering account data, it and the submitted `AuthenticationToken` are presented to a `CredentialsMatcher` to see if what was submitted matches what is stored in the data store.
+
+Shiro has some `CredentialsMatcher` implementations to get you started out of the box, such as the [SimpleCredentialsMatcher](static/current/apidocs/org/apache/shiro/authc/credential/SimpleCredentialsMatcher.html) and [HashedCredentialsMatcher](static/current/apidocs/org/apache/shiro/authc/credential/HashedCredentialsMatcher.html) implementations, but if you wanted to configure a custom implementation for custom matching logic, you could do so directly:
+
+``` java
+Realm myRealm = new com.company.shiro.realm.MyRealm();
+CredentialsMatcher customMatcher = new com.company.shiro.realm.CustomCredentialsMatcher();
+myRealm.setCredentialsMatcher(customMatcher);
+```
+
+Or, if using Shiro's INI [configuration](configuration.html "Configuration"):
+
+``` ini
+[main]
+...
+customMatcher = com.company.shiro.realm.CustomCredentialsMatcher
+myRealm = com.company.shiro.realm.MyRealm
+myRealm.credentialsMatcher = $customMatcher
+...
+```
+
+<a name="Realm-SimpleEqualityCheck"></a>
+#[[####Simple Equality Check]]#
+
+All of Shiro's out-of-the-box `Realm` implementations default to using a [SimpleCredentialsMatcher](static/current/apidocs/org/apache/shiro/authc/credential/SimpleCredentialsMatcher.html). The `SimpleCredentialsMatcher` performs a plain direct equality check of the stored account credentials with what was submitted in the `AuthenticationToken`.
+
+For example, if a [UsernamePasswordToken](static/current/apidocs/org/apache/shiro/authc/UsernamePasswordToken.html) was submitted, the `SimpleCredentialsMatcher` verifies that the password submitted is exactly equal to the password stored in the database.
+
+The `SimpleCredentialsMatcher` performs direct equality comparisons for more than just Strings though. It can work with most common byte sources, such as Strings, character arrays, byte arrays, Files and InputStreams. See its JavaDoc for more.
+
+<a name="Realm-HashingCredentials"></a>
+#[[####Hashing Credentials]]#
+
+Instead of storing credentials in their raw form and performing raw/plain comparisons, a much more secure way of storing end-user's credentials (e.g. passwords) is to one-way hash them first before storing them in the data store.
+
+This ensures that end-users' credentials are never stored in their raw form and that no one can know the original/raw value. This is a much more secure mechanism than plain-text or raw comparisons, and all security-conscious applications should favor this approach over non-hashed storage.
+
+To support these preferred cryptographic hashing strategies, Shiro provides [HashedCredentialsMatcher](static/current/apidocs/org/apache/shiro/authc/credential/HashedCredentialsMatcher.html) implementations to be configured on realms instead of the aforementioned `SimpleCredentialsMatcher`.
+
+Hashing credentials and the benefits of salting and multiple hash iterations are outside the scope of this `Realm` documentation, but definitely read the [HashedCredentialsMatcher JavaDoc](static/current/apidocs/org/apache/shiro/authc/credential/HashedCredentialsMatcher.html) which covers these principles in detail.
+
+<a name="Realm-HashingandCorrespondingMatchers"></a>
+#[[#####Hashing and Corresponding Matchers]]#
+
+So how do you configure a Shiro-enabled application to do this easily?
+
+Shiro provides multiple `HashedCredentialsMatcher` subclass implementations. You must configure the specific implementation on your realm to match the hashing algorithm you use to hash your users' credentials.
+
+For example, let's say your application uses username/password pairs for authentication. And due to the benefits of hashing credentials described above, let's say you want to one-way hash a user's password using the [SHA-256](https://en.wikipedia.org/wiki/SHA_hash_functions) algorithm when you create a user account. You would hash the user's entered plain-text password and save that value:
+
+``` java
+import org.apache.shiro.crypto.hash.Sha256Hash;
+import org.apache.shiro.crypto.RandomNumberGenerator;
+import org.apache.shiro.crypto.SecureRandomNumberGenerator;
+...
+
+//We'll use a Random Number Generator to generate salts.  This 
+//is much more secure than using a username as a salt or not 
+//having a salt at all.  Shiro makes this easy. 
+//
+//Note that a normal app would reference an attribute rather 
+//than create a new RNG every time: 
+RandomNumberGenerator rng = new SecureRandomNumberGenerator();
+Object salt = rng.nextBytes();
+
+//Now hash the plain-text password with the random salt and multiple 
+//iterations and then Base64-encode the value (requires less space than Hex): 
+String hashedPasswordBase64 = new Sha256Hash(plainTextPassword, salt, 1024).toBase64();
+
+User user = new User(username, hashedPasswordBase64);
+//save the salt with the new account.  The HashedCredentialsMatcher 
+//will need it later when handling login attempts: 
+user.setPasswordSalt(salt);
+userDAO.create(user);
+```
+
+Since you're `SHA-256` hashing your user's passwords, you need to tell Shiro to use the appropriate `HashedCredentialsMatcher` to match your hashing preferences. In this example, we create a random salt and perform 1024 hash iterations for strong security (see the `HashedCredentialsMatcher` JavaDoc for why). Here is the Shiro INI configuration to make this work:
+
+``` ini
+[main]
+...
+credentialsMatcher = org.apache.shiro.authc.credential.Sha256CredentialsMatcher
+# base64 encoding, not hex in this example:
+credentialsMatcher.storedCredentialsHexEncoded = false
+credentialsMatcher.hashIterations = 1024
+# This next property is only needed in Shiro 1.0\.  Remove it in 1.1 and later:
+credentialsMatcher.hashSalted = true
+
+...
+myRealm = com.company.....
+myRealm.credentialsMatcher = $credentialsMatcher
+...
+```
+
+<a name="Realm-%7B%7BSaltedAuthenticationInfo%7D%7D"></a>
+#[[######`SaltedAuthenticationInfo`]]#
+
+The last thing to do to ensure this works is that your `Realm` implementation must return a [SaltedAuthenticationInfo](static/current/apidocs/org/apache/shiro/authc/SaltedAuthenticationInfo.html) instance instead of a normal `AuthenticationInfo` one. The `SaltedAuthenticationInfo` interface ensures that the salt that you used when you created the user account (e.g. the `user.setPasswordSalt(salt);` call above) can be referenced by the `HashedCredentialsMatcher`.
+
+The `HashedCredentialsMatcher` needs the salt in order to perform the same hashing technique on the submitted `AuthenticationToken` to see if the token matches what you saved in the data store. So if you use salting for user passwords (and you should!!!), ensure your `Realm` implementation represents that by returning `SaltedAuthenticationInfo` instances.
+
+<a name="Realm-DisablingAuthentication"></a>
+#[[###Disabling Authentication]]#
+
+If for some reason, you don't want a Realm to perform authentication for a data source (maybe because you only want the Realm to perform authorization), you can disable a Realm's support for authentication entirely by always returning `false` from the Realm's `supports` method. Then your realm will never be consulted during an authentication attempt.
+
+Of course at least one configured `Realm` needs to be able to support AuthenticationTokens if you want to authenticate Subjects.
+
+<a name="Realm-RealmAuthorization"></a>
+Realm Authorization
+-------------------
+
+TBD
+
+<a name="Realm-Lendahandwithdocumentation"></a>
+Lend a hand with documentation
+------------------------------
+
+While we hope this documentation helps you with the work you're doing with Apache Shiro, the community is improving and expanding the documentation all the time. If you'd like to help the Shiro project, please consider corrected, expanding, or adding documentation where you see a need. Every little bit of help you provide expands the community and in turn improves Shiro.
+
+The easiest way to contribute your documentation is to send it to the [User Forum](http://shiro-user.582556.n2.nabble.com/) or the [User Mailing List](mailing-lists.html "Mailing Lists").

http://git-wip-us.apache.org/repos/asf/shiro-site/blob/f37b5848/subject.html.vtl
----------------------------------------------------------------------
diff --git a/subject.html.vtl b/subject.html.vtl
deleted file mode 100644
index 0aa3a06..0000000
--- a/subject.html.vtl
+++ /dev/null
@@ -1,355 +0,0 @@
-<h1><a name="Subject-UnderstandingSubjectsinApacheShiro"></a>Understanding Subjects in Apache Shiro</h1>
-
-<p>Without question, the most important concept in Apache Shiro is the <tt>Subject</tt>.  'Subject' is just a security term that means a security-specific 'view' of an application user.  A Shiro <tt>Subject</tt> instance represents both security state and operations for a <em>single</em> application user.</p>
-
-<p>These operations include:</p>
-<ul><li>authentication (login)</li><li>authorization (access control)</li><li>session access</li><li>logout</li></ul>
-
-
-<p>We originally wanted to call it 'User' since that "just makes sense", but we decided against it: too many applications have existing APIs that already have their own User classes/frameworks, and we didn't want to conflict with those. Also, in the security world, the term 'Subject' is actually the recognized nomenclature.</p>
-
-<p>Shiro's API encourages a <tt>Subject</tt>-centric programming paradigm for applications.  When coding application logic, most application developers want to know who the <em>currently executing</em> user is.  While the application can usually look up any user via their own mechanisms (UserService, etc), when it comes to security, the most important question is <b>"Who is the <em>current</em> user?"</b></p>
-
-<p>While any Subject can be acquired by using the <tt>SecurityManager</tt>, application code based on only the current user/<tt>Subject</tt> is much more natural and intuitive.</p>
-
-<h2><a name="Subject-TheCurrentlyExecutingSubject"></a>The Currently Executing Subject</h2>
-
-<p>In almost all environments, you can obtain the currently executing <tt>Subject</tt> by using <tt>org.apache.shiro.SecurityUtils</tt>:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-Subject currentUser = SecurityUtils.getSubject();
-</pre>
-</div></div>
-
-<p>The <tt>getSubject()</tt> call in a standalone application might return a <tt>Subject</tt> based on user data in an application-specific location, and in a server environment (e.g. web app), it acquires the Subject based on user data associated with current thread or incoming request.</p>
-
-<p>After you acquire the current <tt>Subject</tt>, what can you do with it?</p>
-
-<p>If you want to make things available to the user during their current session with the application, you can get their session:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-Session session = currentUser.getSession();
-session.setAttribute( <span class="code-quote">"someKey"</span>, <span class="code-quote">"aValue"</span> );
-</pre>
-</div></div>
-
-<p>The <tt>Session</tt> is a Shiro-specific instance that provides most of what you're used to with regular HttpSessions but with some extra goodies and one <b>big</b> difference:  it does not require an HTTP environment!</p>
-
-<p>If deploying inside a web application, by default the <tt>Session</tt> will be <tt>HttpSession</tt> based.  But, in a non-web environment, like this simple Quickstart, Shiro will automatically use its Enterprise Session Management by default.  This means you get to use the same API in your applications, in any tier, regardless of deployment environment.  This opens a whole new world of applications since any application requiring sessions does not need to be forced to use the <tt>HttpSession</tt> or EJB Stateful Session Beans.  And, any client technology can now share session data.</p>
-
-<p>So now you can acquire a <tt>Subject</tt> and their <tt>Session</tt>.  What about the <em>really</em> useful stuff like checking if they are allowed to do things, like checking against roles and permissions?</p>
-
-<p>Well, we can only do those checks for a known user.  Our <tt>Subject</tt> instance above represents the current user, but <em>who</em> is actually the current user?  Well, they're anonymous - that is, until they log in at least once.  So, let's do that:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-<span class="code-keyword">if</span> ( !currentUser.isAuthenticated() ) {
-    <span class="code-comment">//collect user principals and credentials in a gui specific manner
-</span>    <span class="code-comment">//such as username/password html form, X509 certificate, OpenID, etc.
-</span>    <span class="code-comment">//We'll use the username/password example here since it is the most common.
-</span>    <span class="code-comment">//(<span class="code-keyword">do</span> you know what movie <span class="code-keyword">this</span> is from? ;)
-</span>    UsernamePasswordToken token = <span class="code-keyword">new</span> UsernamePasswordToken(<span class="code-quote">"lonestarr"</span>, <span class="code-quote">"vespa"</span>);
-    <span class="code-comment">//<span class="code-keyword">this</span> is all you have to <span class="code-keyword">do</span> to support 'remember me' (no config - built in!):
-</span>    token.setRememberMe(<span class="code-keyword">true</span>);
-    currentUser.login(token);
-}
-</pre>
-</div></div>
-
-<p>That's it!  It couldn't be easier.</p>
-
-<p>But what if their login attempt fails?  You can catch all sorts of specific exceptions that tell you exactly what happened:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-<span class="code-keyword">try</span> {
-    currentUser.login( token );
-    <span class="code-comment">//<span class="code-keyword">if</span> no exception, that's it, we're done!
-</span>} <span class="code-keyword">catch</span> ( UnknownAccountException uae ) {
-    <span class="code-comment">//username wasn't in the system, show them an error message?
-</span>} <span class="code-keyword">catch</span> ( IncorrectCredentialsException ice ) {
-    <span class="code-comment">//password didn't match, <span class="code-keyword">try</span> again?
-</span>} <span class="code-keyword">catch</span> ( LockedAccountException lae ) {
-    <span class="code-comment">//account <span class="code-keyword">for</span> that username is locked - can't login.  Show them a message?
-</span>} 
-    ... more types exceptions to check <span class="code-keyword">if</span> you want ...
-} <span class="code-keyword">catch</span> ( AuthenticationException ae ) {
-    <span class="code-comment">//unexpected condition - error?
-</span>}
-</pre>
-</div></div>
-
-<p>You, as the application/GUI developer can choose to show the end-user messages based on exceptions or not (for example, <tt>"There is no account in the system with that username."</tt>).  There are many different types of exceptions you can check, or throw your own for custom conditions Shiro might not account for.  See the <a class="external-link" href="https://shiro.apache.org/static/current/apidocs/org/apache/shiro/authc/AuthenticationException.html" rel="nofollow">AuthenticationException JavaDoc</a> for more.</p>
-
-<p>Ok, so by now, we have a logged in user.  What else can we do?</p>
-
-<p>Let's say who they are:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-<span class="code-comment">//print their identifying principal (in <span class="code-keyword">this</span> <span class="code-keyword">case</span>, a username):
-</span>log.info( <span class="code-quote">"User ["</span> + currentUser.getPrincipal() + <span class="code-quote">"] logged in successfully."</span> );
-</pre>
-</div></div>
-
-<p>We can also test to see if they have specific role or not:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-<span class="code-keyword">if</span> ( currentUser.hasRole( <span class="code-quote">"schwartz"</span> ) ) {
-    log.info(<span class="code-quote">"May the Schwartz be with you!"</span> );
-} <span class="code-keyword">else</span> {
-    log.info( <span class="code-quote">"Hello, mere mortal."</span> );
-}
-</pre>
-</div></div>
-
-<p>We can also see if they have a <a href="permissions.html" title="Permissions">permission</a> to act on a certain type of entity:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-<span class="code-keyword">if</span> ( currentUser.isPermitted( <span class="code-quote">"lightsaber:weild"</span> ) ) {
-    log.info(<span class="code-quote">"You may use a lightsaber ring.  Use it wisely."</span>);
-} <span class="code-keyword">else</span> {
-    log.info(<span class="code-quote">"Sorry, lightsaber rings are <span class="code-keyword">for</span> schwartz masters only."</span>);
-}
-</pre>
-</div></div>
-
-<p>Also, we can perform an extremely powerful <em>instance-level</em> <a href="permissions.html" title="Permissions">permission</a> check - the ability to see if the user has the ability to access a specific instance of a type:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-<span class="code-keyword">if</span> ( currentUser.isPermitted( <span class="code-quote">"winnebago:drive:eagle5"</span> ) ) {
-    log.info(<span class="code-quote">"You are permitted to 'drive' the 'winnebago' with license plate (id) 'eagle5'.  "</span> +
-                <span class="code-quote">"Here are the keys - have fun!"</span>);
-} <span class="code-keyword">else</span> {
-    log.info(<span class="code-quote">"Sorry, you aren't allowed to drive the 'eagle5' winnebago!"</span>);
-}
-</pre>
-</div></div>
-
-<p>Piece of cake, right?</p>
-
-<p>Finally, when the user is done using the application, they can log out:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-currentUser.logout(); <span class="code-comment">//removes all identifying information and invalidates their session too.</span>
-</pre>
-</div></div>
-
-<p>This simple API constitutes 90% of what Shiro end-users will ever have to deal with when using Shiro.</p>
-
-<h2><a name="Subject-CustomSubjectInstances"></a>Custom Subject Instances</h2>
-
-<p>A new feature added in Shiro 1.0 is the ability to construct custom/ad-hoc subject instances for use in special situations.</p>
-
-#warning('Special Use Only!', 'You should almost always acquire the currently executing Subject by calling <tt>SecurityUtils.getSubject();</tt><br clear="none">Creating custom <tt>Subject</tt> instances should only be done in special cases.')
-
-<p>Some 'special cases' when this can be useful:</p>
-
-<ul><li>System startup/bootstrap - when there are no users interacting with the system, but code should execute as a 'system' or daemon user.  It is desirable to create Subject instances representing a particular user so bootstrap code executes as that user (e.g. as the <tt>admin</tt> user).
-<br clear="none" class="atl-forced-newline">
-<br clear="none" class="atl-forced-newline">
-This practice is encouraged because it ensures that utility/system code executes in the same way as a normal user, ensuring code is consistent.  This makes code easier to maintain since you don't have to worry about custom code blocks just for system/daemon scenarios.
-<br clear="none" class="atl-forced-newline">
-<br clear="none" class="atl-forced-newline"></li><li>Integration <a href="testing.html" title="Testing">Testing</a> - you might want to create <tt>Subject</tt> instances as necessary to be used in integration tests.  See the <a href="testing.html" title="Testing">testing documentation</a> for more.
-<br clear="none" class="atl-forced-newline">
-<br clear="none" class="atl-forced-newline"></li><li>Daemon/background process work - when a daemon or background process executes, it might need to execute as a particular user.</li></ul>
-
-
-#tip('Tip', 'If you already have access to a <tt>Subject</tt> instance and want it to be available to other threads, you should use the <tt>Subject.associateWith</tt>* methods instead of creating a new Subject instance.')
-
-<p>Ok, so assuming you still need to create custom subject instances, let's see how to do it:</p>
-
-<h3><a name="Subject-Subject.Builder"></a>Subject.Builder</h3>
-
-<p>The <tt>Subject.Builder</tt> class is provided to build <tt>Subject</tt> instances easily without needing to know construction details.</p>
-
-<p>The simplest usage of the Builder is to construct an anonymous, session-less <tt>Subject</tt> instance:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-Subject subject = <span class="code-keyword">new</span> Subject.Builder().buildSubject()
-</pre>
-</div></div>
-
-<p>The default, no-arg <tt>Subject.Builder()</tt> constructor shown above will use the application's currently accessible <tt>SecurityManager</tt> via the <tt>SecurityUtils.getSecurityManager()</tt> method.  You may also specify the <tt>SecurityManager</tt> instance to be used by the additional constructor if desired:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-<span class="code-object">SecurityManager</span> securityManager = <span class="code-comment">//acquired from somewhere
-</span>Subject subject = <span class="code-keyword">new</span> Subject.Builder(securityManager).buildSubject();
-</pre>
-</div></div>
-
-<p>All other <tt>Subject.Builder</tt> methods may be called before the <tt>buildSubject()</tt> method to provide context on how to construct the <tt>Subject</tt> instance.  For example, if you have a session ID and want to acquire the <tt>Subject</tt> that 'owns' that session (assuming the session exists and is not expired):</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-Serializable sessionId = <span class="code-comment">//acquired from somewhere
-</span>Subject subject = <span class="code-keyword">new</span> Subject.Builder().sessionId(sessionId).buildSubject();
-</pre>
-</div></div>
-
-<p>Similarly, if you want to create a <tt>Subject</tt> instance that reflects a certain identity:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-<span class="code-object">Object</span> userIdentity = <span class="code-comment">//a <span class="code-object">long</span> ID or <span class="code-object">String</span> username, or whatever the <span class="code-quote">"myRealm"</span> requires
-</span><span class="code-object">String</span> realmName = <span class="code-quote">"myRealm"</span>;
-PrincipalCollection principals = <span class="code-keyword">new</span> SimplePrincipalCollection(userIdentity, realmName);
-Subject subject = <span class="code-keyword">new</span> Subject.Builder().principals(principals).buildSubject();
-</pre>
-</div></div>
-
-<p>You can then use the built <tt>Subject</tt> instance and make calls on it as expected. But <b>note</b>:  </p>
-
-<p>The built <tt>Subject</tt> instance is <b>not</b> automatically bound to the application (thread) for further use.  If you want it to be available to any code that calls <tt>SecurityUtils.getSubject()</tt>, you must ensure a Thread is associated with the constructed <tt>Subject</tt>.</p>
-
-<h3><a name="Subject-ThreadAssociation"></a>Thread Association <a name="Subject-ThreadAssociation"></a></h3>
-
-<p>As stated above, just building a <tt>Subject</tt> instance does not associate it with a thread - a usual requirement if any calls to <tt>SecurityUtils.getSubject()</tt> during thread execution are to work properly.  There are three ways of ensuring a thread is associated with a <tt>Subject</tt>:</p>
-
-<ul><li><b>Automatic Association</b> - A <tt>Callable</tt> or <tt>Runnable</tt> executed via the <tt>Subject.execute</tt>* methods will automatically bind and unbind the Subject to the thread before and after <tt>Callable</tt>/<tt>Runnable</tt> execution.
-<br clear="none" class="atl-forced-newline">
-<br clear="none" class="atl-forced-newline"></li><li><b>Manual Association</b> - You manually bind and unbind the <tt>Subject</tt> instance to the currently executing thread.  This is usually useful for framework developers.
-<br clear="none" class="atl-forced-newline">
-<br clear="none" class="atl-forced-newline"></li><li><b>Different Thread</b> - A <tt>Callable</tt> or <tt>Runnable</tt> is associated with a <tt>Subject</tt> by calling the <tt>Subject.associateWith</tt>* methods and then the returned <tt>Callable</tt>/<tt>Runnable</tt> is executed by another thread.  This is the preferred approach if you need to execute work on another thread as the <tt>Subject</tt>.</li></ul>
-
-
-<p>The important thing to know about thread association is that 2 things must always occur:</p>
-
-<ol><li>The Subject is <em>bound</em> to the thread so it is available at all points of the thread's execution.  Shiro does this via its <tt>ThreadState</tt> mechanism which is an abstraction on top of a <tt>ThreadLocal</tt>.</li><li>The Subject is <em>unbound</em> at some point later, even if the thread execution results in an error.  This ensures the thread remains clean and clear of any previous <tt>Subject</tt> state in a pooled/reusable thread environment.</li></ol>
-
-
-<p>These principles are guaranteed to occur in the 3 mechanisms listed above.  Their usage is elaborated next.</p>
-
-<h4><a name="Subject-AutomaticAssociation"></a>Automatic Association </h4>
-
-<p>If you only need a <tt>Subject</tt> to be temporarily associated with the current thread, and you want the thread binding and cleanup to occur automatically, a <tt>Subject</tt>'s direct execution of a <tt>Callable</tt> or <tt>Runnable</tt> is the way to go.  After the <tt>Subject.execute</tt> call returns, the current thread is guaranteed to be in the same state as it was before the execution.  This mechanism is the most widely used of the three.</p>
-
-<p>For example, let's say that you had some logic to perform when the system starts up.  You want to execute a chunk of code as a particular user, but once the logic is finished, you want to ensure the thread/environment goes back to normal automatically.  You would do that by calling the <tt>Subject.execute</tt>* methods:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-Subject subject = <span class="code-comment">//build or acquire subject
-</span>subject.execute( <span class="code-keyword">new</span> <span class="code-object">Runnable</span>() {
-    <span class="code-keyword">public</span> void run() {
-        <span class="code-comment">//subject is 'bound' to the current thread now
-</span>        <span class="code-comment">//any SecurityUtils.getSubject() calls in any
-</span>        <span class="code-comment">//code called from here will work
-</span>    }
-});
-<span class="code-comment">//At <span class="code-keyword">this</span> point, the Subject is no longer associated
-</span><span class="code-comment">//with the current thread and everything is as it was before</span>
-</pre>
-</div></div>
-
-<p>Of course <tt>Callable</tt> instances are supported as well so you can have return values and catch exceptions:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-Subject subject = <span class="code-comment">//build or acquire subject
-</span>MyResult result = subject.execute( <span class="code-keyword">new</span> Callable&lt;MyResult&gt;() {
-    <span class="code-keyword">public</span> MyResult call() <span class="code-keyword">throws</span> Exception {
-        <span class="code-comment">//subject is 'bound' to the current thread now
-</span>        <span class="code-comment">//any SecurityUtils.getSubject() calls in any
-</span>        <span class="code-comment">//code called from here will work
-</span>        ...
-        <span class="code-comment">//finish logic as <span class="code-keyword">this</span> Subject
-</span>        ...
-        <span class="code-keyword">return</span> myResult;        
-    }
-});
-<span class="code-comment">//At <span class="code-keyword">this</span> point, the Subject is no longer associated
-</span><span class="code-comment">//with the current thread and everything is as it was before</span>
-</pre>
-</div></div>
-
-<p>This approach is also useful in framework development.  For example, Shiro's support for secure Spring remoting ensures the remote invocation is executed as a particular subject:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-Subject.Builder builder = <span class="code-keyword">new</span> Subject.Builder();
-<span class="code-comment">//populate the builder's attributes based on the incoming RemoteInvocation
-</span>...
-Subject subject = builder.buildSubject();
-
-<span class="code-keyword">return</span> subject.execute(<span class="code-keyword">new</span> Callable() {
-    <span class="code-keyword">public</span> <span class="code-object">Object</span> call() <span class="code-keyword">throws</span> Exception {
-        <span class="code-keyword">return</span> invoke(invocation, targetObject);
-    }
-});
-</pre>
-</div></div>
-
-<h4><a name="Subject-ManualAssociation"></a>Manual Association</h4>
-
-<p>While the <tt>Subject.execute</tt>* methods automatically clean up the thread state after they return, there might be some scenarios where you want to manage the <tt>ThreadState</tt> yourself.  This is almost always done in framework-level development when integrating w/ Shiro and is rarely used even in bootstrap/daemon scenarios (where the <tt>Subject.execute(callable)</tt> example above is more frequent).</p>
-
-#warning('Guarantee Cleanup', 'The most important thing about this mechanism is that you must <em>always</em> guarantee the current thread is cleaned up after logic is executed to ensure there is no thread state corruption in a reusable or pooled thread environment.')
-
-<p>Guaranteeing cleanup is best done in a <tt>try/finally</tt> block:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-Subject subject = <span class="code-keyword">new</span> Subject.Builder()...
-ThreadState threadState = <span class="code-keyword">new</span> SubjectThreadState(subject);
-threadState.bind();
-<span class="code-keyword">try</span> {
-    <span class="code-comment">//execute work as the built Subject
-</span>} <span class="code-keyword">finally</span> {
-    <span class="code-comment">//ensure any state is cleaned so the thread won't be 
-</span>    <span class="code-comment">//corrupt in a reusable or pooled thread environment
-</span>    threadState.clear();
-}
-</pre>
-</div></div>
-
-<p>Interestingly enough, this is exactly what the <tt>Subject.execute</tt>* methods do - they just perform this logic automatically before and after <tt>Callable</tt> or <tt>Runnable</tt> execution.  It is also nearly identical logic performed by Shiro's <tt>ShiroFilter</tt> for web applications (<tt>ShiroFilter</tt> uses web-specific <tt>ThreadState</tt> implementations outside the scope of this section).</p>
-
-#danger('Web Use', 'Don''t use the above <tt>ThreadState</tt> code example in a thread that is processing a web request.  Web-specific ThreadState implementations are used during web requests instead.  Instead, ensure the <tt>ShiroFilter</tt> intercepts web requests to ensure Subject building/binding/cleanup is done properly.')
-
-<h4><a name="Subject-ADifferentThread"></a>A Different Thread</h4>
-
-<p>If you have a <tt>Callable</tt> or <tt>Runnable</tt> instance that should execute as a <tt>Subject</tt> and you will execute the <tt>Callable</tt> or <tt>Runnable</tt> yourself (or hand it off to a thread pool or <tt>Executor</tt> or <tt>ExecutorService</tt> for example), you should use the <tt>Subject.associateWith</tt>* methods.  These methods ensure that the Subject is retained and accessible on the thread that eventually executes.</p>
-
-<p>Callable example:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-Subject subject = <span class="code-keyword">new</span> Subject.Builder()...
-Callable work = <span class="code-comment">//build/acquire a Callable instance.
-</span><span class="code-comment">//associate the work with the built subject so SecurityUtils.getSubject() calls works properly:
-</span>work = subject.associateWith(work);
-ExecutorService executorService = <span class="code-keyword">new</span> java.util.concurrent.Executors.newCachedThreadPool();
-<span class="code-comment">//execute the work on a different thread as the built Subject:
-</span>executor.execute(work);
-</pre>
-</div></div>
-
-<p>Runnable example:</p>
-
-<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
-<pre class="code-java">
-Subject subject = <span class="code-keyword">new</span> Subject.Builder()...
-<span class="code-object">Runnable</span> work = <span class="code-comment">//build/acquire a <span class="code-object">Runnable</span> instance.
-</span><span class="code-comment">//associate the work with the built subject so SecurityUtils.getSubject() calls works properly:
-</span>work = subject.associateWith(work);
-Executor executor = <span class="code-keyword">new</span> java.util.concurrent.Executors.newCachedThreadPool();
-<span class="code-comment">//execute the work on a different thread as the built Subject:
-</span>executor.execute(work);
-</pre>
-</div></div>
-
-#tip('Automatic Cleanup', 'The <tt>associateWith</tt>* methods perform necessary thread cleanup automatically to ensure threads remain clean in a pooled environment.')
-
-<h2><a name="Subject-Lendahandwithdocumentation"></a>Lend a hand with documentation </h2>
-
-<p>While we hope this documentation helps you with the work you're doing with Apache Shiro, the community is improving and expanding the documentation all the time.  If you'd like to help the Shiro project, please consider corrected, expanding, or adding documentation where you see a need. Every little bit of help you provide expands the community and in turn improves Shiro. </p>
-
-<p>The easiest way to contribute your documentation is to send it to the <a class="external-link" href="http://shiro-user.582556.n2.nabble.com/" rel="nofollow">User Forum</a> or the <a href="mailing-lists.html" title="Mailing Lists">User Mailing List</a>.</p>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/shiro-site/blob/f37b5848/subject.md.vtl
----------------------------------------------------------------------
diff --git a/subject.md.vtl b/subject.md.vtl
new file mode 100644
index 0000000..62ccd1b
--- /dev/null
+++ b/subject.md.vtl
@@ -0,0 +1,328 @@
+<a name="Subject-UnderstandingSubjectsinApacheShiro"></a>
+Understanding Subjects in Apache Shiro
+======================================
+
+Without question, the most important concept in Apache Shiro is the `Subject`. 'Subject' is just a security term that means a security-specific 'view' of an application user. A Shiro `Subject` instance represents both security state and operations for a _single_ application user.
+
+These operations include:
+
+*   authentication (login)
+*   authorization (access control)
+*   session access
+*   logout
+
+We originally wanted to call it 'User' since that "just makes sense", but we decided against it: too many applications have existing APIs that already have their own User classes/frameworks, and we didn't want to conflict with those. Also, in the security world, the term 'Subject' is actually the recognized nomenclature.
+
+Shiro's API encourages a `Subject`-centric programming paradigm for applications. When coding application logic, most application developers want to know who the _currently executing_ user is. While the application can usually look up any user via their own mechanisms (UserService, etc), when it comes to security, the most important question is **"Who is the _current_ user?"**
+
+While any Subject can be acquired by using the `SecurityManager`, application code based on only the current user/`Subject` is much more natural and intuitive.
+
+<a name="Subject-TheCurrentlyExecutingSubject"></a>
+The Currently Executing Subject
+-------------------------------
+
+In almost all environments, you can obtain the currently executing `Subject` by using `org.apache.shiro.SecurityUtils`:
+
+``` java
+Subject currentUser = SecurityUtils.getSubject();
+```
+
+The `getSubject()` call in a standalone application might return a `Subject` based on user data in an application-specific location, and in a server environment (e.g. web app), it acquires the Subject based on user data associated with current thread or incoming request.
+
+After you acquire the current `Subject`, what can you do with it?
+
+If you want to make things available to the user during their current session with the application, you can get their session:
+
+``` java
+Session session = currentUser.getSession();
+session.setAttribute( "someKey", "aValue" );
+```
+
+The `Session` is a Shiro-specific instance that provides most of what you're used to with regular HttpSessions but with some extra goodies and one **big** difference: it does not require an HTTP environment!
+
+If deploying inside a web application, by default the `Session` will be `HttpSession` based. But, in a non-web environment, like this simple Quickstart, Shiro will automatically use its Enterprise Session Management by default. This means you get to use the same API in your applications, in any tier, regardless of deployment environment. This opens a whole new world of applications since any application requiring sessions does not need to be forced to use the `HttpSession` or EJB Stateful Session Beans. And, any client technology can now share session data.
+
+So now you can acquire a `Subject` and their `Session`. What about the _really_ useful stuff like checking if they are allowed to do things, like checking against roles and permissions?
+
+Well, we can only do those checks for a known user. Our `Subject` instance above represents the current user, but _who_ is actually the current user? Well, they're anonymous - that is, until they log in at least once. So, let's do that:
+
+``` java
+if ( !currentUser.isAuthenticated() ) {
+    //collect user principals and credentials in a gui specific manner
+    //such as username/password html form, X509 certificate, OpenID, etc.
+    //We'll use the username/password example here since it is the most common.
+    //(do you know what movie this is from? ;)
+    UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
+    //this is all you have to do to support 'remember me' (no config - built in!):
+    token.setRememberMe(true);
+    currentUser.login(token);
+}
+```
+
+That's it! It couldn't be easier.
+
+But what if their login attempt fails? You can catch all sorts of specific exceptions that tell you exactly what happened:
+
+``` java
+try {
+    currentUser.login( token );
+    //if no exception, that's it, we're done!
+} catch ( UnknownAccountException uae ) {
+    //username wasn't in the system, show them an error message?
+} catch ( IncorrectCredentialsException ice ) {
+    //password didn't match, try again?
+} catch ( LockedAccountException lae ) {
+    //account for that username is locked - can't login.  Show them a message?
+}
+    ... more types exceptions to check if you want ...
+} catch ( AuthenticationException ae ) {
+    //unexpected condition - error?
+}
+```
+
+You, as the application/GUI developer can choose to show the end-user messages based on exceptions or not (for example, `"There is no account in the system with that username."`). There are many different types of exceptions you can check, or throw your own for custom conditions Shiro might not account for. See the [AuthenticationException JavaDoc](https://shiro.apache.org/static/current/apidocs/org/apache/shiro/authc/AuthenticationException.html) for more.
+
+Ok, so by now, we have a logged in user. What else can we do?
+
+Let's say who they are:
+
+``` java
+//print their identifying principal (in this case, a username): 
+log.info( "User [" + currentUser.getPrincipal() + "] logged in successfully." );
+```
+
+We can also test to see if they have specific role or not:
+
+``` java
+if ( currentUser.hasRole( "schwartz" ) ) {
+    log.info("May the Schwartz be with you!" );
+} else {
+    log.info( "Hello, mere mortal." );
+}
+```
+
+We can also see if they have a [permission](permissions.html "Permissions") to act on a certain type of entity:
+
+``` java
+if ( currentUser.isPermitted( "lightsaber:weild" ) ) {
+    log.info("You may use a lightsaber ring.  Use it wisely.");
+} else {
+    log.info("Sorry, lightsaber rings are for schwartz masters only.");
+}
+```
+
+Also, we can perform an extremely powerful _instance-level_ [permission](permissions.html "Permissions") check - the ability to see if the user has the ability to access a specific instance of a type:
+
+``` java
+if ( currentUser.isPermitted( "winnebago:drive:eagle5" ) ) {
+    log.info("You are permitted to 'drive' the 'winnebago' with license plate (id) 'eagle5'.  " +
+                "Here are the keys - have fun!");
+} else {
+    log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
+}
+```
+
+Piece of cake, right?
+
+Finally, when the user is done using the application, they can log out:
+
+``` java
+currentUser.logout(); //removes all identifying information and invalidates their session too.
+```
+
+This simple API constitutes 90% of what Shiro end-users will ever have to deal with when using Shiro.
+
+<a name="Subject-CustomSubjectInstances"></a>
+Custom Subject Instances
+------------------------
+
+A new feature added in Shiro 1.0 is the ability to construct custom/ad-hoc subject instances for use in special situations.
+
+#warning('Special Use Only!', 'You should almost always acquire the currently executing Subject by calling <code>SecurityUtils.getSubject();</code> Creating custom <code>Subject</code> instances should only be done in special cases.')
+
+Some 'special cases' when this can be useful:
+
+*   System startup/bootstrap - when there are no users interacting with the system, but code should execute as a 'system' or daemon user. It is desirable to create Subject instances representing a particular user so bootstrap code executes as that user (e.g. as the `admin` user).
+
+    This practice is encouraged because it ensures that utility/system code executes in the same way as a normal user, ensuring code is consistent. This makes code easier to maintain since you don't have to worry about custom code blocks just for system/daemon scenarios.
+
+*   Integration [Testing](testing.html "Testing") - you might want to create `Subject` instances as necessary to be used in integration tests. See the [testing documentation](testing.html "Testing") for more.
+
+*   Daemon/background process work - when a daemon or background process executes, it might need to execute as a particular user.
+
+#tip('Tip', 'If you already have access to a <code>Subject</code> instance and want it to be available to other threads, you should use the <code>Subject.associateWith</code>* methods instead of creating a new Subject instance.')
+
+Ok, so assuming you still need to create custom subject instances, let's see how to do it:
+
+<a name="Subject-Subject.Builder"></a>
+#[[###Subject.Builder]]#
+
+The `Subject.Builder` class is provided to build `Subject` instances easily without needing to know construction details.
+
+The simplest usage of the Builder is to construct an anonymous, session-less `Subject` instance:
+
+``` java
+Subject subject = new Subject.Builder().buildSubject()
+```
+
+The default, no-arg `Subject.Builder()` constructor shown above will use the application's currently accessible `SecurityManager` via the `SecurityUtils.getSecurityManager()` method. You may also specify the `SecurityManager` instance to be used by the additional constructor if desired:
+
+``` java
+SecurityManager securityManager = //acquired from somewhere 
+Subject subject = new Subject.Builder(securityManager).buildSubject();
+```
+
+All other `Subject.Builder` methods may be called before the `buildSubject()` method to provide context on how to construct the `Subject` instance. For example, if you have a session ID and want to acquire the `Subject` that 'owns' that session (assuming the session exists and is not expired):
+
+``` java
+Serializable sessionId = //acquired from somewhere 
+Subject subject = new Subject.Builder().sessionId(sessionId).buildSubject();
+```
+
+Similarly, if you want to create a `Subject` instance that reflects a certain identity:
+
+``` java
+Object userIdentity = //a long ID or String username, or whatever the "myRealm" requires 
+String realmName = "myRealm";
+PrincipalCollection principals = new SimplePrincipalCollection(userIdentity, realmName);
+Subject subject = new Subject.Builder().principals(principals).buildSubject();
+```
+
+You can then use the built `Subject` instance and make calls on it as expected. But **note**:
+
+The built `Subject` instance is **not** automatically bound to the application (thread) for further use. If you want it to be available to any code that calls `SecurityUtils.getSubject()`, you must ensure a Thread is associated with the constructed `Subject`.
+
+<a name="Subject-ThreadAssociation"></a>
+#[[### Thread Association]]#
+
+As stated above, just building a `Subject` instance does not associate it with a thread - a usual requirement if any calls to `SecurityUtils.getSubject()` during thread execution are to work properly. There are three ways of ensuring a thread is associated with a `Subject`:
+
+*   **Automatic Association** - A `Callable` or `Runnable` executed via the `Subject.execute`* methods will automatically bind and unbind the Subject to the thread before and after `Callable`/`Runnable` execution.
+
+*   **Manual Association** - You manually bind and unbind the `Subject` instance to the currently executing thread. This is usually useful for framework developers.
+
+*   **Different Thread** - A `Callable` or `Runnable` is associated with a `Subject` by calling the `Subject.associateWith`* methods and then the returned `Callable`/`Runnable` is executed by another thread. This is the preferred approach if you need to execute work on another thread as the `Subject`.
+
+The important thing to know about thread association is that 2 things must always occur:
+
+1.  The Subject is _bound_ to the thread so it is available at all points of the thread's execution. Shiro does this via its `ThreadState` mechanism which is an abstraction on top of a `ThreadLocal`.
+2.  The Subject is _unbound_ at some point later, even if the thread execution results in an error. This ensures the thread remains clean and clear of any previous `Subject` state in a pooled/reusable thread environment.
+
+These principles are guaranteed to occur in the 3 mechanisms listed above. Their usage is elaborated next.
+
+<a name="Subject-AutomaticAssociation"></a>
+#[[####Automatic Association]]#
+
+If you only need a `Subject` to be temporarily associated with the current thread, and you want the thread binding and cleanup to occur automatically, a `Subject`'s direct execution of a `Callable` or `Runnable` is the way to go. After the `Subject.execute` call returns, the current thread is guaranteed to be in the same state as it was before the execution. This mechanism is the most widely used of the three.
+
+For example, let's say that you had some logic to perform when the system starts up. You want to execute a chunk of code as a particular user, but once the logic is finished, you want to ensure the thread/environment goes back to normal automatically. You would do that by calling the `Subject.execute`* methods:
+
+``` java
+Subject subject = //build or acquire subject 
+subject.execute( new Runnable() {
+    public void run() {
+        //subject is 'bound' to the current thread now
+        //any SecurityUtils.getSubject() calls in any
+        //code called from here will work
+    }
+});
+//At this point, the Subject is no longer associated 
+//with the current thread and everything is as it was before
+```
+
+Of course `Callable` instances are supported as well so you can have return values and catch exceptions:
+
+``` java
+Subject subject = //build or acquire subject 
+MyResult result = subject.execute( new Callable<MyResult>() {
+    public MyResult call() throws Exception {
+        //subject is 'bound' to the current thread now
+        //any SecurityUtils.getSubject() calls in any
+        //code called from here will work
+        ...
+        //finish logic as this Subject
+        ...
+        return myResult;
+    }
+});
+//At this point, the Subject is no longer associated 
+//with the current thread and everything is as it was before
+```
+
+This approach is also useful in framework development. For example, Shiro's support for secure Spring remoting ensures the remote invocation is executed as a particular subject:
+
+``` java
+Subject.Builder builder = new Subject.Builder();
+//populate the builder's attributes based on the incoming RemoteInvocation ...
+Subject subject = builder.buildSubject();
+
+return subject.execute(new Callable() {
+    public Object call() throws Exception {
+        return invoke(invocation, targetObject);
+    }
+});
+```
+
+<a name="Subject-ManualAssociation"></a>
+#[[####Manual Association]]#
+
+While the `Subject.execute`* methods automatically clean up the thread state after they return, there might be some scenarios where you want to manage the `ThreadState` yourself. This is almost always done in framework-level development when integrating w/ Shiro and is rarely used even in bootstrap/daemon scenarios (where the `Subject.execute(callable)` example above is more frequent).
+
+#warning('Guarantee Cleanup', 'The most important thing about this mechanism is that you must <em>always</em> guarantee the current thread is cleaned up after logic is executed to ensure there is no thread state corruption in a reusable or pooled thread environment.')
+
+Guaranteeing cleanup is best done in a `try/finally` block:
+
+``` java
+Subject subject = new Subject.Builder()...
+ThreadState threadState = new SubjectThreadState(subject);
+threadState.bind();
+try {
+    //execute work as the built Subject
+} finally {
+    //ensure any state is cleaned so the thread won't be
+    //corrupt in a reusable or pooled thread environment
+    threadState.clear();
+}
+```
+
+Interestingly enough, this is exactly what the `Subject.execute`* methods do - they just perform this logic automatically before and after `Callable` or `Runnable` execution. It is also nearly identical logic performed by Shiro's `ShiroFilter` for web applications (`ShiroFilter` uses web-specific `ThreadState` implementations outside the scope of this section).
+
+#danger('Web Use', 'Don''t use the above <code>ThreadState</code> code example in a thread that is processing a web request.  Web-specific ThreadState implementations are used during web requests instead.  Instead, ensure the <code>ShiroFilter</code> intercepts web requests to ensure Subject building/binding/cleanup is done properly.')
+
+<a name="Subject-ADifferentThread"></a>
+#[[####A Different Thread]]#
+
+If you have a `Callable` or `Runnable` instance that should execute as a `Subject` and you will execute the `Callable` or `Runnable` yourself (or hand it off to a thread pool or `Executor` or `ExecutorService` for example), you should use the `Subject.associateWith`* methods. These methods ensure that the Subject is retained and accessible on the thread that eventually executes.
+
+Callable example:
+
+``` java
+Subject subject = new Subject.Builder()...
+Callable work = //build/acquire a Callable instance. 
+//associate the work with the built subject so SecurityUtils.getSubject() calls works properly: 
+work = subject.associateWith(work);
+ExecutorService executorService = new java.util.concurrent.Executors.newCachedThreadPool();
+//execute the work on a different thread as the built Subject: 
+executor.execute(work);
+```
+
+Runnable example:
+
+``` java
+Subject subject = new Subject.Builder()...
+Runnable work = //build/acquire a Runnable instance. 
+//associate the work with the built subject so SecurityUtils.getSubject() calls works properly: 
+work = subject.associateWith(work);
+Executor executor = new java.util.concurrent.Executors.newCachedThreadPool();
+//execute the work on a different thread as the built Subject: executor.execute(work);
+```
+
+#tip('Automatic Cleanup', 'The <code>associateWith</code>* methods perform necessary thread cleanup automatically to ensure threads remain clean in a pooled environment.')
+
+<a name="Subject-Lendahandwithdocumentation"></a>
+Lend a hand with documentation
+------------------------------
+
+While we hope this documentation helps you with the work you're doing with Apache Shiro, the community is improving and expanding the documentation all the time. If you'd like to help the Shiro project, please consider corrected, expanding, or adding documentation where you see a need. Every little bit of help you provide expands the community and in turn improves Shiro.
+
+The easiest way to contribute your documentation is to send it to the [User Forum](http://shiro-user.582556.n2.nabble.com/) or the [User Mailing List](mailing-lists.html "Mailing Lists").
\ No newline at end of file


Mime
View raw message