blob: de022470e373c6df8abc429fbf4326dab76186b1 [file] [log] [blame]
<h1><a name="Tutorial-ApacheShiroTutorial"></a>Apache Shiro Tutorial</h1>
<table align="right" width="275" style="margin-left: 20px; margin-bottom: 20px; border-style: solid; border-width: 2px; border-color: navy" cellpadding="10px">
<tr>
<td>
<div id="border">
<h2>Related Content</h2>
<h3><a href="get-started.html">Getting Started</a></h3>
<p>Resources, guides and tutorials for new Shiro users. </br><span style="font-size:11"><a href="get-started.html">Read More &gt;&gt;</a></span></p>
<h3><a href="10-minute-tutorial.html">10-Minute Shiro Tutorial</a></h3>
<p>Try Apache Shiro for yourself in under 10 minutes. </br><span style="font-size:11"><a href="10-minute-tutorial.html">Read More &gt;&gt;</a></span></p>
<h3><a href="webapp-tutorial.html">Web App Tutorial</a></h3>
<p>Step-by-step tutorial for securing a web application with Shiro. </br><span style="font-size:11"><a href="webapp-tutorial.html">Read More &gt;&gt;</a></span></p>
</div>
</td>
</tr>
</table>
<h2><a name="Tutorial-YourFirstApacheShiroApplication"></a>Your First Apache Shiro Application</h2>
<p>If you're new to Apache Shiro, this short tutorial will show you how to set up an initial and very simple application secured by Apache Shiro. We'll discuss Shiro's core concepts along the way to help familiarize you with Shiro's design and API.</p>
<p>If you don't want to actually edit files as you follow this tutorial, you can obtain a nearly identical sample application and reference it as you go. Choose a location:</p>
<ul><li>In Apache Shiro's Git repository: <a class="external-link" href="https://github.com/apache/shiro/tree/master/samples/quickstart">https://github.com/apache/shiro/tree/master/samples/quickstart</a></li><li>In Apache Shiro's source distribution's <tt>samples/quickstart</tt> directory. The source distribution is available from the <a href="download.html" title="Download">Download</a> page.</li></ul>
<h3><a name="Tutorial-Setup"></a>Setup</h3>
<p>In this simple example, we'll create a very simple command-line application that will run and quickly exit, just so you can get a feel for Shiro's API.</p>
<div class="panelMacro"><table class="infoMacro"><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/information.gif" width="16" height="16" alt="" border="0"></td><td colspan="1" rowspan="1"><b>Any Application</b><br clear="none">Apache Shiro was designed from day one to support <em>any</em> application - from the smallest command-line applications to the largest clustered web applications. Even though we're creating a simple app for this tutorial, know that the same usage patterns apply no matter how your application is created or where it is deployed.</td></tr></table></div>
<p>This tutorial requires Java 1.5 or later. We'll also be using Apache <a class="external-link" href="http://maven.apache.org">Maven</a> as our build tool, but of course this is not required to use Apache Shiro. You may acquire Shiro's .jars and incorporate them in any way you like into your application, for example maybe using Apache <a class="external-link" href="http://ant.apache.org">Ant</a> and <a class="external-link" href="http://ant.apache.org/ivy">Ivy</a>.</p>
<p>For this tutorial, please ensure that you are using Maven 2.2.1 or later. You should be able to type <tt>mvn --version</tt> in a command prompt and see something similar to the following:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeHeader panelHeader" style="border-bottom-width: 1px;"><b>Testing Maven Installation</b></div><div class="codeContent panelContent">
<pre class="code-java">
hazlewood:~/shiro-tutorial$ mvn --version
Apache Maven 2.2.1 (r801777; 2009-08-06 12:16:01-0700)
Java version: 1.6.0_24
Java home: /<span class="code-object">System</span>/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Default locale: en_US, platform encoding: MacRoman
OS name: <span class="code-quote">"mac os x"</span> version: <span class="code-quote">"10.6.7"</span> arch: <span class="code-quote">"x86_64"</span> Family: <span class="code-quote">"mac"</span>
</pre>
</div></div>
<p>For now, create a new directory on your filesystem, for example, <b><tt>shiro-tutorial</tt></b> and save the following Maven <b><tt>pom.xml</tt></b> file in that directory:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeHeader panelHeader" style="border-bottom-width: 1px;"><b>pom.xml</b></div><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;?xml version=<span class="code-quote">"1.0"</span> encoding=<span class="code-quote">"UTF-8"</span>?&gt;</span>
&lt;project xmlns=<span class="code-quote">"http://maven.apache.org/POM/4.0.0"</span>
<span class="code-keyword">xmlns:xsi</span>=<span class="code-quote">"http://www.w3.org/2001/XMLSchema-instance"</span>
xsi:schemaLocation=<span class="code-quote">"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"</span>&gt;
<span class="code-tag">&lt;modelVersion&gt;</span>4.0.0<span class="code-tag">&lt;/modelVersion&gt;</span>
<span class="code-tag">&lt;groupId&gt;</span>org.apache.shiro.tutorials<span class="code-tag">&lt;/groupId&gt;</span>
<span class="code-tag">&lt;artifactId&gt;</span>shiro-tutorial<span class="code-tag">&lt;/artifactId&gt;</span>
<span class="code-tag">&lt;version&gt;</span>1.0.0-SNAPSHOT<span class="code-tag">&lt;/version&gt;</span>
<span class="code-tag">&lt;name&gt;</span>First Apache Shiro Application<span class="code-tag">&lt;/name&gt;</span>
<span class="code-tag">&lt;packaging&gt;</span>jar<span class="code-tag">&lt;/packaging&gt;</span>
<span class="code-tag">&lt;properties&gt;</span>
<span class="code-tag">&lt;project.build.sourceEncoding&gt;</span>UTF-8<span class="code-tag">&lt;/project.build.sourceEncoding&gt;</span>
<span class="code-tag">&lt;/properties&gt;</span>
<span class="code-tag">&lt;build&gt;</span>
<span class="code-tag">&lt;plugins&gt;</span>
<span class="code-tag">&lt;plugin&gt;</span>
<span class="code-tag">&lt;groupId&gt;</span>org.apache.maven.plugins<span class="code-tag">&lt;/groupId&gt;</span>
<span class="code-tag">&lt;artifactId&gt;</span>maven-compiler-plugin<span class="code-tag">&lt;/artifactId&gt;</span>
<span class="code-tag">&lt;version&gt;</span>2.0.2<span class="code-tag">&lt;/version&gt;</span>
<span class="code-tag">&lt;configuration&gt;</span>
<span class="code-tag">&lt;source&gt;</span>1.5<span class="code-tag">&lt;/source&gt;</span>
<span class="code-tag">&lt;target&gt;</span>1.5<span class="code-tag">&lt;/target&gt;</span>
<span class="code-tag">&lt;encoding&gt;</span>${project.build.sourceEncoding}<span class="code-tag">&lt;/encoding&gt;</span>
<span class="code-tag">&lt;/configuration&gt;</span>
<span class="code-tag">&lt;/plugin&gt;</span>
&lt;!-- This plugin is only to test run our little application. It is not
needed in most Shiro-enabled applications: --&gt;
<span class="code-tag">&lt;plugin&gt;</span>
<span class="code-tag">&lt;groupId&gt;</span>org.codehaus.mojo<span class="code-tag">&lt;/groupId&gt;</span>
<span class="code-tag">&lt;artifactId&gt;</span>exec-maven-plugin<span class="code-tag">&lt;/artifactId&gt;</span>
<span class="code-tag">&lt;version&gt;</span>1.1<span class="code-tag">&lt;/version&gt;</span>
<span class="code-tag">&lt;executions&gt;</span>
<span class="code-tag">&lt;execution&gt;</span>
<span class="code-tag">&lt;goals&gt;</span>
<span class="code-tag">&lt;goal&gt;</span>java<span class="code-tag">&lt;/goal&gt;</span>
<span class="code-tag">&lt;/goals&gt;</span>
<span class="code-tag">&lt;/execution&gt;</span>
<span class="code-tag">&lt;/executions&gt;</span>
<span class="code-tag">&lt;configuration&gt;</span>
<span class="code-tag">&lt;classpathScope&gt;</span>test<span class="code-tag">&lt;/classpathScope&gt;</span>
<span class="code-tag">&lt;mainClass&gt;</span>Tutorial<span class="code-tag">&lt;/mainClass&gt;</span>
<span class="code-tag">&lt;/configuration&gt;</span>
<span class="code-tag">&lt;/plugin&gt;</span>
<span class="code-tag">&lt;/plugins&gt;</span>
<span class="code-tag">&lt;/build&gt;</span>
<span class="code-tag">&lt;dependencies&gt;</span>
<span class="code-tag">&lt;dependency&gt;</span>
<span class="code-tag">&lt;groupId&gt;</span>org.apache.shiro<span class="code-tag">&lt;/groupId&gt;</span>
<span class="code-tag">&lt;artifactId&gt;</span>shiro-core<span class="code-tag">&lt;/artifactId&gt;</span>
<span class="code-tag">&lt;version&gt;</span>1.1.0<span class="code-tag">&lt;/version&gt;</span>
<span class="code-tag">&lt;/dependency&gt;</span>
&lt;!-- Shiro uses SLF4J for logging. We'll use the 'simple' binding
in this example app. See http://www.slf4j.org for more info. --&gt;
<span class="code-tag">&lt;dependency&gt;</span>
<span class="code-tag">&lt;groupId&gt;</span>org.slf4j<span class="code-tag">&lt;/groupId&gt;</span>
<span class="code-tag">&lt;artifactId&gt;</span>slf4j-simple<span class="code-tag">&lt;/artifactId&gt;</span>
<span class="code-tag">&lt;version&gt;</span>1.6.1<span class="code-tag">&lt;/version&gt;</span>
<span class="code-tag">&lt;scope&gt;</span>test<span class="code-tag">&lt;/scope&gt;</span>
<span class="code-tag">&lt;/dependency&gt;</span>
<span class="code-tag">&lt;/dependencies&gt;</span>
<span class="code-tag">&lt;/project&gt;</span>
</pre>
</div></div>
<h4><a name="Tutorial-TheTutorialclass"></a>The Tutorial class</h4>
<p>We'll be running a simple command-line application, so we'll need to create a Java class with a <tt>public static void main(String[] args)</tt> method. </p>
<p>In the same directory containing your <tt>pom.xml</tt> file, create a *<tt>src/main/java</tt> sub directory. In <tt>src/main/java</tt> create a <tt>Tutorial.java</tt> file with the following contents:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeHeader panelHeader" style="border-bottom-width: 1px;"><b>src/main/java/Tutorial.java</b></div><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.authc.*;
<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.session.Session;
<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.slf4j.Logger;
<span class="code-keyword">import</span> org.slf4j.LoggerFactory;
<span class="code-keyword">public</span> class Tutorial {
<span class="code-keyword">private</span> <span class="code-keyword">static</span> <span class="code-keyword">final</span> <span class="code-keyword">transient</span> Logger log = LoggerFactory.getLogger(Tutorial.class);
<span class="code-keyword">public</span> <span class="code-keyword">static</span> void main(<span class="code-object">String</span>[] args) {
log.info(<span class="code-quote">"My First Apache Shiro Application"</span>);
<span class="code-object">System</span>.exit(0);
}
}
</pre>
</div></div>
<p>Don't worry about the import statements for now - we'll get to them shortly. But for now, we've got a typical command line program 'shell'. All this program will do is print out the text "My First Apache Shiro Application" and exit.</p>
<h3><a name="Tutorial-TestRun"></a>Test Run</h3>
<p>To try our Tutorial application, execute the following in a command prompt in your tutorial project's root dirctory (e.g. <tt>shiro-tutorial</tt>), and type the following:</p>
<p><tt>mvn compile exec:java</tt></p>
<p>And you will see our little Tutorial 'application' run and exit. You should see something similar to the following (notice the bold text, indicating our output):</p>
<div class="panel" style="background-color: white;border-width: 1px;"><div class="panelHeader" style="border-bottom-width: 1px;background-color: white;"><b>Run the Application</b></div><div class="panelContent" style="background-color: white;">
<p><tt>lhazlewood:~/projects/shiro-tutorial$ mvn compile exec:java</tt></p>
<p><tt>... a bunch of Maven output ...</tt></p>
<p><b><tt>1 [Tutorial.main()] INFO Tutorial - My First Apache Shiro Application</tt></b><br clear="none">
<tt>lhazlewood:~/projects/shiro-tutorial\$</tt></p>
</div></div>
<p>We've verified the application runs successfully - now let's enable Apache Shiro. As we continue with the tutorial, you can run <tt>mvn compile exec:java</tt> after each time we add some more code to see the results of our changes.</p>
<h3><a name="Tutorial-EnableShiro"></a>Enable Shiro</h3>
<p>The first thing to understand in enabling Shiro in an application is that almost everything in Shiro is related to a central/core component called the <tt>SecurityManager</tt>. For those familiar with Java security, this is Shiro's notion of a SecurityManager - it is <em>NOT</em> the same thing as the <tt>java.lang.SecurityManager</tt>.</p>
<p>While we will cover Shiro's design in detail in the <a href="architecture.html" title="Architecture">Architecture</a> chapter, it is good enough for now to know that the Shiro <tt>SecurityManager</tt> is the core of a Shiro environment for an application and one <tt>SecurityManager</tt> must exist per application. So, the first thing we must do in our Tutorial application is set-up the <tt>SecurityManager</tt> instance.</p>
<h4><a name="Tutorial-Configuration"></a>Configuration</h4>
<p>While we could instantiate a <tt>SecurityManager</tt> class directly, Shiro's <tt>SecurityManager</tt> implementations have enough configuration options and internal components that make this a pain to do in Java source code - it would be much easier to configure the <tt>SecurityManager</tt> with a flexible text-based configuration format. </p>
<p>To that end, Shiro provides a default &#8216;common denominator&#8217; solution via text-based <a class="external-link" href="http://en.wikipedia.org/wiki/INI_file" rel="nofollow">INI</a> configuration. People are pretty tired of using bulky XML files these days, and INI is easy to read, simple to use, and requires very few dependencies. You&#8217;ll also see later that with a simple understanding of object graph navigation, INI can be used effectively to configure simple object graphs like the SecurityManager. </p>
<div class="panelMacro"><table class="tipMacro"><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/check.gif" width="16" height="16" alt="" border="0"></td><td colspan="1" rowspan="1"><b>Many Configuration Options</b><br clear="none">Shiro's <tt>SecurityManager</tt> implementations and all supporting components are all JavaBeans compatible. This allows Shiro to be configured with practically any configuration format such as XML (Spring, JBoss, Guice, etc), <a class="external-link" href="http://www.yaml.org/" rel="nofollow">YAML</a>, JSON, Groovy Builder markup, and more. INI is just Shiro's 'common denominator' format that allows configuration in any environment in case other options are not available.</td></tr></table></div>
<h5><a name="Tutorial-%7B%7Bshiro.ini%7D%7D"></a><tt>shiro.ini</tt></h5>
<p>So we'll use an INI file to configure the Shiro <tt>SecurityManager</tt> for this simple application. First, create a <b><tt>src/main/resources</tt></b> directory starting in the same directory where the <tt>pom.xml</tt> is. Then create a <tt>shiro.ini</tt> file in that new directory with the following contents:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeHeader panelHeader" style="border-bottom-width: 1px;"><b>src/main/resources/shiro.ini</b></div><div class="codeContent panelContent">
<pre class="code-java">
# =============================================================================
# Tutorial INI configuration
#
# Usernames/passwords are based on the classic Mel Brooks' film <span class="code-quote">"Spaceballs"</span> :)
# =============================================================================
# -----------------------------------------------------------------------------
# Users and their (optional) assigned roles
# username = password, role1, role2, ..., roleN
# -----------------------------------------------------------------------------
[users]
root = secret, admin
guest = guest, guest
presidentskroob = 12345, president
darkhelmet = ludicrousspeed, darklord, schwartz
lonestarr = vespa, goodguy, schwartz
# -----------------------------------------------------------------------------
# Roles with assigned permissions
# roleName = perm1, perm2, ..., permN
# -----------------------------------------------------------------------------
[roles]
admin = *
schwartz = lightsaber:*
goodguy = winnebago:drive:eagle5
</pre>
</div></div>
<p>As you see, this configuration basically sets up a small set of static user accounts, good enough for our first application. In later chapters, you will see how we can use more complex User data sources like relational databases, LDAP an ActiveDirectory, and more.</p>
<h4><a name="Tutorial-ReferencingtheConfiguration"></a>Referencing the Configuration</h4>
<p>Now that we have an INI file defined, we can create the <tt>SecurityManager</tt> instance in our Tutorial application class. Change the <tt>main</tt> method to reflect the following updates:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">public</span> <span class="code-keyword">static</span> void main(<span class="code-object">String</span>[] args) {
log.info(<span class="code-quote">"My First Apache Shiro Application"</span>);
<span class="code-comment">//1.
</span> Factory&lt;<span class="code-object">SecurityManager</span>&gt; factory = <span class="code-keyword">new</span> IniSecurityManagerFactory(<span class="code-quote">"classpath:shiro.ini"</span>);
<span class="code-comment">//2.
</span> <span class="code-object">SecurityManager</span> securityManager = factory.getInstance();
<span class="code-comment">//3.
</span> SecurityUtils.setSecurityManager(securityManager);
<span class="code-object">System</span>.exit(0);
}
</pre>
</div></div>
<p>And there we go - Shiro is enabled in our sample application after adding only 3 lines of code! How easy was that? </p>
<p>Feel free to run <tt>mvn compile exec:java</tt> and see that everything still runs successfully (due to Shiro's default logging of debug or lower, you won't see any Shiro log messages - if it starts and runs without error, then you know everything is still ok).</p>
<p>Here is what the above additions are doing:</p>
<ol><li>We use Shiro's <tt>IniSecurityManagerFactory</tt> implementation to ingest our <tt>shiro.ini</tt> file which is located at the root of the classpath. This implementation reflects Shiro's support of the <a class="external-link" href="http://en.wikipedia.org/wiki/Factory_method_pattern" rel="nofollow">Factory Method Design Pattern</a>. The <tt>classpath:</tt> prefix is an resource indicator that tells shiro where to load the ini file from (other prefixes, like <tt>url:</tt> and <tt>file:</tt> are supported as well).
<br clear="none" class="atl-forced-newline">
<br clear="none" class="atl-forced-newline"></li><li>The <tt>factory.getInstance()</tt> method is called, which parses the INI file and returns a <tt>SecurityManager</tt> instance reflecting the configuration.
<br clear="none" class="atl-forced-newline">
<br clear="none" class="atl-forced-newline"></li><li>In this simple example, we set the <tt>SecurityManager</tt> to be a <em>static</em> (memory) singleton, accessible across the JVM. Note however that this is not desireable if you will ever have more than one Shiro-enabled application in a single JVM. For this simple example, it is ok, but more sophisticated application environments will usually place the <tt>SecurityManager</tt> in application-specific memory (such as in a web app's <tt>ServletContext</tt> or a Spring, Guice or JBoss DI container instance).</li></ol>
<h3><a name="Tutorial-UsingShiro"></a>Using Shiro</h3>
<p>Now that our SecurityManager is set-up and ready-to go, now we can start doing the things we really care about - performing security operations.</p>
<p>When securing our applications, probably the most relevant questions we ask ourselves are &#8220;Who is the current user?&#8221; or &#8220;Is the current user allowed to do X&#8221;? It is common to ask these questions as we're writing code or designing user interfaces: applications are usually built based on user stories, and you want functionality represented (and secured) based on a per-user basis. So, the most natural way for us to think about security in our application is based on the current user. Shiro&#8217;s API fundamentally represents the notion of 'the current user' with its <tt>Subject</tt> concept. </p>
<p>In almost all environments, you can obtain the currently executing user via the following call:</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>Using <tt><a class="external-link" href="static/current/apidocs/org/apache/shiro/SecurityUtils.html">SecurityUtils</a>.<a class="external-link" href="static/current/apidocs/org/apache/shiro/SecurityUtils.html#getSubject()">getSubject()</a></tt>, we can obtain the currently executing <tt><a class="external-link" href="static/current/apidocs/org/apache/shiro/subject/Subject.html">Subject</a></tt>. <em>Subject</em> is a security term that basically means "a security-specific view of the currently executing user". It is not called a 'User' because the word 'User' is usually associated with a human being. In the security world, the term 'Subject' can mean a human being, but also a 3rd party process, cron job, daemon account, or anything similar. It simply means 'the thing that is currently interacting with the software'. For most intents and purposes though, you can think of the <tt>Subject</tt> as Shiro&#8217;s &#8216;User&#8217; concept.</p>
<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 <tt>Subject</tt> based on user data associated with current thread or incoming request.</p>
<p>Now that you have a <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 tutorial application, 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 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> 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 and allows you to handle and react accordingly:</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>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="static/current/apidocs/org/apache/shiro/authc/AuthenticationException.html">AuthenticationException JavaDoc</a> for more. </p>
<div class="panelMacro"><table class="tipMacro"><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/check.gif" width="16" height="16" alt="" border="0"></td><td colspan="1" rowspan="1"><b>Handy Hint</b><br clear="none">Security best practice is to give generic login failure messages to users because you do not want to aid an attacker trying to break into your system.</td></tr></table></div>
<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>
<p></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>
<p></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 permission to act on a certain type of entity:</p>
<p></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> permission check - the ability to see if the user has the ability to access a specific instance of a type:</p>
<p></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>
<p></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>
<h4><a name="Tutorial-FinalTutorialclass"></a>Final Tutorial class</h4>
<p>After adding in the above code examples, here is our final Tutorial class file. Feel free to edit and play with it and change the security checks (and the INI configuration) as you like:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeHeader panelHeader" style="border-bottom-width: 1px;"><b>Final src/main/java/Tutorial.java</b></div><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.authc.*;
<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.session.Session;
<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.slf4j.Logger;
<span class="code-keyword">import</span> org.slf4j.LoggerFactory;
<span class="code-keyword">public</span> class Tutorial {
<span class="code-keyword">private</span> <span class="code-keyword">static</span> <span class="code-keyword">final</span> <span class="code-keyword">transient</span> Logger log = LoggerFactory.getLogger(Tutorial.class);
<span class="code-keyword">public</span> <span class="code-keyword">static</span> void main(<span class="code-object">String</span>[] args) {
log.info(<span class="code-quote">"My First Apache Shiro Application"</span>);
Factory&lt;<span class="code-object">SecurityManager</span>&gt; factory = <span class="code-keyword">new</span> IniSecurityManagerFactory(<span class="code-quote">"classpath:shiro.ini"</span>);
<span class="code-object">SecurityManager</span> securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
<span class="code-comment">// get the currently executing user:
</span> Subject currentUser = SecurityUtils.getSubject();
<span class="code-comment">// Do some stuff with a Session (no need <span class="code-keyword">for</span> a web or EJB container!!!)
</span> Session session = currentUser.getSession();
session.setAttribute(<span class="code-quote">"someKey"</span>, <span class="code-quote">"aValue"</span>);
<span class="code-object">String</span> value = (<span class="code-object">String</span>) session.getAttribute(<span class="code-quote">"someKey"</span>);
<span class="code-keyword">if</span> (value.equals(<span class="code-quote">"aValue"</span>)) {
log.info(<span class="code-quote">"Retrieved the correct value! ["</span> + value + <span class="code-quote">"]"</span>);
}
<span class="code-comment">// let's login the current user so we can check against roles and permissions:
</span> <span class="code-keyword">if</span> (!currentUser.isAuthenticated()) {
UsernamePasswordToken token = <span class="code-keyword">new</span> UsernamePasswordToken(<span class="code-quote">"lonestarr"</span>, <span class="code-quote">"vespa"</span>);
token.setRememberMe(<span class="code-keyword">true</span>);
<span class="code-keyword">try</span> {
currentUser.login(token);
} <span class="code-keyword">catch</span> (UnknownAccountException uae) {
log.info(<span class="code-quote">"There is no user with username of "</span> + token.getPrincipal());
} <span class="code-keyword">catch</span> (IncorrectCredentialsException ice) {
log.info(<span class="code-quote">"Password <span class="code-keyword">for</span> account "</span> + token.getPrincipal() + <span class="code-quote">" was incorrect!"</span>);
} <span class="code-keyword">catch</span> (LockedAccountException lae) {
log.info(<span class="code-quote">"The account <span class="code-keyword">for</span> username "</span> + token.getPrincipal() + <span class="code-quote">" is locked. "</span> +
<span class="code-quote">"Please contact your administrator to unlock it."</span>);
}
<span class="code-comment">// ... <span class="code-keyword">catch</span> more exceptions here (maybe custom ones specific to your application?
</span> <span class="code-keyword">catch</span> (AuthenticationException ae) {
<span class="code-comment">//unexpected condition? error?
</span> }
}
<span class="code-comment">//say who they are:
</span> <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>);
<span class="code-comment">//test a role:
</span> <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>);
}
<span class="code-comment">//test a typed permission (not instance-level)
</span> <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>);
}
<span class="code-comment">//a (very powerful) Instance Level permission:
</span> <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>);
}
<span class="code-comment">//all done - log out!
</span> currentUser.logout();
<span class="code-object">System</span>.exit(0);
}
}
</pre>
</div></div>
<h3><a name="Tutorial-Summary"></a>Summary</h3>
<p>Hopefully this introduction tutorial helped you understand how to set-up Shiro in a basic application as well Shiro's primary design concepts, the <tt>Subject</tt> and <tt>SecurityManager</tt>.</p>
<p>But this was a fairly simple application. You might have asked yourself, "What if I don't want to use INI user accounts and instead want to connect to a more complex user data source?"</p>
<p>To answer that question requires a little deeper understanding of Shiro's architecture and supporting configuration mechanisms. We'll cover Shiro's <a href="architecture.html" title="Architecture">Architecture</a> next.</p>