shiro-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From lhazlew...@apache.org
Subject svn commit: r890398 - in /incubator/shiro/trunk: core/src/main/java/org/apache/shiro/config/ core/src/main/java/org/apache/shiro/realm/text/ core/src/test/java/org/apache/shiro/config/ core/src/test/java/org/apache/shiro/realm/text/ core/src/test/resou...
Date Mon, 14 Dec 2009 16:40:40 GMT
Author: lhazlewood
Date: Mon Dec 14 16:40:39 2009
New Revision: 890398

URL: http://svn.apache.org/viewvc?rev=890398&view=rev
Log:
Added constructors to IniRealm and IniSecurityManagerFactory to load an Ini by resource path
and included accompanying tests.  Also updated the Quickstart to use this mechanism (a little
easier to understand).

Added:
    incubator/shiro/trunk/core/src/test/resources/org/apache/shiro/config/
    incubator/shiro/trunk/core/src/test/resources/org/apache/shiro/config/IniSecurityManagerFactoryTest.ini
    incubator/shiro/trunk/samples/quickstart/src/main/resources/shiro.ini
Modified:
    incubator/shiro/trunk/core/src/main/java/org/apache/shiro/config/Ini.java
    incubator/shiro/trunk/core/src/main/java/org/apache/shiro/config/IniSecurityManagerFactory.java
    incubator/shiro/trunk/core/src/main/java/org/apache/shiro/realm/text/IniRealm.java
    incubator/shiro/trunk/core/src/test/java/org/apache/shiro/config/IniSecurityManagerFactoryTest.java
    incubator/shiro/trunk/core/src/test/java/org/apache/shiro/realm/text/IniRealmTest.java
    incubator/shiro/trunk/samples/quickstart/src/main/java/Quickstart.java

Modified: incubator/shiro/trunk/core/src/main/java/org/apache/shiro/config/Ini.java
URL: http://svn.apache.org/viewvc/incubator/shiro/trunk/core/src/main/java/org/apache/shiro/config/Ini.java?rev=890398&r1=890397&r2=890398&view=diff
==============================================================================
--- incubator/shiro/trunk/core/src/main/java/org/apache/shiro/config/Ini.java (original)
+++ incubator/shiro/trunk/core/src/main/java/org/apache/shiro/config/Ini.java Mon Dec 14 16:40:39
2009
@@ -19,6 +19,7 @@
 package org.apache.shiro.config;
 
 import org.apache.shiro.io.ResourceUtils;
+import org.apache.shiro.util.CollectionUtils;
 import org.apache.shiro.util.StringUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -286,6 +287,23 @@
         return this.sections.hashCode();
     }
 
+    public String toString() {
+        if (CollectionUtils.isEmpty(this.sections)) {
+            return "<empty INI>";
+        } else {
+            StringBuilder sb = new StringBuilder("sections=");
+            int i = 0;
+            for (Ini.Section section : this.sections.values()) {
+                if (i > 0) {
+                    sb.append(",");
+                }
+                sb.append(section.toString());
+                i++;
+            }
+            return sb.toString();
+        }
+    }
+
     public int size() {
         return this.sections.size();
     }

Modified: incubator/shiro/trunk/core/src/main/java/org/apache/shiro/config/IniSecurityManagerFactory.java
URL: http://svn.apache.org/viewvc/incubator/shiro/trunk/core/src/main/java/org/apache/shiro/config/IniSecurityManagerFactory.java?rev=890398&r1=890397&r2=890398&view=diff
==============================================================================
--- incubator/shiro/trunk/core/src/main/java/org/apache/shiro/config/IniSecurityManagerFactory.java
(original)
+++ incubator/shiro/trunk/core/src/main/java/org/apache/shiro/config/IniSecurityManagerFactory.java
Mon Dec 14 16:40:39 2009
@@ -59,6 +59,10 @@
         super(config);
     }
 
+    public IniSecurityManagerFactory(String iniResourcePath) {
+        super(Ini.fromResourcePath(iniResourcePath));
+    }
+
     protected SecurityManager createInstance(Ini ini) {
         if (CollectionUtils.isEmpty(ini)) {
             throw new NullPointerException("Ini argument cannot be null or empty.");

Modified: incubator/shiro/trunk/core/src/main/java/org/apache/shiro/realm/text/IniRealm.java
URL: http://svn.apache.org/viewvc/incubator/shiro/trunk/core/src/main/java/org/apache/shiro/realm/text/IniRealm.java?rev=890398&r1=890397&r2=890398&view=diff
==============================================================================
--- incubator/shiro/trunk/core/src/main/java/org/apache/shiro/realm/text/IniRealm.java (original)
+++ incubator/shiro/trunk/core/src/main/java/org/apache/shiro/realm/text/IniRealm.java Mon
Dec 14 16:40:39 2009
@@ -58,6 +58,13 @@
         processDefinitions(ini);
     }
 
+    public IniRealm(String resourcePath) {
+        this();
+        Ini ini = Ini.fromResourcePath(resourcePath);
+        this.resourcePath = resourcePath;
+        processDefinitions(ini);
+    }
+
     public String getResourcePath() {
         return resourcePath;
     }
@@ -67,7 +74,7 @@
     }
 
     @Override
-    public void onInit() {
+    protected void onInit() {
         // We override init() instead of onInit() because we _don't_ want any caches to be
created
         // (see the superclass init() code).
         // This is an in-memory realm only - no need for an additional cache when we're already

Modified: incubator/shiro/trunk/core/src/test/java/org/apache/shiro/config/IniSecurityManagerFactoryTest.java
URL: http://svn.apache.org/viewvc/incubator/shiro/trunk/core/src/test/java/org/apache/shiro/config/IniSecurityManagerFactoryTest.java?rev=890398&r1=890397&r2=890398&view=diff
==============================================================================
--- incubator/shiro/trunk/core/src/test/java/org/apache/shiro/config/IniSecurityManagerFactoryTest.java
(original)
+++ incubator/shiro/trunk/core/src/test/java/org/apache/shiro/config/IniSecurityManagerFactoryTest.java
Mon Dec 14 16:40:39 2009
@@ -47,6 +47,15 @@
     }
 
     @Test
+    public void testGetInstanceWithResourcePath() {
+        String path = "classpath:org/apache/shiro/config/IniSecurityManagerFactoryTest.ini";
+        IniSecurityManagerFactory factory = new IniSecurityManagerFactory(path);
+        SecurityManager sm = factory.getInstance();
+        assertNotNull(sm);
+        assertTrue(sm instanceof DefaultSecurityManager);
+    }
+
+    @Test
     public void testGetInstanceWithEmptyIni() {
         Ini ini = new Ini();
         IniSecurityManagerFactory factory = new IniSecurityManagerFactory(ini);

Modified: incubator/shiro/trunk/core/src/test/java/org/apache/shiro/realm/text/IniRealmTest.java
URL: http://svn.apache.org/viewvc/incubator/shiro/trunk/core/src/test/java/org/apache/shiro/realm/text/IniRealmTest.java?rev=890398&r1=890397&r2=890398&view=diff
==============================================================================
--- incubator/shiro/trunk/core/src/test/java/org/apache/shiro/realm/text/IniRealmTest.java
(original)
+++ incubator/shiro/trunk/core/src/test/java/org/apache/shiro/realm/text/IniRealmTest.java
Mon Dec 14 16:40:39 2009
@@ -35,7 +35,7 @@
 
     @Test
     public void testNullIni() {
-        IniRealm realm = new IniRealm(null);
+        IniRealm realm = new IniRealm((Ini) null);
     }
 
     @Test

Added: incubator/shiro/trunk/core/src/test/resources/org/apache/shiro/config/IniSecurityManagerFactoryTest.ini
URL: http://svn.apache.org/viewvc/incubator/shiro/trunk/core/src/test/resources/org/apache/shiro/config/IniSecurityManagerFactoryTest.ini?rev=890398&view=auto
==============================================================================
--- incubator/shiro/trunk/core/src/test/resources/org/apache/shiro/config/IniSecurityManagerFactoryTest.ini
(added)
+++ incubator/shiro/trunk/core/src/test/resources/org/apache/shiro/config/IniSecurityManagerFactoryTest.ini
Mon Dec 14 16:40:39 2009
@@ -0,0 +1,24 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+[users]
+user1 = user1, admin
+
+[roles]
+admin = *
\ No newline at end of file

Modified: incubator/shiro/trunk/samples/quickstart/src/main/java/Quickstart.java
URL: http://svn.apache.org/viewvc/incubator/shiro/trunk/samples/quickstart/src/main/java/Quickstart.java?rev=890398&r1=890397&r2=890398&view=diff
==============================================================================
--- incubator/shiro/trunk/samples/quickstart/src/main/java/Quickstart.java (original)
+++ incubator/shiro/trunk/samples/quickstart/src/main/java/Quickstart.java Mon Dec 14 16:40:39
2009
@@ -19,15 +19,18 @@
 
 import org.apache.shiro.SecurityUtils;
 import org.apache.shiro.authc.*;
-import org.apache.shiro.mgt.DefaultSecurityManager;
-import org.apache.shiro.realm.text.PropertiesRealm;
+import org.apache.shiro.config.IniSecurityManagerFactory;
+import org.apache.shiro.mgt.SecurityManager;
 import org.apache.shiro.session.Session;
 import org.apache.shiro.subject.Subject;
+import org.apache.shiro.util.Factory;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 
 /**
+ * Simple Quickstart application showing how to use Shiro's API.
+ *
  * @author Les Hazlewood
  * @since 0.9 RC2
  */
@@ -36,78 +39,81 @@
     private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
 
 
-    public static void main( String[] args ) {
+    public static void main(String[] args) {
 
-        //Most applications would never instantiate a SecurityManager directly - you would
instead configure
-        //Shiro in web.xml or a container (JEE, Spring, etc).
-        //But, since this is a quickstart, we just want you to get a feel for how the Shiro
API looks, so this
-        //is sufficient to have a simple working example:
-        DefaultSecurityManager securityManager = new DefaultSecurityManager();
-        securityManager.setRealm(new PropertiesRealm());
+        // The easiest way to create a Shiro SecurityManager with configured
+        // realms, users, roles and permissions is to use the simple INI config.
+        // We'll do that by using a factory that can injest a .ini file and
+        // return a SecurityManager instance:
+
+        // Use the shiro.ini file at the root of the classpath
+        // (file: and url: prefixes load from files and urls respectively):
+        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
+        SecurityManager securityManager = factory.getInstance();
+
+        // for this simple example quickstart, make the SecurityManager
+        // accessible as a JVM singleton.  Most applications wouldn't do this
+        // and instead rely on their container configuration or web.xml for
+        // webapps.  That is outside the scope of this simple quickstart, so
+        // we'll just do the bare minimum so you can continue to get a feel
+        // for things.
+        SecurityUtils.setSecurityManager(securityManager);
 
-        //for this simple example quickstart, make the SecurityManager accessible across
the JVM.  Most
-        //applications wouldn't do this and instead rely on their container configuration
or web.xml for webapps.  That
-        //is outside the scope of this simple quickstart, so we'll just do the bare minimum
so you can continue to
-        //get a feel for things.
-        SecurityUtils.setSecurityManager( securityManager );
+        // Now that a simple Shiro environment is set up, let's see what you can do:
 
-
-        //now that a simple Shiro environment is set up, let's see what you can do:
-
-        //get the currently executing user:
+        // get the currently executing user:
         Subject currentUser = SecurityUtils.getSubject();
 
-        //Do some stuff with a Session (no need for a web or EJB container!!!)
+        // Do some stuff with a Session (no need for a web or EJB container!!!)
         Session session = currentUser.getSession();
-        session.setAttribute( "someKey", "aValue" );
-        String value = (String)session.getAttribute("someKey");
-        if ( value.equals( "aValue" ) ) {
-            log.info( "Retrieved the correct value! [" + value + "]" );
+        session.setAttribute("someKey", "aValue");
+        String value = (String) session.getAttribute("someKey");
+        if (value.equals("aValue")) {
+            log.info("Retrieved the correct value! [" + value + "]");
         }
 
-
-        //let's log in the current user so we can check against roles and permissions:
-        if ( !currentUser.isAuthenticated() ) {
-            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"
);
+        // let's login the current user so we can check against roles and permissions:
+        if (!currentUser.isAuthenticated()) {
+            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
             token.setRememberMe(true);
             try {
                 currentUser.login(token);
             } catch (UnknownAccountException uae) {
-                log.info( "There is no user with username of " + token.getPrincipal() );
-            } catch ( IncorrectCredentialsException ice ) {
+                log.info("There is no user with username of " + token.getPrincipal());
+            } catch (IncorrectCredentialsException ice) {
                 log.info("Password for account " + token.getPrincipal() + " was incorrect!");
-            } catch ( LockedAccountException lae ) {
+            } catch (LockedAccountException lae) {
                 log.info("The account for username " + token.getPrincipal() + " is locked.
 " +
-                         "Please contact your administrator to unlock it.");
+                        "Please contact your administrator to unlock it.");
             }
             // ... catch more exceptions here (maybe custom ones specific to your application?
-            catch ( AuthenticationException ae ) {
+            catch (AuthenticationException ae) {
                 //unexpected condition?  error?
             }
         }
 
         //say who they are:
         //print their identifying principal (in this case, a username):
-        log.info( "User [" + currentUser.getPrincipal() + "] logged in successfully." );
+        log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
 
         //test a role:
-        if ( currentUser.hasRole( "schwartz" ) ) {
-            log.info("May the Schwartz be with you!" );
+        if (currentUser.hasRole("schwartz")) {
+            log.info("May the Schwartz be with you!");
         } else {
-            log.info( "Hello, mere mortal." );
+            log.info("Hello, mere mortal.");
         }
 
         //test a typed permission (not instance-level)
-        if ( currentUser.isPermitted( "lightsaber:weild" ) ) {
+        if (currentUser.isPermitted("lightsaber:weild")) {
             log.info("You may use a lightsaber ring.  Use it wisely.");
         } else {
             log.info("Sorry, lightsaber rings are for schwartz masters only.");
         }
 
         //a (very powerful) Instance Level permission:
-        if ( currentUser.isPermitted( "winnebago:drive:eagle5" ) ) {
+        if (currentUser.isPermitted("winnebago:drive:eagle5")) {
             log.info("You are permitted to 'drive' the winnebago with license plate (id)
'eagle5'.  " +
-                     "Here are the keys - have fun!");
+                    "Here are the keys - have fun!");
         } else {
             log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
         }

Added: incubator/shiro/trunk/samples/quickstart/src/main/resources/shiro.ini
URL: http://svn.apache.org/viewvc/incubator/shiro/trunk/samples/quickstart/src/main/resources/shiro.ini?rev=890398&view=auto
==============================================================================
--- incubator/shiro/trunk/samples/quickstart/src/main/resources/shiro.ini (added)
+++ incubator/shiro/trunk/samples/quickstart/src/main/resources/shiro.ini Mon Dec 14 16:40:39
2009
@@ -0,0 +1,58 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+# =============================================================================
+# Quickstart INI Realm configuration
+#
+# For those that might not understand the references in this file, the
+# definitions are all based on the classic Mel Brooks' film "Spaceballs". ;)
+# =============================================================================
+
+# -----------------------------------------------------------------------------
+# Users and their assigned roles
+#
+# Each line conforms to the format defined in the
+# org.apache.shiro.realm.text.TextConfigurationRealm#setUserDefinitions JavaDoc
+# -----------------------------------------------------------------------------
+[users]
+# user 'admin' with password 'secret' and the 'root' role
+admin = secret, admin
+# user 'guest' with the password 'guest' and the 'guest' role
+guest = guest, guest
+# user 'presidentskroob' with password '12345' ("That's the same combination on
+# my luggage!!!" ;)), and role 'president'
+presidentskroob = 12345, president
+# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
+darkhelmet = ludicrousspeed, darklord, schwartz
+# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
+lonestarr = vespa, goodguy, schwartz
+
+# -----------------------------------------------------------------------------
+# Roles with assigned permissions
+# 
+# Each line conforms to the format defined in the
+# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
+# -----------------------------------------------------------------------------
+[roles]
+# 'admin' role has all permissions, indicated by the wildcard '*'
+admin = *
+# The 'schwartz' role can do anything (*) with any lightsaber:
+schwartz = lightsaber:*
+# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
+# license plate 'eagle5' (instance specific id)
+goodguy = winnebago:drive:eagle5



Mime
View raw message