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:ch.reboundsoft.shinobi.authstore.CachedAuthStoreImpl.java

@Inject
public CachedAuthStoreImpl(ShinobiSecurityManager securityManager) {
    this.subjects = new HashMap<>();
    SecurityUtils.setSecurityManager(securityManager.getSecurityManager());
}

From source file:ch.reboundsoft.shinobi.authstore.DefaultAuthStoreImpl.java

@Inject
public DefaultAuthStoreImpl(ShinobiSecurityManager securityManager) {

    this.subjects = new HashMap<>();
    SecurityUtils.setSecurityManager(securityManager.getSecurityManager());
}

From source file:cn.cjam.test.TestShiro.java

public static void main(String[] args) {
    log.info("My First Apache Shiro Application");

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

    // ??://  w ww  . j  av a  2 s.c o m
    Subject currentUser = SecurityUtils.getSubject();

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

    // ???
    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 (AuthenticationException ae) {
            //??
        }
    }

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

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

    //?? (?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.");
    }

    //(?)??:
    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!");
    }

    //? - t!
    currentUser.logout();

    System.exit(0);
}

From source file:cn.fh.starter.shiro.autoconfigure.ShiroManager.java

License:Apache License

@Bean(name = "securityManager")
@ConditionalOnMissingBean//from   w  w  w.  ja v  a2s.c o m
public DefaultSecurityManager securityManager(CacheManager shiroCacheManager) {
    DefaultWebSecurityManager dwsm = new DefaultWebSecurityManager();

    // Factory?
    // session
    dwsm.setSubjectFactory(new StatelessSubjectFactory());
    dwsm.setSessionManager(defaultSessionManager());
    // session
    ((DefaultSessionStorageEvaluator) ((DefaultSubjectDAO) dwsm.getSubjectDAO()).getSessionStorageEvaluator())
            .setSessionStorageEnabled(false);

    //      <!-- ?/??Cache, EhCache  -->
    dwsm.setCacheManager(shiroCacheManager);

    SecurityUtils.setSecurityManager(dwsm);
    return dwsm;
}

From source file:cn.heweiming.webjars.learn.shiro.ShiroDemo02.java

public static void main(String[] args) {
    logger.info("My First Apache Shiro Application");

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

    // get the curretnly 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 ("aValue".equals(value)) {
        logger.info("Retrieved the correct value! [" + value + "]");
    }//from w ww .java  2 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) {
            logger.info("There is no user with username of " + token.getPrincipal());
        } catch (IncorrectCredentialsException ice) {
            logger.info("Password for account " + token.getPrincipal() + " was incorrent!");
        } catch (LockedAccountException lae) {
            logger.info("The account for username " + token.getPrincipal() + " is locked . "
                    + " Please contact your administrator to unlock it.");
        } catch (AuthenticationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    // say who they are:
    // print their identifying principal (int this case, a username):
    logger.info("User [" + currentUser.getPrincipal() + "]");

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

    // test a typed permissions (not isstance-level)
    if (currentUser.isPermitted("lightsaber:weild")) {
        logger.info("You may use a lightsaber ring. Use is wisely.");
    } else {
        logger.info("Sorry, lightsaber rings are for schwartz masters only.");
    }

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

    // all done - log out!
    currentUser.logout();
    System.exit(0);
}

From source file:cn.hh.study.shiro.QuickStart.java

public static void main(String[] args) {
    // Using the IniSecurityManagerFactory, which will use the an INI file
    // as the security file.
    //  ini ?? ?(IniSecurityManagerFactory)
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");

    // Setting up the SecurityManager...
    SecurityManager securityManager = factory.getInstance();
    // SecurityUtils  singleton???????
    // ? SecurityManager
    // ???? SecurityUtils.getSubject() ???
    SecurityUtils.setSecurityManager(securityManager);

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

    logger.info("User is authenticated:  " + currentUser.isAuthenticated());

    // 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")) {
        logger.info("Retrieved the correct value! [" + value + "]");
    }/*from  w  ww . ja  va2  s  .  c o  m*/

    // let's login the current user so we can check against roles and
    // permissions:
    if (!currentUser.isAuthenticated()) {
        // 
        UsernamePasswordToken token = new UsernamePasswordToken("presidentskroob", "12345");
        token.setRememberMe(true);
        try {
            currentUser.login(token);// 
        } catch (UnknownAccountException uae) {
            logger.info("There is no user with username of " + token.getPrincipal());
        } catch (IncorrectCredentialsException ice) {
            logger.info("Password for account " + token.getPrincipal() + " was incorrect!");
        } catch (LockedAccountException lae) {
            logger.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):
    logger.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

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

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

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

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

}

From source file:cn.hlj.shiro.helloworld.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 .  SecurityUtils.getSubject() . 
    Subject currentUser = SecurityUtils.getSubject();

    // Do some stuff with a Session (no need for a web or EJB container!!!)
    //  WEB  EJB  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  ww  . j ava  2s.c  om*/

    // let's login the current user so we can check against roles and permissions:
    // ??. ??. 
    if (!currentUser.isAuthenticated()) {
        // ???? UsernamePasswordToken . 
        UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
        token.setRememberMe(true);
        try {
            // ?. ??? Shiro ?. 
            currentUser.login(token);
        }
        // ???,  UnknownAccountException . 
        // ? UsernamePasswordToken  token.getPrincipal() ???
        catch (UnknownAccountException uae) {
            log.info("--> There is no user with username of " + token.getPrincipal());
            return;
        }
        // ?????,  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?
        // ? AuthenticationException ?
        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.");
        return;
    }

    //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:
    // ????. 
    // ?? User  zs  query
    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:cnki.shiro.helloworld.JdbcRelamTest.java

public static void main(String[] args) {

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

    MysqlDataSource datasource = new MysqlDataSource();

    datasource.setUser("cnki");

    datasource.setPassword("cnki");

    datasource.setServerName("192.168.100.51");

    // datasource.setDriverClassName("com.mysql.jdbc.Driver");

    datasource.setUrl("jdbc:mysql://192.168.100.51:3306/test");

    // datasource.setMaxActive(10);

    org.apache.shiro.realm.jdbc.JdbcRealm jdbcRealm = new JdbcRealm();

    jdbcRealm.setDataSource(datasource);

    jdbcRealm.setPermissionsLookupEnabled(true);

    jdbcRealm.setAuthenticationQuery("SELECT PASSWORD FROM account WHERE name = ?");

    jdbcRealm.setUserRolesQuery(/*from  www  . java2 s .  com*/
            "SELECT NAME FROM role WHERE id =(SELECT roleId FROM account_role WHERE userId = (SELECT id FROM account WHERE NAME = ?))");

    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()) {

        UsernamePasswordToken token = new UsernamePasswordToken("ynp", "2222");

        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:

    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:co.paralleluniverse.fibers.shiro.FiberShiroRealmTest.java

License:Open Source License

@Test
public void testSingleRealm() throws ExecutionException, InterruptedException {
    final IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro-single-realm.ini");
    final SecurityManager securityManager = factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);

    final Boolean authed = FiberUtil.runInFiber(new SuspendableCallable<Boolean>() {
        @Override/*from w ww  .j  a v a  2  s . c o  m*/
        public Boolean run() throws SuspendExecution, InterruptedException {
            SecurityUtils.getSubject().login(new UsernamePasswordToken("test", "test"));
            return SecurityUtils.getSubject().isAuthenticated() && SecurityUtils.getSubject().hasRole("roleA")
                    && SecurityUtils.getSubject().isPermitted("resource:actionA");
        }
    });
    assertTrue(authed);
}

From source file:co.paralleluniverse.fibers.shiro.FiberShiroRealmTest.java

License:Open Source License

@Test
public void testMultiRealm() throws ExecutionException, InterruptedException {
    final IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro-multi-realm.ini");
    final SecurityManager securityManager = factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);

    final Boolean authed = FiberUtil.runInFiber(new SuspendableCallable<Boolean>() {
        @Override//  www . jav  a2s.  com
        public Boolean run() throws SuspendExecution, InterruptedException {
            SecurityUtils.getSubject().login(new UsernamePasswordToken("test", "test"));
            return SecurityUtils.getSubject().isAuthenticated() && SecurityUtils.getSubject().hasRole("roleA")
                    && SecurityUtils.getSubject().isPermitted("resource:actionA");
        }
    });
    assertTrue(authed);
}