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:ru.ppsrk.gwt.server.AuthServiceImpl.java

License:Open Source License

public static void initShiro() {
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
    SecurityManager securityManager = factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);
}

From source file:shiro.Helloworld.java

public static void main(String[] args) {
    //?01//w ww.java  2 s .c o m
    // 01
    // 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");
    // shiro?
    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???
    Subject currentUser = SecurityUtils.getSubject();

    // Do some stuff with a Session (no need for a web or EJB container!!!)
    // shirosession?
    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("?");
        }
    }

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

@Before
public void setUp() throws Exception {
    SecurityUtils.setSecurityManager(securityManager);
}

From source file:shiro.SubjectTest.java

@Test
public void integralTest() {
    log.info(">> integralTest()");
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
    SecurityManager securityManager = factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);
    // get the currently executing user:
    Subject currentUser = SecurityUtils.getSubject();
    log.info("User [" + currentUser.getPrincipal() + "] is logged in :" + 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")) {
        log.info("Retrieved the correct value! [" + value + "]");
    }// w ww  .j  a v a 2s.  com

    // let's login the current user so we can check against roles and permissions:
    if (!currentUser.isAuthenticated()) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //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.error("", ae);
        }
    }

    //say who they are:
    //print their identifying principal (in this case, a username):
    log.info("User [" + currentUser.getPrincipal() + "] is logged in : " + currentUser.isAuthenticated());

    //test a role:
    if (currentUser.hasRole("admin")) {
        log.info("You are admin");
    } else {
        log.info("You are unprivileged user");
    }

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

From source file:tshiro.ShiroTest.java

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

    // Setting up the SecurityManager...
    org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);

    Subject user = SecurityUtils.getSubject();

    UsernamePasswordToken token = new UsernamePasswordToken("root", "secret");

    user.login(token);/*from  ww w.  j  av  a  2 s.co  m*/

    Session session = user.getSession();
    session.setAttribute("someKey", "aValue");

    log.info("User key value:  " + session.getAttribute("someKey"));

    log.info("User is authenticated:  " + user.isAuthenticated());

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

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

    if (user.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 (user.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!");
    }
}

From source file:ua.orion.cpu.core.security.OrionActiveDirectoryRealmTest.java

License:Apache License

@BeforeClass
public void setup() {
    ThreadContext.remove();//from w  ww.  j  a  va  2 s  .c o m
    realm = new OrionActiveDirectoryRealm();
    realm.setSystemUsername("student");
    realm.setSystemPassword("student");
    realm.setSearchBase("DC=uni,DC=zhu,DC=edu,DC=ua");
    realm.setUrl("ldap://localhost:389");
    realm.setPrincipalSuffix("@uni.zhu.edu.ua");
    securityManager = new DefaultSecurityManager(realm);
    SecurityUtils.setSecurityManager(securityManager);
}

From source file:ua.orion.cpu.core.security.OrionActiveDirectoryRealmTest.java

License:Apache License

@AfterClass
public void tearDown() {
    SecurityUtils.setSecurityManager(null);
    securityManager.destroy();
    ThreadContext.remove();
}

From source file:uk.ac.edukapp.shibboleth.ShiroShibbolethFilterTest.java

License:Apache License

@Before
public void before() {
    filter = new ShiroShibbolethFilter();
    MockitoAnnotations.initMocks(this);
    SecurityUtils.setSecurityManager(securityManager);
}

From source file:uk.ac.ox.it.ords.api.audit.resources.AbstractResourceTest.java

License:Apache License

/**
 * Configure Shiro and start the server//from  w  w w. ja  va2  s . c  o m
 * @throws Exception
 */
@BeforeClass
public static void initialize() throws Exception {

    //
    // Set up roles
    //
    createTestUsersAndRoles();

    //
    // This is for unit testing only and uses the test.shiro.ini configuration
    //
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:test.shiro.ini");
    SecurityManager securityManager = factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);

    //
    // Create an embedded server with JSON processing
    //
    JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();

    ArrayList<Object> providers = new ArrayList<Object>();
    providers.add(new JacksonJsonProvider());
    providers.add(new UnrecognizedPropertyExceptionMapper());
    providers.add(new ValidationExceptionMapper());
    sf.setProviders(providers);

    //
    // Add our REST resources to the server
    //
    ArrayList<ResourceProvider> resources = new ArrayList<ResourceProvider>();
    resources.add(new SingletonResourceProvider(new AuditResource(), true));
    sf.setResourceProviders(resources);

    //
    // Start the server at the endpoint
    //
    sf.setAddress(ENDPOINT_ADDRESS);
    server = sf.create();
    startServer();
}

From source file:uk.ac.ox.it.ords.api.database.resources.AbstractResourceTest.java

License:Apache License

/**
 * Configure Shiro and start the server//from   w w w . j  av a 2  s . c  o m
 * @throws Exception
 */
@BeforeClass
public static void initialize() throws Exception {

    //
    // Set up roles
    //
    createTestUsersAndRoles();

    //
    // This is for unit testing only and uses the test.shiro.ini configuration
    //
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:test.shiro.ini");
    SecurityManager securityManager = factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);

    //
    // Create an embedded server with JSON processing
    //

    //
    // Create an embedded server with JSON processing
    //
    JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();

    ArrayList<Object> providers = new ArrayList<Object>();
    providers.add(new JacksonJsonProvider());
    //providers.add(new UnrecognizedPropertyExceptionMapper());
    //providers.add(new ValidationExceptionMapper());
    sf.setProviders(providers);

    //
    // Add our REST resources to the server
    //
    ArrayList<ResourceProvider> resources = new ArrayList<ResourceProvider>();

    //
    // Add our REST resources to the server
    //
    resources.add(new SingletonResourceProvider(new Database(), true));

    sf.setResourceProviders(resources);

    //
    // Start the server at the endpoint
    //
    sf.setAddress(ENDPOINT_ADDRESS);
    server = sf.create();
    databases = new ArrayList<DatabaseReference>();
    startServer();
}