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:Homework4ShiroCommandLineClient.java

/**
 * @param args//from ww w .j  a va  2  s.c o m
 */
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);

    Subject currentUser = SecurityUtils.getSubject();

    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?
        }
    }

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

    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!");
    }

    currentUser.logout();

    System.exit(0);
}

From source file:Tutorial.java

public static void main(String[] args) {
    log.info(// ww  w.  jav a 2 s .  c o  m
            "\n\n\n\t\t\t**************************************************\n\t\t\t\tMy First Apache Shiro Application\n\t\t\t**************************************************\n");

    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
    //Factory<SecurityManager> factory = new IniSecurityManagerFactory("file:src/main/webapp/WEB-INF/shiro.ini");
    SecurityManager securityManager = factory.getInstance();
    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")) {
        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();
    log.info("User Logged out successfully!!");

    System.exit(0);
}

From source file:QuickstartGuice.java

License:Apache License

public static void main(String[] args) {

    // We will utilize standard Guice bootstrapping to create a Shiro SecurityManager.
    Injector injector = Guice.createInjector(new QuickstartShiroModule());
    SecurityManager securityManager = injector.getInstance(SecurityManager.class);

    // 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  a 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) {
            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:ShiroGriffonAddon.java

License:Apache License

private void initialize() {
    String className = getConfigValueAsString(getApp().getConfig(), KEY_SECURITY_MANAGER_FACTORY,
            DEFAULT_SECURITY_MANAGER_FACTORY);
    if (getLog().isDebugEnabled()) {
        getLog().debug("Using " + className + " as SecurityManagerFactory");
    }//from  w w  w.j  a va 2  s.c om
    Class factoryClass = safeLoadClass(className);
    SecurityManagerFactory factory = (SecurityManagerFactory) getApp().newInstance(factoryClass, "");
    SecurityUtils.setSecurityManager(factory.createSecurityManager(getApp()));
    SubjectHolder.setSubject(SecurityUtils.getSubject());
}

From source file: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();// ww w. j a  v a  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());

    //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:UserSubjectTest.java

License:Open Source License

@Test
public void UserSessionsRunTest() {
    //UserSessionFactory test = new UserSessionFactory();
    //UserSubject user = test.createUserSession("user1");

    //user.loginUser("simonangerer", "default");
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
    SecurityManager securityManager = factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);

    // session handling
    UserSubject user1 = new UserSubject("someSessionKey1", "someSessionValue1");
    UserSubject user2 = new UserSubject("someSessionKey2", "someSessionValue2");

    // login tests
    user1.loginUser("simonangerer", "default");
    user2.loginUser("fabiansalzgeber", "123");

    //get roles, permissions
    user1.checkPermission("adminstuff");
    user1.checkRole("doctor");
    user1.isLoggedIn();// w w w  .  j a  va2 s . co m

    //all done - log out!
    user1.logoutUser();
    user2.logoutUser();

    //empty session
    user1.isLoggedIn();
}

From source file:ApacheShiro.ShiroMVC.java

public void AgregarRol(String nombreRol, String Permisos) {
    roles.put(nombreRol, Permisos);// w  ww. j  av a2s.co m
    defaultSecurityManager.setRealm(new IniRealm(ini));
    SecurityUtils.setSecurityManager(defaultSecurityManager);

}

From source file:at.oculus.teamf.technical.accessrights.UserSessionFactory.java

License:Open Source License

private static void UserSessionFactory() {
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
    SecurityManager securityManager = factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);
    log.info("Security management intialized");
}

From source file:blade.authenticator.shiro.ShiroAuthenticatorPre.java

License:Apache License

@Activate
public void activate() {
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:userauth.ini");
    SecurityUtils.setSecurityManager(factory.getInstance());
    _log.info("activate");
}

From source file:br.com.criativasoft.opendevice.wsrest.AbstractAtmosphereConnection.java

License:Open Source License

private void initConnection() throws IOException {
    if (server == null) {
        OpenDeviceConfig odevc = ODev.getConfig();

        Config.Builder conf = new Config.Builder();
        conf.port(port);//from   ww w.j  av a  2  s . c  om
        conf.supportChunking(true);
        conf.maxChunkContentLength(5 * 1024 * 1024); // 5BM

        //conf.host("::0"); // bind all local IPs
        conf.host("0.0.0.0"); // bind all local IPs
        configure(conf);

        conf.resource(JacksonProvider.class);

        // Custom static resources
        for (String resource : webresources) {
            conf.resource(resource);
        }

        // Jersey
        for (Class<?> resource : resources) {
            conf.resource(resource);
        }

        conf.initParam("com.sun.jersey.api.json.POJOMappingFeature", "true");
        conf.initParam(ApplicationConfig.BROADCASTER_MESSAGE_PROCESSING_THREADPOOL_MAXSIZE, "10");
        conf.initParam(ApplicationConfig.BROADCASTER_ASYNC_WRITE_THREADPOOL_MAXSIZE, "10");
        conf.initParam(ApplicationConfig.SCAN_CLASSPATH, "false");
        conf.initParam(ApplicationConfig.ANALYTICS, "false");
        // conf.initParam(ApplicationConfig.DROP_ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "false");

        // conf.initParam("com.sun.jersey.spi.container.ResourceMethodDispatchProvider", "true");
        //.initParam(ApplicationConfig.OBJECT_FACTORY, GuiceConfigFactory.class.getName())
        conf.interceptor(new CrossOriginInterceptor());
        if (odevc.isAuthRequired())
            conf.interceptor(new NewShiroInterceptor());
        //            conf.interceptor(new JacksonFilterInterceptor());
        conf.interceptor(this); // add this as interceptor

        // SSL Support
        String certificate = odevc.getCertificateFile();
        if (!StringUtils.isEmpty(certificate)) {
            //                File cert = new File(certificate);
            //                if(!cert.exists()) throw new IllegalArgumentException("Certificate not found !");
            //                File key = new File(odevc.getCertificateKey());
            //                if(!key.exists()) throw new IllegalArgumentException("Certificate key must be provided !");
            //
            //                SslContext sslContext = SslContext.newServerContext(SslProvider.JDK, cert, key, odevc.getCertificatePass());
            //                conf.sslContext(sslContext);
        }

        // Authentication
        if (odevc.isAuthRequired()) {
            List<Realm> realms = new LinkedList<Realm>();
            realms.add(new BearerAuthRealm((DeviceManager) getConnectionManager()));
            realms.add(new GoogleAuthRealm((DeviceManager) getConnectionManager()));
            realms.add(new AccountDaoRealm((DeviceManager) getConnectionManager()));

            RestWebSecurityManager securityManager = new RestWebSecurityManager(realms);
            securityManager.setCacheManager(new MemoryConstrainedCacheManager());
            securityManager.setSessionManager(new DefaultWebSessionManager());

            Authenticator authenticator = securityManager.getAuthenticator();
            if (authenticator instanceof ModularRealmAuthenticator) {
                ((ModularRealmAuthenticator) authenticator)
                        .setAuthenticationStrategy(new FirstSuccessfulStrategy());
            }

            // NOTE: Works with ShiroResourceFilterFactory, registred in AppResourceConfigurator
            SecurityUtils.setSecurityManager(securityManager);

        }

        server = new Nettosphere.Builder().config(conf.build()).build();

        broadcasterFactory = server.framework().getBroadcasterFactory();
    }
}