Shiro | 1 | Easy Application Security with Apache Shiro

Easy Applica+on Security with Apache Shiro Les Hazlewood Apache Shiro Project Chair CTO, Stormpath, •  Iden9ty Management and Access Control API •  Security for your applica9ons •  User security workflows •  Security best prac9ces •  Developer tools, SDKs, libraries What is Apache Shiro? 300K
•  Applica9on security framework •  ASF TLP hJp:// •  Quick and Easy •  Simplifies Security Dec 2010
Aug 2012
Agenda Authen9ca9on Authoriza9on Session Management Cryptography Web Support Auxiliary Features Quick Terminology •  Subject – Security-­‐specific user ‘view’ •  Principals – Subject’s iden9fying aJributes •  Creden+als – Secret values that verify iden9ty •  Realm – Security-­‐specific DAO Authen+ca+on Authen+ca+on Authoriza9on Session Management Cryptography Web Support Auxiliary Features Authen+ca+on Defined Identity verification:
Proving a user is who he says he is
Shiro Authen+ca+on Features •  Subject-­‐based (current user) •  Single method call •  Rich Excep9on Hierarchy •  ‘Remember Me’ built in •  Event listeners How to Authen+cate with Shiro Steps
1.  Collect principals & credentials
2.  Submit to Authentication System
3.  Allow, retry, or block access
Step 1: Collec+ng Principals & Creden+als UsernamePasswordToken token = new
UsernamePasswordToken(username, password);
//”Remember Me” built-in:
Step 2: Submission Subject currentUser =
Step 3: Grant Access or Handle Failure
try {
} catch (UnknownAccountException uae ){ ...
} catch (IncorrectCredentialsException ice { ...
} catch ( LockedAccountException lae ) { ...
} catch ( ExcessiveAttemptsException eae ) { ...
} ... catch your own ...
} catch ( AuthenticationException ae ) {
//unexpected error?
//No problems, show authenticated view…
How does it work? Subject .login(token) How does it work? Subject .login(token) SecurityManager How does it work? Subject .login(token) SecurityManager Authen9cator How does it work? Subject .login(token) SecurityManager Authen9cator Realm 1 Realm 2 … Realm N How does it work? Subject .login(token) SecurityManager Authen9cator Realm 1 Realm 2 … Authen9ca9on Strategy Realm N Authoriza+on Authen9ca9on Authoriza+on Session Management Cryptography Web Support Auxiliary Features Authoriza+on Defined Process of determining “who can do what” AKA Access Control Elements of Authoriza+on •  Permissions •  Roles •  Users Permissions Defined •  Most atomic security element •  Describes resource types and their behavior •  The “what” of an applica9on •  Does not define “who” •  AKA “rights” Roles Defined •  Implicit or Explicit construct •  Implicit: Name only •  Explicit: A named collec9on of Permissions Allows behavior aggrega9on Enables dynamic (run9me) altera9on of user abili9es. Users Defined •  The “who” of the applica9on •  What each user can do is defined by their associa9on with Roles or Permissions Example: User’s roles imply PrinterPermission Authoriza+on Features •  Subject-­‐centric (current user) •  Checks based on roles or permissions •  Powerful out-­‐of-­‐the-­‐box WildcardPermission •  Any data model – Realms decide How to Authorize with Shiro Mul9ple means of checking access control: •  Programma9cally •  JDK 1.5 annota9ons & AOP •  JSP/GSP/JSF* TagLibs (web support) Programma+c Authoriza+on Role Check //get the current Subject
Subject currentUser =
if (currentUser.hasRole(“administrator”)) {
//show the ‘delete user’ button‫‏‬
} else {
//don’t show the button?)‫‏‬
Programma+c Authoriza+on Permission Check Subject currentUser =
Permission deleteUser =
new UserPermission(“jsmith”,“delete”);
If (currentUser.isPermitted(deleteUser)) {
//show the ‘delete user’ button‫‏‬
} else {
//don’t show the button?
Programma+c Authoriza+on Permission Check (String-­‐based) String perm = “user:delete:jsmith”;
//show the ‘delete user’ button
} else {
//don’t show the button?
Annota+on Authoriza+on Role Check @RequiresRoles( “teller” )
public void openAccount(Account a) {
//do something in here that
//only a ‘teller’ should do
Annota+on Authoriza+on Permission Check @RequiresPermissions(“account:create”)
public void openAccount(Account a) {
//create the account
Enterprise Session Management Authen9ca9on Authoriza9on Session Management Cryptography Web Support Auxiliary Features Session Management Defined Managing the lifecycle of Subject-­‐specific temporal data context Session Management Features •  Heterogeneous client access •  POJO/J2SE based (IoC friendly) •  Event listeners •  Host address reten9on •  Inac9vity/expira9on support (touch()) •  Transparent web use -­‐ HJpSession •  Container-­‐Independent Clustering! Acquiring and Crea+ng Sessions Subject currentUser =
//guarantee a session
Session session = subject.getSession();
//get a session if it exists
Session API getStartTimestamp()
setAttribute(key, value)
Cryptography Authen9ca9on Authoriza9on Session Management Cryptography Web Support Auxiliary Features Cryptography Defined Protec9ng informa9on from undesired access by hiding it or conver9ng it into nonsense. Elements of Cryptography •  Ciphers •  Hashes Ciphers Defined Encryp9on and decryp9on data based on shared or public/private keys. •  Symmetric Cipher – same key •  Block Cipher – chunks of bits •  Stream Cipher – stream of bits •  Asymmetric Cipher -­‐ different keys Hashes Defined A one-­‐way, irreversible conversion of an input source (a.k.a. Message Digest) Used for: •  Creden9als transforma9on, Checksum •  Data with underlying byte array Files, Streams, etc Cryptography Features Simplicity •  Interface-­‐driven, POJO based •  Simplified wrapper over JCE infrastructure. •  “Object Orien9fies” cryptography concepts •  Easier to understand API Cipher Features •  OO Hierarchy JcaCipherService, AbstractSymmetricCipherService, DefaultBlockCipherService, etc •  Just instan9ate a class No “Transforma9on String”/Factory methods •  More secure default seings than JDK! Cipher Modes, Ini9aliza9on Vectors, et. al. Example: Plaintext (image courtesy WikiPedia) Example: ECB Mode (JDK Default!) (image courtesy WikiPedia) Example: Shiro Defaults (image courtesy WikiPedia) Shiro’s CipherService Interface public interface CipherService {
ByteSource encrypt(byte[] raw,
byte[] key);
void encrypt(InputStream in,
OutputStream out, byte[] key);
ByteSource decrypt( byte[] cipherText,
byte[] key);
void decrypt(InputStream in,
OutputStream out, byte[] key);
Hash Features •  Default interface implementa9ons MD5, SHA1, SHA-­‐256, et. al. •  Built in Hex & Base64 conversion •  Built-­‐in support for Salts and repeated hashing Shiro’s Hash Interface public interface Hash {
byte[] getBytes();
String toHex();
String toBase64();
Intui+ve OO Hash API //some examples:
new Md5Hash(“foo”).toHex();
//File MD5 Hash value for checksum:
new Md5Hash( aFile ).toHex();
//store password, but not plaintext:
new Sha512(aPassword, salt,
Web Support Authen9ca9on Authoriza9on Cryptography Session Management Web Support Auxiliary Features Web Support Features •  Simple ShiroFilter web.xml defini9on •  Protects all URLs •  Innova9ve Filtering (URL-­‐specific chains) •  JSP Tag support •  Transparent HJpSession support web.xml <filter>
shiro.ini [main]
ldapRealm = org.apache.shiro.realm.ldap.JndiLdapRealm
ldapRealm.userDnTemplate = uid={0},ou=users,dc=mycompany,dc=com
ldapRealm.contextFactory.url = ldap://ldapHost:389
securityManager.realm = $realm
/images/** = anon
/account/** = authc
/rest/** = authcBasic
/remoting/** = authc, roles[b2bClient], …
JSP TagLib Authoriza+on <%@ taglib prefix=“shiro”
uri=“” %>
<shiro:hasRole name=“administrator”>
<a href=“manageUsers.jsp”>
Click here to manage users
<shiro:lacksRole name=“administrator”>
No user admin for you!
JSP TagLibs <%@ taglib prefix=“shiro” uri= %>
<!-- Other tags: -->
Auxiliary Features Authen9ca9on Authoriza9on Cryptography Session Management Web Support Auxiliary Features Auxiliary Features •  Threading & Concurrency Callable/Runnable & Executor/ExecutorService •  “Run As” support •  Ad-­‐hoc Subject instance crea9on •  Unit Tes9ng •  Remembered vs Authen9cated Logging Out One method: //Logs
the user out, relinquishes account
//data, and invalidates any Session
App-­‐specific log-­‐out logic: Before/Amer the call Listen for Authen9ca9on or StoppedSession events. Coming in 1.3, 2.0 •  Typesafe EventBus •  OOTB Hazelcast Session clustering •  Lower coupling in components Composi9on over Inheritance •  Stronger JEE (CDI, JSF) support •  Default Realm Pluggable authc lookup, authz lookup •  Default Authen9ca9on Filter (mul9ple HTTP schemes + UI fallback) Stormpath: User Management API Service Applica+on + Stormpath Realm •  Realms + Plug-­‐ins •  REST API Stormpath Authen+ca+on Out-­‐of-­‐the-­‐box Features •  Managed security data model •  Secure creden9al storage •  Password self-­‐service •  Management GUI Access Control Stormpath: Cloud Deployment Public Cloud Corporate Network Applica+on Applica+on REST Stormpath Firewall Applica+on Outbound Sync Ac+ve Directory Thank You! • •  TwiJer: @lhazlewood •  hJp:// 
Download PDF