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.wegas.core.security.util.SecurityProducer.java

License:MIT License

/**
 *
 *///from  w ww.  j a v  a  2  s  . c  o m
public void init() {
    final String iniFile = "classpath:shiro.ini";
    logger.info("Initializing Shiro INI SecurityManager using " + iniFile);
    securityManager = new IniSecurityManagerFactory(iniFile).getInstance();
    SecurityUtils.setSecurityManager(securityManager);
}

From source file:com.wegas.unit.AbstractEJBContainerTest.java

License:MIT License

@BeforeClass
public static void setUp() throws Exception {
    Map<String, Object> properties = new HashMap<>(); // Init Ejb container
    properties.put(EJBContainer.MODULES, new File[] { new File("../wegas-core/target/embed-classes") });
    properties.put("org.glassfish.ejb.embedded.glassfish.installation.root",
            "../wegas-core/src/test/glassfish");
    //properties.put(EJBContainer.APP_NAME,"class");
    //ejbContainer.getContext().rebind("inject", this);

    // Init shiro
    SecurityUtils.setSecurityManager(new IniSecurityManagerFactory("classpath:shiro.ini").getInstance());

    /* Log Levels */
    Logger.getLogger("javax.enterprise.system.tools.deployment").setLevel(Level.SEVERE);
    Logger.getLogger("javax.enterprise.system").setLevel(Level.SEVERE);
    org.glassfish.ejb.LogFacade.getLogger().setLevel(Level.SEVERE);

    container = EJBContainer.createEJBContainer(properties);
    Helper.lookupBy(container.getContext(), UserFacade.class, UserFacade.class).guestLogin(); //login as guest

    gmFacade = Helper.lookupBy(container.getContext(), GameModelFacade.class, GameModelFacade.class);
}

From source file:com.wordpress.infow.shiro.hw.HelloWorld.java

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

    // 1. Ingest shiro.ini file
    Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory(
            "classpath:shiro.ini"); // Other options:
    // [url:, file:]

    // 2. Return a security manager based on our shiro.ini
    org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();

    // 3. set the SecurityManager to be a static (memory) singleton
    SecurityUtils.setSecurityManager(securityManager);

    // 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")) {
        HelloWorld.log.info("Retrieved the correct value! [" + value + "]");
    }/* www. java  2 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("lonestarr", "vespa");
        token.setRememberMe(true);
        try {
            currentUser.login(token);
        } catch (UnknownAccountException uae) {
            HelloWorld.log.info("There is no user with username of " + token.getPrincipal());
        } catch (IncorrectCredentialsException ice) {
            HelloWorld.log.info("Password for account " + token.getPrincipal() + " was incorrect!");
        } catch (LockedAccountException lae) {
            HelloWorld.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):
    HelloWorld.log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

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

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

    // a (very powerful) Instance Level permission:
    if (currentUser.isPermitted("winnebago:drive:eagle5")) {
        HelloWorld.log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  "
                + "Here are the keys - have fun!");
    } else {
        HelloWorld.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.xiaofong.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):

    // 1 SecurityManager Ini SecurityManager
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");

    // 2SecurityManager SecurityUtils
    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 + "]");
    }/*from w  w w  .jav  a2  s  .  com*/

    // 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:com.xjsaber.shiro.getstart.Tutorial.java

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

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

    // ? SecurityManager
    SecurityUtils.setSecurityManager(securityManager);

    // 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 ("aValue".equals(value)) {
        log.info("Retrieved the correct value! [" + value + "]");
    }//  w  w w . ja v a 2s.  c o m

    // 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.xzy.test.Quickstart.java

public static void main(String[] args) {

    //System.out.println(ClassLoader.getSystemResource(""));
    //System.out.println(new File(".").getAbsolutePath());
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("src/main/java/com/xzy/test/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 + "]");
    }//  w  ww .  j a va 2s .  co m

    // 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.yimeicloud.study.shiro.QuickStart.java

@Test
public void runTest() {
    // ?SecurityManagerini??SecurityManager
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
    // ?SecurityManagerSecurityUtils
    SecurityManager securityManager = factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);

    // ??//  w  w  w . j ava  2s  .c o  m
    Subject currentUser = SecurityUtils.getSubject();
    // ?session
    Session session = currentUser.getSession();
    session.setAttribute("someKey", "aValue");
    String value = (String) session.getAttribute("someKey");
    if ("aValue".equals(value)) {
        log.info("Retrieved the correct value![" + value + "]");
    }

    // ?
    UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");

    // 
    try {
        currentUser.login(token);
    } catch (UnknownAccountException e) {
        log.info("??");
    } catch (IncorrectCredentialsException e) {
        log.info("?");
    } catch (LockedAccountException e) {
        log.info("??");
    } catch (AuthenticationException e) {
        log.info("?");
    }

    // ?
    if (currentUser.isAuthenticated()) {
        log.info("?...");
    } else {
        log.info("?...");
    }

    // test role
    if (currentUser.hasRole("goodguy")) {
        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!");
    }

    // 
    currentUser.logout();
}

From source file:com.zhengxuetao.shiro.Login.java

public void login(String configPath, String account, String pwd) {
    //1?? SecurityManager  Ini ?? SecurityManager
    Factory<SecurityManager> factory = new IniSecurityManagerFactory(configPath); //src/main/resources?classpath:???
    //2? SecurityManager   SecurityUtils
    SecurityManager securityManager = factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);
    //3? Subject ???/?? Token?/?
    Subject subject = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(account, pwd);

    try {//from w w w .  j  av a2  s.  c om
        //4???
        subject.login(token);
    } catch (AuthenticationException e) {
        //5??
        e.printStackTrace();
        System.out.println("");
        throw e;
    }
    if (subject.isAuthenticated()) { //?
        System.out.println(account + "?");
    }
}

From source file:com.zhengxuetao.shiro.LoginFromDB.java

public void testLogin(String account, String pwd) {
    //1?? SecurityManager  Ini ?? SecurityManager
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-jdbc-realm.ini"); //src/main/resources?classpath:???
    //2? SecurityManager   SecurityUtils
    SecurityManager securityManager = factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);
    //3? Subject ???/?? Token?/?
    Subject subject = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(account, pwd);

    try {//from   w  w  w  .  j a v  a2 s.  c om
        //4???
        subject.login(token);
    } catch (AuthenticationException e) {
        //5??
        e.printStackTrace();
        System.out.println("");
        throw e;
    }
    if (subject.isAuthenticated()) { //?
        System.out.println(account + "?");
    }
    //6?
    subject.logout();
}

From source file:com.zhengxuetao.shiro.LoginFromFile.java

public void testLogin(String account, String pwd) {
    //1?? SecurityManager  Ini ?? SecurityManager
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); //src/main/resources?classpath:???
    //2? SecurityManager   SecurityUtils
    SecurityManager securityManager = factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);
    //3? Subject ???/?? Token?/?
    Subject subject = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(account, pwd);

    try {/*from w  w w. j a v  a  2  s  .c o  m*/
        //4???
        subject.login(token);
    } catch (AuthenticationException e) {
        //5??
        System.out.println("");
        throw e;
    }
    if (subject.isAuthenticated()) { //?
        System.out.println(account + "?");
    }
    //6?
    subject.logout();
}