shiro-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From bdem...@apache.org
Subject [55/67] shiro-site git commit: initial attempt at adding a bootstrap
Date Wed, 19 Oct 2016 14:24:45 GMT
http://git-wip-us.apache.org/repos/asf/shiro-site/blob/ddea166c/subject.html.vtl
----------------------------------------------------------------------
diff --git a/subject.html.vtl b/subject.html.vtl
new file mode 100644
index 0000000..a3f2914
--- /dev/null
+++ b/subject.html.vtl
@@ -0,0 +1,355 @@
+<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="http://www.jsecurity.org/api/org/jsecurity/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/ddea166c/templates/default.vtl
----------------------------------------------------------------------
diff --git a/templates/default.vtl b/templates/default.vtl
index 581b7ce..15d4dab 100644
--- a/templates/default.vtl
+++ b/templates/default.vtl
@@ -15,6 +15,9 @@
    limitations under the License.
 -->
 <html>
+
+#parse("templates/macros.vtl")
+
 <head>
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     <meta name="description" content="Apache Shiro is a powerful and easy-to-use Java security framework that performs authentication, authorization, cryptography, and session management.">
@@ -39,16 +42,29 @@
     </title>
 
 
+    <link rel="stylesheet" href="$root/assets/css/gh-pages/gh-fork-ribbon.css" />
+    <!--[if lt IE 9]>
+      <link rel="stylesheet" href="$root/assets/css/gh-pages/gh-fork-ribbon.ie.css" />
+    <![endif]-->
+
+
+
     <link rel="icon" type="image/vnd.microsoft.icon" href="$root/assets/images/favicon.ico">
 
+    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
+    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
+    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
+    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css">
+
+    <!--
+    <link rel="stylesheet" href="https://oss.maxcdn.com/libs/normalize-css/3.0.0/normalize.min.css">
+    -->
+
     <link rel="stylesheet" type="text/css" href="$root/assets/css/normalize.css">
+
     <link rel="stylesheet" type="text/css" href="$root/assets/css/confluence.css" media="screen">
     <link rel="stylesheet" type="text/css" href="$root/assets/css/style.css">
 
-    <link rel="stylesheet" href="$root/assets/css/gh-pages/gh-fork-ribbon.css" />
-    <!--[if lt IE 9]>
-      <link rel="stylesheet" href="$root/assets/css/gh-pages/gh-fork-ribbon.ie.css" />
-    <![endif]-->
 
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
     <script type="text/javascript" src="$root/assets/js/jquery_googleanalytics/jquery.google-analytics.js"></script>

http://git-wip-us.apache.org/repos/asf/shiro-site/blob/ddea166c/templates/macros.vtl
----------------------------------------------------------------------
diff --git a/templates/macros.vtl b/templates/macros.vtl
new file mode 100644
index 0000000..7d9b83e
--- /dev/null
+++ b/templates/macros.vtl
@@ -0,0 +1,6 @@
+#parse( "templates/macros/danger.vtl" )
+#parse( "templates/macros/info.vtl" )
+#parse( "templates/macros/tip.vtl" )
+#parse( "templates/macros/warning.vtl" )
+#parse( "templates/macros/lend-a-hand.vtl" )
+#parse( "templates/macros/redirect.vtl" )
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/shiro-site/blob/ddea166c/templates/macros/danger.vtl
----------------------------------------------------------------------
diff --git a/templates/macros/danger.vtl b/templates/macros/danger.vtl
new file mode 100644
index 0000000..6fd069f
--- /dev/null
+++ b/templates/macros/danger.vtl
@@ -0,0 +1,7 @@
+#macro(danger $title, $message)
+<div markdown="span" class="alert alert-danger" role="alert">
+    <i class="fa fa-exclamation-circle"></i>
+    <b>${title}</b><br/>
+    ${message}
+</div>
+#end
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/shiro-site/blob/ddea166c/templates/macros/info.vtl
----------------------------------------------------------------------
diff --git a/templates/macros/info.vtl b/templates/macros/info.vtl
new file mode 100644
index 0000000..805e1dc
--- /dev/null
+++ b/templates/macros/info.vtl
@@ -0,0 +1,7 @@
+#macro(info $title, $message)
+<div markdown="span" class="alert alert-info" role="alert">
+    <i class="fa fa-info-circle"></i>
+    <b>${title}</b><br/>
+    ${message}
+</div>
+#end
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/shiro-site/blob/ddea166c/templates/macros/lend-a-hand.vtl
----------------------------------------------------------------------
diff --git a/templates/macros/lend-a-hand.vtl b/templates/macros/lend-a-hand.vtl
new file mode 100644
index 0000000..f734534
--- /dev/null
+++ b/templates/macros/lend-a-hand.vtl
@@ -0,0 +1,9 @@
+#macro(todoAddDoc)
+<p>TODO</p>
+
+<h2><a name="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>
+#end
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/shiro-site/blob/ddea166c/templates/macros/redirect.vtl
----------------------------------------------------------------------
diff --git a/templates/macros/redirect.vtl b/templates/macros/redirect.vtl
new file mode 100644
index 0000000..08e0fda
--- /dev/null
+++ b/templates/macros/redirect.vtl
@@ -0,0 +1,11 @@
+#macro(redirect $newHref, $title)
+<p>This page has been moved.  You are being redirected.</p>
+
+#warning('Redirection Notice', "This page should redirect to <a href=""$newHref"" title=""$title"">$title</a>.")
+
+<script type="text/javascript">
+    <!--
+    window.location = "$newHref"
+    //-->
+</script>
+#end
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/shiro-site/blob/ddea166c/templates/macros/tip.vtl
----------------------------------------------------------------------
diff --git a/templates/macros/tip.vtl b/templates/macros/tip.vtl
new file mode 100644
index 0000000..e8046ad
--- /dev/null
+++ b/templates/macros/tip.vtl
@@ -0,0 +1,7 @@
+#macro(tip $title, $message)
+<div markdown="span" class="alert alert-success" role="alert">
+    <i class="fa fa-check-square-o"></i>
+    <b>${title}</b><br/>
+    ${message}
+</div>
+#end
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/shiro-site/blob/ddea166c/templates/macros/warning.vtl
----------------------------------------------------------------------
diff --git a/templates/macros/warning.vtl b/templates/macros/warning.vtl
new file mode 100644
index 0000000..7fb4310
--- /dev/null
+++ b/templates/macros/warning.vtl
@@ -0,0 +1,7 @@
+#macro(warning $title, $message)
+<div markdown="span" class="alert alert-warning" role="alert">
+    <i class="fa fa-warning"></i>
+    <b>${title}</b><br/>
+    ${message}
+</div>
+#end
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/shiro-site/blob/ddea166c/testing.html
----------------------------------------------------------------------
diff --git a/testing.html b/testing.html
deleted file mode 100644
index 33fa61e..0000000
--- a/testing.html
+++ /dev/null
@@ -1,241 +0,0 @@
-<h1><a name="Testing-TestingwithApacheShiro"></a>Testing with Apache Shiro</h1>
-
-<p>This part of the documentation explains how to enable Shiro in unit tests.</p>
-
-<h2><a name="Testing-Whattoknowfortests"></a>What to know for tests</h2>
-
-<p>As we've already covered in the <a href="subject.html" title="Subject">Subject reference</a>, we know that a Subject is security-specific view of the 'currently executing' user, and that Subject instances are always bound to a thread to ensure we know <em>who</em> is executing logic at any time during the thread's execution.</p>
-
-<p>This means three basic things must always occur in order to support being able to access the currently executing Subject:</p>
-
-<ol><li>A <tt>Subject</tt> instance must be created</li><li>The <tt>Subject</tt> instance must be <em>bound</em> to the currently executing thread.</li><li>After the thread is finished executing (or if the thread's execution results in a <tt>Throwable</tt>), the <tt>Subject</tt> must be <em>unbound</em> to ensure that the thread remains 'clean' in any thread-pooled environment.</li></ol>
-
-
-<p>Shiro has architectural components that perform this bind/unbind logic automatically for a running application.  For example, in a web application, the root Shiro Filter performs this logic when <a class="external-link" href="static/current/apidocs/org/apache/shiro/web/servlet/AbstractShiroFilter.html#doFilterInternal(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)">filtering a request</a>.  But as test environments and frameworks differ, we need to perform this bind/unbind logic ourselves for our chosen test framework.</p>
-
-<h2><a name="Testing-TestSetup"></a>Test Setup</h2>
-
-<p>So we know after creating a <tt>Subject</tt> instance, it must be <em>bound</em> to thread.  After the thread (or in this case, a test) is finished executing, we must <em>unbind</em> the Subject to keep the thread 'clean'.</p>
-
-<p>Luckily enough, modern test frameworks like JUnit and TestNG natively support this notion of 'setup' and 'teardown' already.  We can leverage this support to simulate what Shiro would do in a 'complete' application.  We've created a base abstract class that you can use in your own testing below - feel free to copy and/or modify as you see fit.  It can be used in both unit testing and integration testing (we're using JUnit in this example, but TestNG works just as well):</p>
-
-<h3><a name="Testing-AbstractShiroTest"></a>AbstractShiroTest</h3>
-
-<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.SecurityUtils;
-<span class="code-keyword">import</span> org.apache.shiro.UnavailableSecurityManagerException;
-<span class="code-keyword">import</span> org.apache.shiro.mgt.<span class="code-object">SecurityManager</span>;
-<span class="code-keyword">import</span> org.apache.shiro.subject.Subject;
-<span class="code-keyword">import</span> org.apache.shiro.subject.support.SubjectThreadState;
-<span class="code-keyword">import</span> org.apache.shiro.util.LifecycleUtils;
-<span class="code-keyword">import</span> org.apache.shiro.util.ThreadState;
-<span class="code-keyword">import</span> org.junit.AfterClass;
-
-/**
- * Abstract test <span class="code-keyword">case</span> enabling Shiro in test environments.
- */
-<span class="code-keyword">public</span> <span class="code-keyword">abstract</span> class AbstractShiroTest {
-
-    <span class="code-keyword">private</span> <span class="code-keyword">static</span> ThreadState subjectThreadState;
-
-    <span class="code-keyword">public</span> AbstractShiroTest() {
-    }
-
-    /**
-     * Allows subclasses to set the currently executing {@link Subject} instance.
-     *
-     * @param subject the Subject instance
-     */
-    <span class="code-keyword">protected</span> void setSubject(Subject subject) {
-        clearSubject();
-        subjectThreadState = createThreadState(subject);
-        subjectThreadState.bind();
-    }
-
-    <span class="code-keyword">protected</span> Subject getSubject() {
-        <span class="code-keyword">return</span> SecurityUtils.getSubject();
-    }
-
-    <span class="code-keyword">protected</span> ThreadState createThreadState(Subject subject) {
-        <span class="code-keyword">return</span> <span class="code-keyword">new</span> SubjectThreadState(subject);
-    }
-
-    /**
-     * Clears Shiro's thread state, ensuring the thread remains clean <span class="code-keyword">for</span> <span class="code-keyword">future</span> test execution.
-     */
-    <span class="code-keyword">protected</span> void clearSubject() {
-        doClearSubject();
-    }
-
-    <span class="code-keyword">private</span> <span class="code-keyword">static</span> void doClearSubject() {
-        <span class="code-keyword">if</span> (subjectThreadState != <span class="code-keyword">null</span>) {
-            subjectThreadState.clear();
-            subjectThreadState = <span class="code-keyword">null</span>;
-        }
-    }
-
-    <span class="code-keyword">protected</span> <span class="code-keyword">static</span> void setSecurityManager(<span class="code-object">SecurityManager</span> securityManager) {
-        SecurityUtils.setSecurityManager(securityManager);
-    }
-
-    <span class="code-keyword">protected</span> <span class="code-keyword">static</span> <span class="code-object">SecurityManager</span> getSecurityManager() {
-        <span class="code-keyword">return</span> SecurityUtils.getSecurityManager();
-    }
-
-    @AfterClass
-    <span class="code-keyword">public</span> <span class="code-keyword">static</span> void tearDownShiro() {
-        doClearSubject();
-        <span class="code-keyword">try</span> {
-            <span class="code-object">SecurityManager</span> securityManager = getSecurityManager();
-            LifecycleUtils.destroy(securityManager);
-        } <span class="code-keyword">catch</span> (UnavailableSecurityManagerException e) {
-            <span class="code-comment">//we don't care about <span class="code-keyword">this</span> when cleaning up the test environment
-</span>            <span class="code-comment">//(<span class="code-keyword">for</span> example, maybe the subclass is a unit test and it didn't
-</span>            <span class="code-comment">// need a <span class="code-object">SecurityManager</span> instance because it was using only 
-</span>            <span class="code-comment">// mock Subject instances)
-</span>        }
-        setSecurityManager(<span class="code-keyword">null</span>);
-    }
-}
-</pre>
-</div></div>
-
-<div class="panelMacro"><table class="noteMacro"><colgroup span="1"><col span="1" width="24"><col span="1"></colgroup><tr><td colspan="1" rowspan="1" valign="top"><img align="middle" src="https://cwiki.apache.org/confluence/images/icons/emoticons/warning.gif" width="16" height="16" alt="" border="0"></td><td colspan="1" rowspan="1"><b>Testing &amp; Frameworks</b><br clear="none">The code in the <tt>AbstractShiroTest</tt> class uses Shiro's <tt>ThreadState</tt> concept and a static SecurityManager.  These techniques are useful in tests and in framework code, but rarely ever used in application code.  
-
-<p>Most end-users working with Shiro who need to ensure thread-state consistency will almost always use Shiro's automatic management mechanisms, namely the <tt>Subject.associateWith</tt> and the <tt>Subject.execute</tt> methods.  These methods are covered in the reference on <a href="subject.html#Subject-ThreadAssociation">Subject thread association</a>.</p></td></tr></table></div>
-
-<h2><a name="Testing-UnitTesting"></a>Unit Testing</h2>
-
-<p>Unit testing is mostly about testing your code and only your code in a limited scope.  When you take Shiro into account, what you really want to focus on is that your code works correctly with Shiro's <em>API</em> - you don't want to necessarily test that Shiro's implementation is working correctly (that's something that the Shiro development team must ensure in Shiro's code base).</p>
-
-<p>Testing to see if Shiro's implementations work in conjunction with your implementations is really integration testing (discussed below).</p>
-
-<h3><a name="Testing-ExampleShiroUnitTest"></a>ExampleShiroUnitTest</h3>
-
-<p>Because unit tests are better suited for testing your own logic (and not any implementations your logic might call), it is a great idea to <em>mock</em> any APIs that your logic depends on.  This works very well with Shiro - you can mock the <tt>Subject</tt> interface and have it reflect whatever conditions you want your code under test to react to.  We can leverage modern mock frameworks like <a class="external-link" href="http://easymock.org/" rel="nofollow">EasyMock</a> and <a class="external-link" href="http://mockito.org/" rel="nofollow">Mockito</a> to do this for us.  </p>
-
-<p>But as stated above, the key in Shiro tests is to remember that any Subject instance (mock or real) must be bound to the thread during test execution.  So all we need to do is bind the mock Subject to ensure things work as expected.</p>
-
-<p>(this example uses EasyMock, but Mockito works equally as well):</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.subject.Subject;
-<span class="code-keyword">import</span> org.junit.After;
-<span class="code-keyword">import</span> org.junit.Test;
-
-<span class="code-keyword">import</span> <span class="code-keyword">static</span> org.easymock.EasyMock.*;
-
-/**
- * Simple example test class showing how one may perform unit tests <span class="code-keyword">for</span> code that requires Shiro APIs.
- */
-<span class="code-keyword">public</span> class ExampleShiroUnitTest <span class="code-keyword">extends</span> AbstractShiroTest {
-
-    @Test
-    <span class="code-keyword">public</span> void testSimple() {
-
-        <span class="code-comment">//1.  Create a mock authenticated Subject instance <span class="code-keyword">for</span> the test to run:
-</span>        Subject subjectUnderTest = createNiceMock(Subject.class);
-        expect(subjectUnderTest.isAuthenticated()).andReturn(<span class="code-keyword">true</span>);
-
-        <span class="code-comment">//2. Bind the subject to the current thread:
-</span>        setSubject(subjectUnderTest);
-
-        <span class="code-comment">//perform test logic here.  Any call to 
-</span>        <span class="code-comment">//SecurityUtils.getSubject() directly (or nested in the 
-</span>        <span class="code-comment">//call stack) will work properly.
-</span>    }
-
-    @After
-    <span class="code-keyword">public</span> void tearDownSubject() {
-        <span class="code-comment">//3. Unbind the subject from the current thread:
-</span>        clearSubject();
-    }
-
-}
-</pre>
-</div></div>
-
-<p>As you can see, we're not setting up a Shiro <tt>SecurityManager</tt> instance or configuring a <tt>Realm</tt> or anything like that.  We're simply creating a mock <tt>Subject</tt> instance and binding it to the thread via the <tt>setSubject</tt> method call.  This will ensure that any calls in our test code or in the code we're testing to <tt>SecurityUtils.getSubject()</tt> will work correctly.</p>
-
-<p>Note that the <tt>setSubject</tt> method implementation will bind your mock Subject to the thread and it will remain there until you call <tt>setSubject</tt> with a different <tt>Subject</tt> instance or until you explicitly clear it from the thread via the <tt>clearSubject()</tt> call.</p>
-
-<p>How long you keep the subject bound to the thread (or swap it out for a new instance in a different test) is up to you and your testing requirements.  </p>
-
-<h4><a name="Testing-tearDownSubject%28%29"></a>tearDownSubject()</h4>
-
-<p>The <tt>tearDownSubject()</tt> method in the example uses a Junit 4 annotation to ensure that the Subject is cleared from the thread after every test method is executed, no matter what.  This requires you to set up a new <tt>Subject</tt> instance and set it (via <tt>setSubject</tt>) for every test that executes.</p>
-
-<p>This is not strictly necessary however.  For example, you could just bind a new Subject instance (via <tt>setSujbect</tt>) at the beginning of every test, say, in an <tt>@Before</tt>-annotated method.  But if you're going to do that, you might as well have the <tt>@After tearDownSubject()</tt> method to keep things symmetrical and 'clean'.</p>
-
-<p>You can mix and match this setup/teardown logic in each method manually or use the @Before and @After annotations as you see fit.  The <tt>AbstractShiroTest</tt> super class will however unbind the Subject from the thread after all tests because of the <tt>@AfterClass</tt> annotation in its <tt>tearDownShiro()</tt> method.</p>
-
-<h2><a name="Testing-IntegrationTesting"></a>Integration Testing</h2>
-
-<p>Now that we've covered unit test setup, let's talk a bit about integration testing.  Integration testing is testing implementations across API boundaries.  For example, testing that implementation A works when calling implementation B and that implementation B does what it is supposed to.</p>
-
-<p>You can easily perform integration testing in Shiro as well.  Shiro's <tt>SecurityManager</tt> instance and things it wraps (like Realms and SessionManager, etc) are all very lightweight POJOs that use very little memory.  This means you can create and tear down a <tt>SecurityManager</tt> instance for every test class you execute.  When your integration tests run, they will be using 'real' <tt>SecurityManager</tt> and <tt>Subject</tt> instances like your application will be using at runtime.</p>
-
-<h3><a name="Testing-ExampleShiroIntegrationTest"></a>ExampleShiroIntegrationTest</h3>
-
-<p>The example code below looks almost identical to the Unit Test example above, but the 3 step process is slightly different:</p>
-
-<ol><li>There is now a step '0', which sets up a 'real' SecurityManager instance.</li><li>Step 1 now constructs a 'real' Subject instance with the <tt>Subject.Builder</tt> and binds it to the thread.</li></ol>
-
-
-<p>Thread binding and unbinding (steps 2 and 3) function the same as the Unit Test example.</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.config.IniSecurityManagerFactory;
-<span class="code-keyword">import</span> org.apache.shiro.mgt.<span class="code-object">SecurityManager</span>;
-<span class="code-keyword">import</span> org.apache.shiro.subject.Subject;
-<span class="code-keyword">import</span> org.apache.shiro.util.Factory;
-<span class="code-keyword">import</span> org.junit.After;
-<span class="code-keyword">import</span> org.junit.BeforeClass;
-<span class="code-keyword">import</span> org.junit.Test;
-
-<span class="code-keyword">public</span> class ExampleShiroIntegrationTest <span class="code-keyword">extends</span> AbstractShiroTest {
-
-    @BeforeClass
-    <span class="code-keyword">public</span> <span class="code-keyword">static</span> void beforeClass() {
-        <span class="code-comment">//0.  Build and set the <span class="code-object">SecurityManager</span> used to build Subject instances used in your tests
-</span>        <span class="code-comment">//    This typically only needs to be done once per class <span class="code-keyword">if</span> your shiro.ini doesn't change,
-</span>        <span class="code-comment">//    otherwise, you'll need to <span class="code-keyword">do</span> <span class="code-keyword">this</span> logic in each test that is different
-</span>        Factory&lt;<span class="code-object">SecurityManager</span>&gt; factory = <span class="code-keyword">new</span> IniSecurityManagerFactory(<span class="code-quote">"classpath:test.shiro.ini"</span>);
-        setSecurityManager(factory.getInstance());
-    }
-
-    @Test
-    <span class="code-keyword">public</span> void testSimple() {
-        <span class="code-comment">//1.  Build the Subject instance <span class="code-keyword">for</span> the test to run:
-</span>        Subject subjectUnderTest = <span class="code-keyword">new</span> Subject.Builder(getSecurityManager()).buildSubject();
-
-        <span class="code-comment">//2. Bind the subject to the current thread:
-</span>        setSubject(subjectUnderTest);
-
-        <span class="code-comment">//perform test logic here.  Any call to 
-</span>        <span class="code-comment">//SecurityUtils.getSubject() directly (or nested in the 
-</span>        <span class="code-comment">//call stack) will work properly.
-</span>    }
-
-    @AfterClass
-    <span class="code-keyword">public</span> void tearDownSubject() {
-        <span class="code-comment">//3. Unbind the subject from the current thread:
-</span>        clearSubject();
-    }
-}
-</pre>
-</div></div>
-
-<p>As you can see, a concrete <tt>SecurityManager</tt> implementation is instantiated and made accessible for the remainder of the test via the <tt>setSecurityManager</tt> method.  Test methods can then use this <tt>SecurityManager</tt> when using the <tt>Subject.Builder</tt> later via the <tt>getSecurityManager()</tt> method.</p>
-
-<p>Also note that the <tt>SecurityManager</tt> instance is set up once in a <tt>@BeforeClass</tt> setup method - a fairly common practice for most test classes.  But if you wanted to, you could create a new <tt>SecurityManager</tt> instance and set it via <tt>setSecurityManager</tt> at any time from any test method - for example, you might reference two different .ini files to build a new <tt>SecurityManager</tt> depending on your test requirements.  </p>
-
-<p>Finally, just as with the Unit Test example, the <tt>AbstractShiroTest</tt> super class will clean up all Shiro artifacts (any remaining <tt>SecurityManager</tt> and <tt>Subject</tt> instance) via its <tt>@AfterClass tearDownShiro()</tt> method to ensure the thread is 'clean' for the next test class to run.</p>
-
-<h2><a name="Testing-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>

http://git-wip-us.apache.org/repos/asf/shiro-site/blob/ddea166c/testing.html.vtl
----------------------------------------------------------------------
diff --git a/testing.html.vtl b/testing.html.vtl
new file mode 100644
index 0000000..a186294
--- /dev/null
+++ b/testing.html.vtl
@@ -0,0 +1,240 @@
+<h1><a name="Testing-TestingwithApacheShiro"></a>Testing with Apache Shiro</h1>
+
+<p>This part of the documentation explains how to enable Shiro in unit tests.</p>
+
+<h2><a name="Testing-Whattoknowfortests"></a>What to know for tests</h2>
+
+<p>As we've already covered in the <a href="subject.html" title="Subject">Subject reference</a>, we know that a Subject is security-specific view of the 'currently executing' user, and that Subject instances are always bound to a thread to ensure we know <em>who</em> is executing logic at any time during the thread's execution.</p>
+
+<p>This means three basic things must always occur in order to support being able to access the currently executing Subject:</p>
+
+<ol><li>A <tt>Subject</tt> instance must be created</li><li>The <tt>Subject</tt> instance must be <em>bound</em> to the currently executing thread.</li><li>After the thread is finished executing (or if the thread's execution results in a <tt>Throwable</tt>), the <tt>Subject</tt> must be <em>unbound</em> to ensure that the thread remains 'clean' in any thread-pooled environment.</li></ol>
+
+
+<p>Shiro has architectural components that perform this bind/unbind logic automatically for a running application.  For example, in a web application, the root Shiro Filter performs this logic when <a class="external-link" href="static/current/apidocs/org/apache/shiro/web/servlet/AbstractShiroFilter.html\#doFilterInternal(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)">filtering a request</a>.  But as test environments and frameworks differ, we need to perform this bind/unbind logic ourselves for our chosen test framework.</p>
+
+<h2><a name="Testing-TestSetup"></a>Test Setup</h2>
+
+<p>So we know after creating a <tt>Subject</tt> instance, it must be <em>bound</em> to thread.  After the thread (or in this case, a test) is finished executing, we must <em>unbind</em> the Subject to keep the thread 'clean'.</p>
+
+<p>Luckily enough, modern test frameworks like JUnit and TestNG natively support this notion of 'setup' and 'teardown' already.  We can leverage this support to simulate what Shiro would do in a 'complete' application.  We've created a base abstract class that you can use in your own testing below - feel free to copy and/or modify as you see fit.  It can be used in both unit testing and integration testing (we're using JUnit in this example, but TestNG works just as well):</p>
+
+<h3><a name="Testing-AbstractShiroTest"></a>AbstractShiroTest</h3>
+
+<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.SecurityUtils;
+<span class="code-keyword">import</span> org.apache.shiro.UnavailableSecurityManagerException;
+<span class="code-keyword">import</span> org.apache.shiro.mgt.<span class="code-object">SecurityManager</span>;
+<span class="code-keyword">import</span> org.apache.shiro.subject.Subject;
+<span class="code-keyword">import</span> org.apache.shiro.subject.support.SubjectThreadState;
+<span class="code-keyword">import</span> org.apache.shiro.util.LifecycleUtils;
+<span class="code-keyword">import</span> org.apache.shiro.util.ThreadState;
+<span class="code-keyword">import</span> org.junit.AfterClass;
+
+/**
+ * Abstract test <span class="code-keyword">case</span> enabling Shiro in test environments.
+ */
+<span class="code-keyword">public</span> <span class="code-keyword">abstract</span> class AbstractShiroTest {
+
+    <span class="code-keyword">private</span> <span class="code-keyword">static</span> ThreadState subjectThreadState;
+
+    <span class="code-keyword">public</span> AbstractShiroTest() {
+    }
+
+    /**
+     * Allows subclasses to set the currently executing {@link Subject} instance.
+     *
+     * @param subject the Subject instance
+     */
+    <span class="code-keyword">protected</span> void setSubject(Subject subject) {
+        clearSubject();
+        subjectThreadState = createThreadState(subject);
+        subjectThreadState.bind();
+    }
+
+    <span class="code-keyword">protected</span> Subject getSubject() {
+        <span class="code-keyword">return</span> SecurityUtils.getSubject();
+    }
+
+    <span class="code-keyword">protected</span> ThreadState createThreadState(Subject subject) {
+        <span class="code-keyword">return</span> <span class="code-keyword">new</span> SubjectThreadState(subject);
+    }
+
+    /**
+     * Clears Shiro's thread state, ensuring the thread remains clean <span class="code-keyword">for</span> <span class="code-keyword">future</span> test execution.
+     */
+    <span class="code-keyword">protected</span> void clearSubject() {
+        doClearSubject();
+    }
+
+    <span class="code-keyword">private</span> <span class="code-keyword">static</span> void doClearSubject() {
+        <span class="code-keyword">if</span> (subjectThreadState != <span class="code-keyword">null</span>) {
+            subjectThreadState.clear();
+            subjectThreadState = <span class="code-keyword">null</span>;
+        }
+    }
+
+    <span class="code-keyword">protected</span> <span class="code-keyword">static</span> void setSecurityManager(<span class="code-object">SecurityManager</span> securityManager) {
+        SecurityUtils.setSecurityManager(securityManager);
+    }
+
+    <span class="code-keyword">protected</span> <span class="code-keyword">static</span> <span class="code-object">SecurityManager</span> getSecurityManager() {
+        <span class="code-keyword">return</span> SecurityUtils.getSecurityManager();
+    }
+
+    @AfterClass
+    <span class="code-keyword">public</span> <span class="code-keyword">static</span> void tearDownShiro() {
+        doClearSubject();
+        <span class="code-keyword">try</span> {
+            <span class="code-object">SecurityManager</span> securityManager = getSecurityManager();
+            LifecycleUtils.destroy(securityManager);
+        } <span class="code-keyword">catch</span> (UnavailableSecurityManagerException e) {
+            <span class="code-comment">//we don't care about <span class="code-keyword">this</span> when cleaning up the test environment
+</span>            <span class="code-comment">//(<span class="code-keyword">for</span> example, maybe the subclass is a unit test and it didn't
+</span>            <span class="code-comment">// need a <span class="code-object">SecurityManager</span> instance because it was using only 
+</span>            <span class="code-comment">// mock Subject instances)
+</span>        }
+        setSecurityManager(<span class="code-keyword">null</span>);
+    }
+}
+</pre>
+</div></div>
+
+#warning('Testing &amp; Frameworks', 'The code in the <tt>AbstractShiroTest</tt> class uses Shiro''s <tt>ThreadState</tt> concept and a static SecurityManager.  These techniques are useful in tests and in framework code, but rarely ever used in application code.
+<p>Most end-users working with Shiro who need to ensure thread-state consistency will almost always use Shiro''s automatic management mechanisms, namely the <tt>Subject.associateWith</tt> and the <tt>Subject.execute</tt> methods.  These methods are covered in the reference on <a href="subject.html\#Subject-ThreadAssociation">Subject thread association</a>.</p>')
+
+<h2><a name="Testing-UnitTesting"></a>Unit Testing</h2>
+
+<p>Unit testing is mostly about testing your code and only your code in a limited scope.  When you take Shiro into account, what you really want to focus on is that your code works correctly with Shiro's <em>API</em> - you don't want to necessarily test that Shiro's implementation is working correctly (that's something that the Shiro development team must ensure in Shiro's code base).</p>
+
+<p>Testing to see if Shiro's implementations work in conjunction with your implementations is really integration testing (discussed below).</p>
+
+<h3><a name="Testing-ExampleShiroUnitTest"></a>ExampleShiroUnitTest</h3>
+
+<p>Because unit tests are better suited for testing your own logic (and not any implementations your logic might call), it is a great idea to <em>mock</em> any APIs that your logic depends on.  This works very well with Shiro - you can mock the <tt>Subject</tt> interface and have it reflect whatever conditions you want your code under test to react to.  We can leverage modern mock frameworks like <a class="external-link" href="http://easymock.org/" rel="nofollow">EasyMock</a> and <a class="external-link" href="http://mockito.org/" rel="nofollow">Mockito</a> to do this for us.  </p>
+
+<p>But as stated above, the key in Shiro tests is to remember that any Subject instance (mock or real) must be bound to the thread during test execution.  So all we need to do is bind the mock Subject to ensure things work as expected.</p>
+
+<p>(this example uses EasyMock, but Mockito works equally as well):</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.subject.Subject;
+<span class="code-keyword">import</span> org.junit.After;
+<span class="code-keyword">import</span> org.junit.Test;
+
+<span class="code-keyword">import</span> <span class="code-keyword">static</span> org.easymock.EasyMock.*;
+
+/**
+ * Simple example test class showing how one may perform unit tests <span class="code-keyword">for</span> code that requires Shiro APIs.
+ */
+<span class="code-keyword">public</span> class ExampleShiroUnitTest <span class="code-keyword">extends</span> AbstractShiroTest {
+
+    @Test
+    <span class="code-keyword">public</span> void testSimple() {
+
+        <span class="code-comment">//1.  Create a mock authenticated Subject instance <span class="code-keyword">for</span> the test to run:
+</span>        Subject subjectUnderTest = createNiceMock(Subject.class);
+        expect(subjectUnderTest.isAuthenticated()).andReturn(<span class="code-keyword">true</span>);
+
+        <span class="code-comment">//2. Bind the subject to the current thread:
+</span>        setSubject(subjectUnderTest);
+
+        <span class="code-comment">//perform test logic here.  Any call to 
+</span>        <span class="code-comment">//SecurityUtils.getSubject() directly (or nested in the 
+</span>        <span class="code-comment">//call stack) will work properly.
+</span>    }
+
+    @After
+    <span class="code-keyword">public</span> void tearDownSubject() {
+        <span class="code-comment">//3. Unbind the subject from the current thread:
+</span>        clearSubject();
+    }
+
+}
+</pre>
+</div></div>
+
+<p>As you can see, we're not setting up a Shiro <tt>SecurityManager</tt> instance or configuring a <tt>Realm</tt> or anything like that.  We're simply creating a mock <tt>Subject</tt> instance and binding it to the thread via the <tt>setSubject</tt> method call.  This will ensure that any calls in our test code or in the code we're testing to <tt>SecurityUtils.getSubject()</tt> will work correctly.</p>
+
+<p>Note that the <tt>setSubject</tt> method implementation will bind your mock Subject to the thread and it will remain there until you call <tt>setSubject</tt> with a different <tt>Subject</tt> instance or until you explicitly clear it from the thread via the <tt>clearSubject()</tt> call.</p>
+
+<p>How long you keep the subject bound to the thread (or swap it out for a new instance in a different test) is up to you and your testing requirements.  </p>
+
+<h4><a name="Testing-tearDownSubject%28%29"></a>tearDownSubject()</h4>
+
+<p>The <tt>tearDownSubject()</tt> method in the example uses a Junit 4 annotation to ensure that the Subject is cleared from the thread after every test method is executed, no matter what.  This requires you to set up a new <tt>Subject</tt> instance and set it (via <tt>setSubject</tt>) for every test that executes.</p>
+
+<p>This is not strictly necessary however.  For example, you could just bind a new Subject instance (via <tt>setSujbect</tt>) at the beginning of every test, say, in an <tt>@Before</tt>-annotated method.  But if you're going to do that, you might as well have the <tt>@After tearDownSubject()</tt> method to keep things symmetrical and 'clean'.</p>
+
+<p>You can mix and match this setup/teardown logic in each method manually or use the @Before and @After annotations as you see fit.  The <tt>AbstractShiroTest</tt> super class will however unbind the Subject from the thread after all tests because of the <tt>@AfterClass</tt> annotation in its <tt>tearDownShiro()</tt> method.</p>
+
+<h2><a name="Testing-IntegrationTesting"></a>Integration Testing</h2>
+
+<p>Now that we've covered unit test setup, let's talk a bit about integration testing.  Integration testing is testing implementations across API boundaries.  For example, testing that implementation A works when calling implementation B and that implementation B does what it is supposed to.</p>
+
+<p>You can easily perform integration testing in Shiro as well.  Shiro's <tt>SecurityManager</tt> instance and things it wraps (like Realms and SessionManager, etc) are all very lightweight POJOs that use very little memory.  This means you can create and tear down a <tt>SecurityManager</tt> instance for every test class you execute.  When your integration tests run, they will be using 'real' <tt>SecurityManager</tt> and <tt>Subject</tt> instances like your application will be using at runtime.</p>
+
+<h3><a name="Testing-ExampleShiroIntegrationTest"></a>ExampleShiroIntegrationTest</h3>
+
+<p>The example code below looks almost identical to the Unit Test example above, but the 3 step process is slightly different:</p>
+
+<ol><li>There is now a step '0', which sets up a 'real' SecurityManager instance.</li><li>Step 1 now constructs a 'real' Subject instance with the <tt>Subject.Builder</tt> and binds it to the thread.</li></ol>
+
+
+<p>Thread binding and unbinding (steps 2 and 3) function the same as the Unit Test example.</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.config.IniSecurityManagerFactory;
+<span class="code-keyword">import</span> org.apache.shiro.mgt.<span class="code-object">SecurityManager</span>;
+<span class="code-keyword">import</span> org.apache.shiro.subject.Subject;
+<span class="code-keyword">import</span> org.apache.shiro.util.Factory;
+<span class="code-keyword">import</span> org.junit.After;
+<span class="code-keyword">import</span> org.junit.BeforeClass;
+<span class="code-keyword">import</span> org.junit.Test;
+
+<span class="code-keyword">public</span> class ExampleShiroIntegrationTest <span class="code-keyword">extends</span> AbstractShiroTest {
+
+    @BeforeClass
+    <span class="code-keyword">public</span> <span class="code-keyword">static</span> void beforeClass() {
+        <span class="code-comment">//0.  Build and set the <span class="code-object">SecurityManager</span> used to build Subject instances used in your tests
+</span>        <span class="code-comment">//    This typically only needs to be done once per class <span class="code-keyword">if</span> your shiro.ini doesn't change,
+</span>        <span class="code-comment">//    otherwise, you'll need to <span class="code-keyword">do</span> <span class="code-keyword">this</span> logic in each test that is different
+</span>        Factory&lt;<span class="code-object">SecurityManager</span>&gt; factory = <span class="code-keyword">new</span> IniSecurityManagerFactory(<span class="code-quote">"classpath:test.shiro.ini"</span>);
+        setSecurityManager(factory.getInstance());
+    }
+
+    @Test
+    <span class="code-keyword">public</span> void testSimple() {
+        <span class="code-comment">//1.  Build the Subject instance <span class="code-keyword">for</span> the test to run:
+</span>        Subject subjectUnderTest = <span class="code-keyword">new</span> Subject.Builder(getSecurityManager()).buildSubject();
+
+        <span class="code-comment">//2. Bind the subject to the current thread:
+</span>        setSubject(subjectUnderTest);
+
+        <span class="code-comment">//perform test logic here.  Any call to 
+</span>        <span class="code-comment">//SecurityUtils.getSubject() directly (or nested in the 
+</span>        <span class="code-comment">//call stack) will work properly.
+</span>    }
+
+    @AfterClass
+    <span class="code-keyword">public</span> void tearDownSubject() {
+        <span class="code-comment">//3. Unbind the subject from the current thread:
+</span>        clearSubject();
+    }
+}
+</pre>
+</div></div>
+
+<p>As you can see, a concrete <tt>SecurityManager</tt> implementation is instantiated and made accessible for the remainder of the test via the <tt>setSecurityManager</tt> method.  Test methods can then use this <tt>SecurityManager</tt> when using the <tt>Subject.Builder</tt> later via the <tt>getSecurityManager()</tt> method.</p>
+
+<p>Also note that the <tt>SecurityManager</tt> instance is set up once in a <tt>@BeforeClass</tt> setup method - a fairly common practice for most test classes.  But if you wanted to, you could create a new <tt>SecurityManager</tt> instance and set it via <tt>setSecurityManager</tt> at any time from any test method - for example, you might reference two different .ini files to build a new <tt>SecurityManager</tt> depending on your test requirements.  </p>
+
+<p>Finally, just as with the Unit Test example, the <tt>AbstractShiroTest</tt> super class will clean up all Shiro artifacts (any remaining <tt>SecurityManager</tt> and <tt>Subject</tt> instance) via its <tt>@AfterClass tearDownShiro()</tt> method to ensure the thread is 'clean' for the next test class to run.</p>
+
+<h2><a name="Testing-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>


Mime
View raw message