blob: b84a641ecf8bc04137c956c26099295e94609311 [file] [log] [blame]
<h1><a name="JavaAuthorizationGuide-JavaAuthorizationGuidewithApacheShiro"></a>Java Authorization Guide with Apache Shiro</h1>
<p><br clear="none" class="atl-forced-newline">
Authorization, or access control, is the function of specifying access rights to resources. In other words, <em>who</em> has access to <em>what</em>.</p>
<p>Examples of authorization checks are: Is the user allowed to look at this webpage, edit this data, view this button, or print to this printer? Those are all decisions determining what a user has access to.</p>
<h2><a name="JavaAuthorizationGuide-ElementsofAuthorization"></a>Elements of Authorization</h2>
<p>Authorization has three core elements that we reference quite a bit in Shiro-- permissions, roles, and users. </p>
<h3><a name="JavaAuthorizationGuide-PermissionsDefined"></a>Permissions Defined</h3>
<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="authorization-features.html">Authorization Features</a></h3>
<p>Quick overview of permissions, roles, and users in Shiro. </br><span style="font-size:11"><a href="authorization-features.html">Read More &gt;&gt;</a></span></p>
<h3><a href="authorization.html">Authorization Docs</a></h3>
<p>Full documentation on Apache Shiro's Authorization functionality. </br><span style="font-size:11"><a href="authorization.html">Read More &gt;&gt;</a></span></p>
<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>
<p>Permissions are the most atomic level of a security policy and they are statements of functionality. Permissions represent what can be done in your application. A well formed permission describes a resource types and what actions are possible when you interact with those resources. Can you <em>open</em> a <em>door</em>? Can you <em>read</em> a <em>file</em>? Can you <em>delete</em> a <em>customer record</em>? Can you <em>push</em> a <em>button</em>? </p>
<p>Common actions for data-related resources are create, read, update, and delete, commonly referred to as CRUD.</p>
<p>It is important to understand that permissions do not have knowledge of <em>who</em> can perform the actions-- they are just statements of <em>what</em> actions can be performed.</p>
<h4><a name="JavaAuthorizationGuide-Levelsofpermissiongranularity"></a>Levels of permission granularity</h4>
<p>The permissions above all specify an actions (open, read, delete, etc) on a resource (door, file, customer record, etc). In Shiro, you can define a permission to any depth you like. Here are a few common permission levels in order of granularity.</p>
<ul><li>Resource Level - This is the broadest and easiest to build. A user can edit customer records or open doors. The resource is specified but not a specific instance of that resource.</li><li>Instance Level - The permission specifies the instance of a resource. A user can edit the customer record for IBM or open the kitchen door.</li><li>Attribute Level - The permission now specifies an attribute of an instance or resource. A user can edit the address on the IBM customer record.</li></ul>
<p>For more information on Permissions please check out the <a href="permissions.html" title="Permissions">Permissions Documentation</a></p>
<h3><a name="JavaAuthorizationGuide-RolesDefined"></a>Roles Defined</h3>
<p>In the context of Authorization, Roles are effectively a collection of permissions used to simplify the management of permissions and users. So users can be assigned roles instead of being assigned permissions directly, which can get complicated with larger user bases and more complex applications. So, for example, a bank application might have an <em>administrator</em> role or a <em>bank teller</em> role.</p>
<p>There are two types of roles that you need to be aware of and Shiro will support both.</p>
<h4><a name="JavaAuthorizationGuide-ImplicitRoles"></a>Implicit Roles</h4>
<p>Most people view roles as what we define as an implicit role where your application <em>implies</em> a set of permissions because a user has a particular role as opposed to the role explicitly being assigned permissions or your application checking for those permissions. Role checks in code are generally a reflection of an implicit role. You can view patient data because you have the <em>administrator</em> role. You can create an account because you have the <em>bank teller</em> role. The fact that these names exist does not have a correlation to what the software can actually do. Most people use roles in this manner. It is easiest but it can create a lot of maintenance and management problems for all the but the simplest application.</p>
<h4><a name="JavaAuthorizationGuide-ExplicitRoles"></a>Explicit Roles</h4>
<p>An explicit role has permissions <em>explicitly</em> assigned to it and therefore is an <em>explicit</em> collection of permissions. Permission checks in code are a reflection of an explicit role. You can view patient data because because you have the <em>view patient data</em> permission as part of your <em>administrator</em> role. You can create an account because you have the <em>create account</em> permission as part of your <em>bank teller</em> role. You can perform these actions, not because of some implicit role name based on a string but because the corresponding permission was explicitly assigned to your role.</p>
<p>The big benefits of explicit roles are easier manageability and lower maintenance of your application. If you ever need to add, remove, or change a role, you can do so without touching your source code. And in Shiro, you'll also be able to dynamically add, remove, or change roles at runtime and your authorization checks will always have up to date values. This means you won't have to force users to log out and log back in order to get their new permissions.</p>
<h3><a name="JavaAuthorizationGuide-UsersDefined"></a>Users Defined</h3>
<p>A user is the "who" of an application. In Shiro, though, the concept of a user is really the <a href="subject.html" title="Subject">Subject</a> instance. We use word Subject instead of user because user usually implies a human being and in Shiro a Subject can be anything interacting with your application-- whether it be a human or a service. </p>
<p>Users are allowed to perform certain actions in your application through their association with roles or direct permissions. So you are able to open a customer record because you've been assigned the <em>open customer record</em> permission, either through a role you've been assigned or through a direct permission assignment.</p>
<p>For more information on Users, aka Subjects, please check out the <a href="subject.html" title="Subject">Subject Documentation</a>.</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">Ultimately, your <a href="realm.html" title="Realm">Realm</a> implementation is what communicates with your data source (RDBMS, LDAP, etc). So your realm is what will tell Shiro whether or not roles or permissions exist. You have full control over how your authorization model works.</td></tr></table></div>
<h2><a name="JavaAuthorizationGuide-HowtoperformAuthorizationinJavawithShiro"></a>How to perform Authorization in Java with Shiro</h2>
<p>Authorization in Shiro can be handled in four ways.</p>
<ul><li>Programmatically - You can perform authorization checks in your java code with structures like <tt>if</tt> and <tt>else</tt> blocks.</li><li>JDK annotations - You can attach an authorization annotation to your Java methods</li><li>JSP/GSP TagLibs - You can control jsp or gsp page output based on roles and permissions</li></ul>
<h3><a name="JavaAuthorizationGuide-ProgrammaticAuthorization"></a>Programmatic Authorization</h3>
<p>Checking for permissions and roles, programmatically in your Java code is the traditional way of handling authorization. Here's how you can perform a permission check or role check in Shiro.</p>
<h4><a name="JavaAuthorizationGuide-RoleCheck"></a>Role Check</h4>
<p>This is an example of how you do a role check programmatically in your application. We want to check if a user has the <em>administrator</em> role and if they do, then we'll show a special button, otherwise we won't show it.</p>
<p>First we get access to the current user, the <a href="subject.html" title="Subject">Subject</a>. Then we pass the <em>adminstrator</em> to the Subject's <tt><a class="external-link" href="static/current/apidocs/org/apache/shiro/subject/Subject.html#hasRole(java.lang.String)">.hasRole()</a></tt> method. It will return <tt>TRUE</tt> or <tt>FALSE</tt>. </p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-comment">//get the current Subject
</span>Subject currentUser =
SecurityUtils.getSubject();
<span class="code-keyword">if</span> (currentUser.hasRole(&#8220;administrator&#8221;)) {
<span class="code-comment">//show a special button&#8207;
</span>} <span class="code-keyword">else</span> {
<span class="code-comment">//don&#8217;t show the button?)&#8207;
</span>}
</pre>
</div></div>
<p>Now a role based check is quick and easy to implement but it has a major drawback. It is implicit.</p>
<p>What if you just want to add, remove, or redefine a role later? You'll have to crack open your source code and change all your role checks to reflect the change in your security model. You'll have to shut down the application, crack open the code, test it, and then restart it everytime. </p>
<p>In very simple applications this is probably good enough but for larger apps this can be a major problem throughout the life of your application and drive a large maintenance cost for your software. </p>
<h4><a name="JavaAuthorizationGuide-PermissionCheck"></a>Permission Check</h4>
<p>This is an example of how you do security checks by permission. We want to check if a user has permission to print to laserjet3000n and if they do, then we'll show a print button, otherwise we won't show it. This is an example of an instance level permission or instance level authorization.</p>
<p>Again, first you get access to the current user, the <a href="subject.html" title="Subject">Subject</a>. Then you construct a <tt><a class="external-link" href="static/current/apidocs/org/apache/shiro/authz/Permission.html">Permission</a></tt> object or an instance that represents an action on a resource. In this case, the instance is named <tt>printerPermission</tt>, the resource is <em>laserjet3000n</em>, and the action is <em>print</em>. Then we pass <tt>printerPermission</tt> to the Subject's <tt><a class="external-link" href="static/current/apidocs/org/apache/shiro/subject/Subject.html#isPermitted(java.util.List)">.isPermitted()</a></tt> method. It will return true or false. </p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
Subject currentUser =
SecurityUtils.getSubject();
Permission printPermission =
<span class="code-keyword">new</span> PrinterPermission(&#8220;laserjet3000n&#8221;,&#8220;print&#8221;);
If (currentUser.isPermitted(printPermission)) {
<span class="code-comment">//<span class="code-keyword">do</span> one thing (show the print button?)&#8207;
</span>} <span class="code-keyword">else</span> {
<span class="code-comment">//don&#8217;t show the button?
</span>}
</pre>
</div></div>
<h4><a name="JavaAuthorizationGuide-PermissionCheck%28Stringbased%29"></a>Permission Check (String-based)</h4>
<p>You can also a permission check using a simple string instead of a permission class.</p>
<p>So, if you don't want to implement our <a class="external-link" href="static/current/apidocs/org/apache/shiro/authz/Permission.html">permission interface</a> then you just pass in a String. In this example, we pass the <tt>.isPermitted()</tt> method a string, <tt>printer:print:LaserJet4400n</tt></p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-object">String</span> perm = &#8220;printer:print:laserjet4400n&#8221;;
<span class="code-keyword">if</span>(currentUser.isPermitted(perm)){
<span class="code-comment">//show the print button?
</span>} <span class="code-keyword">else</span> {
<span class="code-comment">//don&#8217;t show the button?
</span>}
</pre>
</div></div>
<p>You can construct the permission string the way you want so long as your <a href="realm.html" title="Realm">Realm</a> knows how to work with it. In this example we use Shiro's optional permission syntax, <a href="permissions.html" title="Permissions">WildCardPermissions</a>. WildCardPermissions are powerful and intuitive. If you'd like to learn more about them then check out the <a class="external-link" href="static/current/apidocs/org/apache/shiro/authz/Permission.html">Permissions Documentation</a>.</p>
<p>With string-based permission checks, you get the same functionality as the example before. The benefit is that you are not forced to implement a permission interface and you can construct the permission via a simple string. The downside is that you don't have type safety and if you needed more complicated permission capabilitues that are outside the scope of what this represents, you're going to want to implement your own permission objects based on the permission interface.</p>
<h3><a name="JavaAuthorizationGuide-AnnotationAuthorization"></a>Annotation Authorization</h3>
<p>If you don't want to do code level authorization checks, then you can use Java Annotations as well. Shiro offers a number of <a href="java-annotations-list.html" title="Java Annotations List">Java annotations</a> that allow you to annotate methods. </p>
<h4><a name="JavaAuthorizationGuide-EnablingAnnotationSupport"></a>Enabling Annotation Support</h4>
<p>Before you can use Java annotations, you'll need to enable AOP support in your application. There are a number of different AOP frameworks so, unfortunately, there is no standard way to enable AOP in an application.</p>
<p>For AspectJ, you can review our <a class="external-link" href="https://github.com/apache/shiro/tree/master/samples/aspectj">AspectJ sample application</a>.</p>
<p>For Spring, you can look into our <a href="spring.html" title="Spring">Spring Integration</a> documentation.</p>
<p>For Guice, you can look into our <a href="guice.html" title="Guice">Guice Integration</a> documentation.</p>
<h4><a name="JavaAuthorizationGuide-PermissionCheck"></a>Permission Check</h4>
<p>In this example, we want to check that a user has the <tt>account:create</tt> permission before they can invoke the <tt>openAccount</tt> method. If they do, then the method is called as expected, and if they don't, then an exception is thrown. </p>
<p>Like programmatic checks, you can use the <a class="external-link" href="static/current/apidocs/org/apache/shiro/authz/Permission.html">Permission</a> objects or the simple string methods with this annotation.</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-comment">//Will <span class="code-keyword">throw</span> an AuthorizationException <span class="code-keyword">if</span> none
</span><span class="code-comment">//of the caller&#8217;s roles imply the Account
</span><span class="code-comment">//'create' permission&#65533;
</span>@RequiresPermissions(&#8220;account:create&#8221;)&#8207;
<span class="code-keyword">public</span> void openAccount( Account acct ) {
<span class="code-comment">//create the account
</span>}
</pre>
</div></div>
<h4><a name="JavaAuthorizationGuide-RoleCheck"></a>Role Check</h4>
<p>In this example, we want to check that a user has the <tt>teller</tt> role before they can invoke the <tt>openAccount</tt> method. If they do, then the method is called as expected, and if they don't, then an exception is thrown.</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-comment">//Throws an AuthorizationException <span class="code-keyword">if</span> the caller
</span><span class="code-comment">//doesn&#8217;t have the &#8216;teller&#8217; role:
</span>
@RequiresRoles( &#8220;teller&#8221; )
<span class="code-keyword">public</span> void openAccount( Account acct ) {
<span class="code-comment">//<span class="code-keyword">do</span> something in here that only a teller
</span> <span class="code-comment">//should <span class="code-keyword">do</span>
</span>}
</pre>
</div></div>
<h3><a name="JavaAuthorizationGuide-JSPTagLibAuthorization"></a>JSP TagLib Authorization</h3>
<p>For JSP/GSP based web applications, Shiro also offers a <a href="jsp-tag-library.html" title="JSP Tag Library">tag library</a> for you to use. </p>
<p>In this example, we're going to show users with the <em>users:manage</em> permission a link to the Manage Users page. If they do not have the permission, then we'll show them a nice message.</p>
<p>First, we'll need to add the Shiro taglib to our web application. Next, we add the <tt>&lt;shiro:hasPermission&gt;</tt> tag with a check for <em>users:manage</em>. Within the <tt>&lt;shiro:hasPermission&gt;</tt> tags we will place the code we want to execute if the user has the permission we're checking for. If we want to take an action if the user lacks the permission, then we need to also add the <tt>&lt;shiro:lacksPermission&gt;</tt> tag, again checking for <em>users:manage</em>. And any code we want to excute if the user lacks the permission will need to be placed within the <tt>&lt;shiro:lacksPermission&gt;</tt> tags.</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
&lt;%@ taglib prefix=&#8220;shiro&#8221; uri=http:<span class="code-comment">//shiro.apache.org/tags %&gt;
</span>&lt;html&gt;
&lt;body&gt;
&lt;shiro:hasPermission name=&#8220;users:manage&#8221;&gt;
&lt;a href=&#8220;manageUsers.jsp&#8221;&gt;
Click here to manage users
&lt;/a&gt;
&lt;/shiro:hasPermission&gt;
&lt;shiro:lacksPermission name=&#8220;users:manage&#8221;&gt;
No user management <span class="code-keyword">for</span> you!
&lt;/shiro:lacksPermission&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
</div></div>
<p>Of course, there also tags for checking roles and other user data and states.</p>
<p>For more information on JSP/GSP Tags please check out the <a href="jsp-tag-library.html" title="JSP Tag Library">JSP Tag Library</a> and for more information on integration your application in your web application, please read the <a href="web.html" title="Web">Web Integration Documentation</a></p>
<h2><a name="JavaAuthorizationGuide-CachingAuthorization"></a>Caching Authorization</h2>
<p>TBD</p>
<h2><a name="JavaAuthorizationGuide-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>