Example usage for org.apache.shiro SecurityUtils setSecurityManager

List of usage examples for org.apache.shiro SecurityUtils setSecurityManager

Introduction

In this page you can find the example usage for org.apache.shiro SecurityUtils setSecurityManager.

Prototype

public static void setSecurityManager(SecurityManager securityManager) 

Source Link

Document

Sets a VM (static) singleton SecurityManager, specifically for transparent use in the #getSubject() getSubject() implementation.

Usage

From source file:com.rainy.shiro.demo.Standalone.java

License:Apache License

public static void main(String[] args) {

    //        IniConfiguration config = new IniConfiguration();
    //        //the following call will automatically use shiro.ini at the root of the classpath:
    //        config.init();
    //        // w  w w .  j  ava 2  s  . c o  m
    //        //This is for Standalone (single-VM) applications that don't use a configuration container (Spring, JBoss, etc)
    //        //See its JavaDoc for our feelings on this.
    //        SecurityUtils.setSecurityManager(config.getSecurityManager());

    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
    SecurityManager securityManager = factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);
    //Now you are ready to access the Subject, as shown in the Quickstart:
    Subject currentUser = SecurityUtils.getSubject();
    //anything else you want to do with the Subject (see the Quickstart for examples).
    currentUser.logout();
    System.exit(0);
}

From source file:com.seelecloud.cms.shirotest.ShiroTest.java

License:Apache License

public static void main(String[] args) {

    log.info("My First Apache Shiro Application");

    @SuppressWarnings("resource")
    ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "classpath:/spring.xml",
            "classpath:/spring-mybatis.xml", "classpath:/spring-shiro.xml" });

    //       Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
    //       SecurityManager securityManager = factory.getInstance();
    SecurityManager securityManager = (SecurityManager) context.getBean("securityManager");
    SecurityUtils.setSecurityManager(securityManager);

    // get the currently executing user:
    Subject currentUser = SecurityUtils.getSubject();

    //        Session session = currentUser.getSession(true);
    //        //  w ww. j a  v  a2s  . c  om
    //        session.setAttribute("administrator", "123456");
    //        String value = (String) session.getAttribute("administrator");
    //        if (value.equals("123456")) {
    //            log.info("Retrieved the correct value! [" + value + "]");
    //        }

    // let's login the current user so we can check against roles and permissions:
    if (!currentUser.isAuthenticated()) {
        UsernamePasswordToken token = new UsernamePasswordToken("administrator", "123456");
        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("Password for account " + token.getPrincipal() + " was incorrect!");
        } catch (LockedAccountException lae) {
            log.info("The account for username " + token.getPrincipal() + " is locked.  "
                    + "Please contact your administrator to unlock it.");
        }
        // ... catch more exceptions here (maybe custom ones specific to your application?
        catch (AuthenticationException ae) {
            //unexpected condition?  error?
        }
    } else {
        log.info("user has authc!");
    }

    if (currentUser.isAuthenticated()) {
        log.info("authc");
    } else {
        log.info("no authc");
    }

    log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

    //test a role:
    if (currentUser.hasRole("?")) {
        log.info("role has authz!");
    } else {
        log.info("no role !");
    }

    currentUser.logout();

    System.exit(0);
}

From source file:com.sff.hello.Quickstart.java

public static void main(String[] args) {

    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
    SecurityManager securityManager = factory.getInstance();

    SecurityUtils.setSecurityManager(securityManager);

    // ?? Subject.  SecurityUtils.getSubject();
    Subject currentUser = SecurityUtils.getSubject();

    // Do some stuff with a Session (no need for a web or EJB container!!!)
    //  Session //from  w  ww. ja v  a 2s .c o  m
    // ? Session: Subject#getSession()
    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 + "]");
    }

    // let's login the current user so we can check against roles and permissions:
    // ????. ???. 
    //  Subject  isAuthenticated() 
    if (!currentUser.isAuthenticated()) {
        // ???? UsernamePasswordToken 
        UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
        // rememberme
        token.setRememberMe(true);
        try {
            // .
            currentUser.login(token);
        }
        // ,  shiro  UnknownAccountException . 
        catch (UnknownAccountException uae) {
            log.info("----> There is no user with username of " + token.getPrincipal());
            return;
        }
        // , ???,  shiro  IncorrectCredentialsException  
        catch (IncorrectCredentialsException ice) {
            log.info("----> Password for account " + token.getPrincipal() + " was incorrect!");
            return;
        }
        // ? LockedAccountException
        catch (LockedAccountException lae) {
            log.info("The account for username " + token.getPrincipal() + " is locked.  "
                    + "Please contact your administrator to unlock it.");
        }
        // ... catch more exceptions here (maybe custom ones specific to your application?
        // ?. 
        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.");

    //test a role:
    // ??.  Subject  hasRole . 
    if (currentUser.hasRole("schwartz")) {
        log.info("----> May the Schwartz be with you!");
    } else {
        log.info("----> Hello, mere mortal.");
        return;
    }

    //test a typed permission (not instance-level)
    // ??.  Subject  isPermitted()  
    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("user:delete:zhangsan")) {
        log.info("----> You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  "
                + "Here are the keys - have fun!");
    } else {
        log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
    }

    //all done - log out!
    // .  Subject  Logout() . 
    System.out.println("---->" + currentUser.isAuthenticated());

    currentUser.logout();

    System.out.println("---->" + currentUser.isAuthenticated());

    System.exit(0);
}

From source file:com.shiro.helloworld.Quickstart.java

public static void main(String[] args) {

    // 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 ingest 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);

    // Now that a simple Shiro environment is set up, let's see what you can do:

    // get the currently executing user:
    // 1. ?? Subject( Shiro ),  SecurityUtils.getSubject() . 
    Subject currentUser = SecurityUtils.getSubject();

    // Do some stuff with a Session (no need for a web or EJB container!!!)
    // :  Session. 
    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 + "]");
    }// w w w.j  a v a 2s  .co  m

    // let's login the current user so we can check against roles and permissions:
    //2. ????. ??.  Subject  isAuthenticated() . 
    if (!currentUser.isAuthenticated()) {
        //3. ???? UsernamePasswordToken . 
        UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
        token.setRememberMe(true);
        try {
            //4. .  Subject  login(AuthenticationToken).  UsernamePasswordToken 
            // UsernamePasswordToken  AuthenticationToken . 
            currentUser.login(token);
        }
        //5. ???,  UnknownAccountException . 
        catch (UnknownAccountException uae) {
            log.info("--> There is no user with username of " + token.getPrincipal());
            return;
        }
        //6. ??, ???,  IncorrectCredentialsException . 
        catch (IncorrectCredentialsException ice) {
            log.info("--> Password for account " + token.getPrincipal() + " was incorrect!");
            return;
        }
        //7. ?,  LockedAccountException . ? Realm .
        //?. 
        catch (LockedAccountException lae) {
            log.info("The account for username " + token.getPrincipal() + " is locked.  "
                    + "Please contact your administrator to unlock it.");
        }
        // ... catch more exceptions here (maybe custom ones specific to your application?
        //8. ?. ????. 
        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.");

    //test a role:
    //9. ???? ???. 
    if (currentUser.hasRole("schwartz")) {
        log.info("--> May the Schwartz be with you!");
    } else {
        log.info("Hello, mere mortal.");
    }

    //test a typed permission (not instance-level)
    //10. ???
    // lightsaber:* ?? lightsaber ??. 
    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:
    //11. user:query:zhangsan ?? user  zhangsan ? query ?. 
    if (currentUser.isPermitted("user:query:zhangsan")) {
        log.info("--> You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  "
                + "Here are the keys - have fun!");
    } else {
        log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
    }

    //all done - log out!
    //12. . 
    currentUser.logout();

    System.exit(0);
}

From source file:com.shiro.test.Quickstart.java

License:Apache License

public static void main(String[] args) {

    com.javalego.security.SecurityContext.getCurrent().setServices(new SecurityShiro("classpath:shiro.ini"));
    try {/*from w  ww  .  j  av  a 2  s  . co m*/
        com.javalego.security.SecurityContext.getCurrent().getServices().login("lonestarr", "vespa");
        System.out
                .println(com.javalego.security.SecurityContext.getCurrent().getServices().hasRole("schwartz"));
    } catch (LocalizedException e) {
        log.error(e.getMessage());
    }
    System.exit(0);

    // 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 ingest 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);

    // Now that a simple Shiro environment is set up, let's see what you can do:

    // get the currently executing user:
    Subject currentUser = SecurityUtils.getSubject();

    // 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 + "]");
    }

    // 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("Password for account " + token.getPrincipal() + " was incorrect!");
        } catch (LockedAccountException lae) {
            log.info("The account for username " + token.getPrincipal() + " is locked.  "
                    + "Please contact your administrator to unlock it.");
        }
        // ... catch more exceptions here (maybe custom ones specific to your application?
        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.");

    //test a role:
    if (currentUser.hasRole("schwartz")) {
        log.info("May the Schwartz be with you!");
    } else {
        log.info("Hello, mere mortal.");
    }

    //test a typed permission (not instance-level)
    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")) {
        log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  "
                + "Here are the keys - have fun!");
    } else {
        log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
    }

    //all done - log out!
    currentUser.logout();

    System.exit(0);
}

From source file:com.shrio.demo.quickstart.Quickstart.java

public static void main(String[] args) {

    // 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 ingest 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.properties");
    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);

    // Now that a simple Shiro environment is set up, let's see what you can do:

    // get the currently executing user:
    Subject currentUser = SecurityUtils.getSubject();

    // 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 + "]");
    }/*from  ww  w . j  a v  a2 s  .c om*/

    // 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("Password for account " + token.getPrincipal() + " was incorrect!");
        } catch (LockedAccountException lae) {
            log.info("The account for username " + token.getPrincipal() + " is locked.  "
                    + "Please contact your administrator to unlock it.");
        }
        // ... catch more exceptions here (maybe custom ones specific to your application?
        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.");

    //test a role:
    if (currentUser.hasRole("schwartz")) {
        log.info("May the Schwartz be with you!");
    } else {
        log.info("Hello, mere mortal.");
    }

    //test a typed permission (not instance-level)
    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")) {
        log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  "
                + "Here are the keys - have fun!");
    } else {
        log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
    }

    //all done - log out!
    currentUser.logout();

    System.exit(0);
}

From source file:com.snail.controller.test.JdbcReamTest.java

public static void main(String[] args) {

    System.out.println("Hello shiro!");

    MysqlDataSource datasource = new MysqlDataSource();
    datasource.setUser("root");
    datasource.setPassword("12345");
    datasource.setServerName("localhost");
    // datasource.setDriverClassName("com.mysql.jdbc.Driver");
    datasource.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8");
    // datasource.setMaxActive(10);

    org.apache.shiro.realm.jdbc.JdbcRealm jdbcRealm = new JdbcRealm();
    jdbcRealm.setDataSource(datasource);
    jdbcRealm.setPermissionsLookupEnabled(true);
    jdbcRealm.setAuthenticationQuery("SELECT password FROM users WHERE username = ?");
    jdbcRealm.setUserRolesQuery("SELECT rolename FROM user_roles WHERE username= ?");
    jdbcRealm.setPermissionsQuery("SELECT permission FROM user_permissions WHERE rolename= ?");
    //      jdbcRealm
    //            .setPermissionsQuery("SELECT NAME FROM permission WHERE id in (SELECT permissionId FROM permission_role WHERE (SELECT id FROM role WHERE NAME = ?))");
    DefaultSecurityManager security = new DefaultSecurityManager(jdbcRealm);
    SecurityUtils.setSecurityManager(security);
    Subject currentUser = SecurityUtils.getSubject();
    if (!currentUser.isAuthenticated()) {
        //lilei/*from  ww w  . jav  a 2 s  . c o  m*/
        UsernamePasswordToken token = new UsernamePasswordToken("lilei", "1234");
        token.setRememberMe(true);
        try {
            currentUser.login(token);
            System.out.println("login successfully");
        } catch (UnknownAccountException uae) {
            System.out.println("There is no user with username of " + token.getPrincipal());
        } catch (IncorrectCredentialsException ice) {
            System.out.println("Password for account " + token.getPrincipal() + " was incorrect!");
        } catch (LockedAccountException lae) {
            System.out.println("The account for username " + token.getPrincipal() + " is locked.  "
                    + "Please contact your administrator to unlock it.");
        }
        // ... catch more exceptions here (maybe custom ones specific to
        // your application?
        catch (AuthenticationException ae) {
            // unexpected condition? error?
        }
    }
    // say who they are:
    // print their identifying principal (in this case, a username):
    System.out.println("User [" + currentUser.getPrincipal() + "] logged in successfully.");
    // test a role:
    if (currentUser.hasRole("admin")) {
        System.out.println("May the admin be with you!");
    } else {
        System.out.println("Hello, mere mortal.");
    }

    // test a typed permission (not instance-level)

    if (currentUser.isPermitted("write")) {
        System.out.println("You can write!.");
    } else {

        System.out.println("Sorry, lightsaber rings are for schwartz masters only.");
    }
    // a (very powerful) Instance Level permission: TODO
    if (currentUser.isPermitted("winnebago:drive:eagle5")) {
        System.out.println("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  "
                + "Here are the keys - have fun!");
    } else {
        System.out.println("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
    }
    // all done - log out!
    currentUser.logout();
}

From source file:com.stormpath.shiro.examples.Quickstart.java

License:Apache License

@SuppressWarnings("Duplicates")
public static void main(String[] args) {

    // 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 ingest 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);

    // get the currently executing user:
    Subject currentUser = SecurityUtils.getSubject();

    // At this point is it not possible to provide an example user.
    // If you are new to Shiro please take a look at this example:
    // https://github.com/apache/shiro/blob/1.3.x/samples/quickstart/src/main/java/Quickstart.java
    // for details on basic usage.

    // We know the user is not authenticated yet, but this is how you would check.
    if (!currentUser.isAuthenticated()) {
        // If you want following code to succeed, you will need to create a user with id 'lonestarr'
        // and password 'vespa' in your application.
        String username = "lonestarr";
        UsernamePasswordToken token = new UsernamePasswordToken(username, "vespa");

        try {/*www.ja  va2s. co m*/
            currentUser.login(token);
        } catch (AuthenticationException ae) {
            log.info("Login for user [{}] failed.", username);
        }
    }
}

From source file:com.studyshiro.helloworld.Hello.java

public static void main(String[] args) {
    //1??SecurityManagerIni??SecurityManager
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:hello.ini");
    //2?SecurityManager SecurityUtils
    SecurityManager securityManager = factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);

    // ?? Subject.  SecurityUtils.getSubject();
    Subject currentUser = SecurityUtils.getSubject();

    //  Session//from  w w  w  .j a  va2 s  .co  m
    // ? Session: Subject#getSession()
    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 + "]");
    }

    // ????. ???. ???
    //  Subject  isAuthenticated()
    if (!currentUser.isAuthenticated()) {
        // ???? UsernamePasswordToken 
        UsernamePasswordToken token = new UsernamePasswordToken("Zhang", "123456");
        // rememberme
        token.setRememberMe(true);
        try {
            // .
            currentUser.login(token);
        }
        // ,  shiro  UnknownAccountException .
        catch (UnknownAccountException uae) {
            log.info("----> There is no user with username of " + token.getPrincipal());
            return;
        }
        // , ???,  shiro  IncorrectCredentialsException 
        catch (IncorrectCredentialsException ice) {
            log.info("----> Password for account " + token.getPrincipal() + " was incorrect!");
            return;
        }
        // ? LockedAccountException
        catch (LockedAccountException lae) {
            log.info("The account for username " + token.getPrincipal() + " is locked.  "
                    + "Please contact your administrator to unlock it.");
        }
        // ... catch more exceptions here (maybe custom ones specific to your application?
        // ?.
        catch (AuthenticationException ae) {
            //unexpected condition?  error?
        }
    }
    //say who they are:
    //print their identifying principal (in this case, a username):
    //principals????????principals?Primary principals??/?/?
    log.info("----> User [" + currentUser.getPrincipal() + "] logged in successfully.");

    //test a role:
    // ??.  Subject  hasRole .
    if (currentUser.hasRole("roleStudent")) {
        log.info("----> May the roleStudent be with you!");
    } else {
        log.info("----> Hello, mere mortal.");
        return;
    }

    //test a typed permission (not instance-level)
    // ??.  Subject  isPermitted() 
    if (currentUser.isPermitted("wc:testContent")) {
        log.info("----> You may use a wc ring.  Use it wisely.");
    } else {
        log.info("Sorry, wc rings are for roleStudent masters only.");
    }

    //a (very powerful) Instance Level permission:
    // ??.
    if (currentUser.isPermitted("user:delete:zhaochunyu")) {
        log.info("----> You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  "
                + "Here are the keys - have fun!");
    } else {
        log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
    }

    //all done - log out!
    // .  Subject  Logout() . ---->true
    System.out.println("---->" + currentUser.isAuthenticated());
    //
    currentUser.logout();

    //---->false
    System.out.println("---->" + currentUser.isAuthenticated());

    System.exit(0);
}

From source file:com.test.Quickstart.java

License:Apache License

public static void main(String[] args) {

    // 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 ingest 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);

    // Now that a simple Shiro environment is set up, let's see what you can do:

    // get the currently executing user:
    Subject currentUser = SecurityUtils.getSubject();

    // 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")) {
        System.out.println("Retrieved the correct value! [" + value + "]");
    }//ww w  . jav  a2s .com

    // 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) {
            System.out.println("There is no user with username of " + token.getPrincipal());
        } catch (IncorrectCredentialsException ice) {
            System.out.println("Password for account " + token.getPrincipal() + " was incorrect!");
        } catch (LockedAccountException lae) {
            System.out.println("The account for username " + token.getPrincipal() + " is locked.  "
                    + "Please contact your administrator to unlock it.");
        }
        // ... catch more exceptions here (maybe custom ones specific to your application?
        catch (AuthenticationException ae) {
            //unexpected condition?  error?
        }
    }

    //say who they are:
    //print their identifying principal (in this case, a username):
    System.out.println("User [" + currentUser.getPrincipal() + "] logged in successfully.");

    //test a role:
    if (currentUser.hasRole("schwartz")) {
        System.out.println("May the Schwartz be with you!");
    } else {
        System.out.println("Hello, mere mortal.");
    }

    //test a typed permission (not instance-level)
    if (currentUser.isPermitted("lightsaber:weild")) {
        System.out.println("You may use a lightsaber ring.  Use it wisely.");
    } else {
        System.out.println("Sorry, lightsaber rings are for schwartz masters only.");
    }

    //a (very powerful) Instance Level permission:
    if (currentUser.isPermitted("winnebago:drive:eagle5")) {
        System.out.println("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  "
                + "Here are the keys - have fun!");
    } else {
        System.out.println("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
    }

    if (currentUser.isPermitted("winnebago:drive")) {
        System.out.println("drive");
    } else {
        System.out.println("no drive");
    }
    //all done - log out!
    currentUser.logout();

    System.exit(0);
}