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:org.i3xx.step.zero.security.impl.shiro.NaFactoryImpl.java

License:Apache License

public void setSecurityManager(Properties props) {
    if (props == null) {
        //does nothing
    }/*from w  w  w .  j av  a  2 s. c om*/

    Realm realm = new NaMyRealm();

    DefaultSecurityManager securityManager = new DefaultSecurityManager(realm);
    SecurityUtils.setSecurityManager(securityManager);

    MemoryConstrainedCacheManager cacheManager = new MemoryConstrainedCacheManager();
    securityManager.setCacheManager(cacheManager);
}

From source file:org.icgc.dcc.submission.sftp.SftpPublicKeyAuthenticatorTest.java

License:Open Source License

@Test
@SneakyThrows/*  www.j  av  a2s  .c  om*/
public void testPublicKey() {
    // Simulate the behavior of SecurityManagerProvider
    DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
    SecurityUtils.setSecurityManager(defaultSecurityManager);

    // Setup public and private keys for test
    val keyStore = tmp.newFolder();
    val keyName = "sftp";
    val privateKey = new File(keyStore, keyName);
    val publicKey = new File(keyStore, keyName + ".pub");

    // Create SFTP client
    JSch jsch = new JSch();
    createKeyPair(jsch, privateKey, publicKey);
    jsch.addIdentity(privateKey.getAbsolutePath());

    // Enable public key in application
    when(config.hasPath("sftp.key")).thenReturn(true);
    when(config.getString("sftp.key")).thenReturn(getPublicKeyValue(publicKey));

    // Create class under test
    SftpServerService service = createService();
    service.startAsync().awaitRunning();

    // Connect to server
    val session = jsch.getSession(USERNAME, SFTP_HOST, SFTP_PORT);
    session.setConfig("StrictHostKeyChecking", "no");
    session.connect();

    val sftpChannel = session.openChannel("sftp");
    sftpChannel.connect();

    service.stopAsync().awaitTerminated();
}

From source file:org.icgc.dcc.submission.shiro.SecurityManagerProvider.java

License:Open Source License

@Override
public SecurityManager get() {
    DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager(realms);
    disableSessions(defaultSecurityManager);

    // Bind globally
    SecurityUtils.setSecurityManager(defaultSecurityManager);

    return defaultSecurityManager;
}

From source file:org.ihtsdo.ttk.fx.app.IsaacApp.java

License:Apache License

/**
 * Method description//from  ww  w. j a  v a2  s .c  o  m
 *
 *
 * @param args
 */
public static void main(String[] args) {

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

    SecurityUtils.setSecurityManager(factory.getInstance());

    Subject currentUser = SecurityUtils.getSubject();
    Session session = currentUser.getSession();

    if (!currentUser.isAuthenticated()) {

        // collect user principals and credentials in a gui specific manner
        // such as username/password html form, X509 certificate, OpenID, etc.
        // We'll use the username/password example here since it is the most common.
        UsernamePasswordToken token = new UsernamePasswordToken("root", "secret");

        // this is all you have to do to support 'remember me' (no config - built in!):
        token.setRememberMe(true);
        currentUser.login(token);
    }

    if (currentUser.isAuthenticated()) {
        // TODO somehow associate the user UUID with the subject
        SessionAttributes.get().put(SessionAttributeKeys.USER_UUID_ARRAY, TermAux.USER.getUuids());
        SessionAttributes.get().put(SessionAttributeKeys.EDIT_MODULE_UUID_ARRAY, Snomed.CORE_MODULE.getUuids());

    } else {
        System.out.println("User is not authenticated");
        System.exit(0);
    }
    launch(args);
}

From source file:org.jason.demo.mutiThread.ShiroDemo.java

public static void main(String[] args) {
    // ? SecurityManager
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
    SecurityManager securityManager = factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);
    // Now that a simple Shiro environment is set up, let's see what you can
    // do://from w w  w . j ava2 s .  co  m

    // 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("userInfo", "?");
    String value = (String) session.getAttribute("userInfo");
    if (value.equals("rayn")) {
        logger.info("Retrieved the correct value! [" + value + "]");
    }

    // let's login the current user so we can check against roles and
    // permissions:
    UsernamePasswordToken token = null;
    if (!currentUser.isAuthenticated()) {
        token = new UsernamePasswordToken("liu", "123123", false);
        try {
            currentUser.login(token);
        } catch (UnknownAccountException uae) {
            logger.info("???" + token.getPrincipal());
        } catch (IncorrectCredentialsException ice) {
            logger.info("[" + token.getPrincipal() + "] ?");
        } catch (LockedAccountException lae) {
            logger.info(
                    "?? [" + token.getPrincipal() + "] ???.");
        }
        // ... catch more exceptions here (maybe custom ones specific to
        // your application?
        catch (AuthenticationException ae) {
            // unexpected condition? error?
            ae.printStackTrace();
        }
    }

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

    currentUser = SecurityUtils.getSubject();
    // test a role:
    if (currentUser.hasRole("admin")) {
        logger.info("admin.");
    } else {
        logger.info("");
    }

    // test a typed permission (not instance-level)
    if (currentUser.isPermitted("users:del")) {
        logger.info("users:del");
    } else {
        logger.info("??????");
    }

    // a (very powerful) Instance Level permission:
    if (currentUser.isPermitted("users:create:del:upd")) {
        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();

    ThreadContext.unbindSubject();

    System.exit(0);
}

From source file:org.killbill.billing.entitlement.EntitlementTestSuiteWithEmbeddedDB.java

License:Apache License

protected void configureShiro() {
    final Ini config = new Ini();
    config.addSection("users");
    config.getSection("users").put("EntitlementUser", "password, entitlement");
    config.addSection("roles");
    config.getSection("roles").put("entitlement",
            Permission.ACCOUNT_CAN_CREATE.toString() + "," + Permission.ENTITLEMENT_CAN_CREATE.toString() + ","
                    + Permission.ENTITLEMENT_CAN_CHANGE_PLAN.toString() + ","
                    + Permission.ENTITLEMENT_CAN_PAUSE_RESUME.toString() + ","
                    + Permission.ENTITLEMENT_CAN_TRANSFER.toString() + ","
                    + Permission.ENTITLEMENT_CAN_CANCEL.toString());

    // Reset the security manager
    ThreadContext.unbindSecurityManager();

    final Factory<SecurityManager> factory = new IniSecurityManagerFactory(config);
    final SecurityManager securityManager = factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);
}

From source file:org.killbill.billing.util.security.api.DefaultSecurityService.java

License:Apache License

@LifecycleHandlerType(LifecycleHandlerType.LifecycleLevel.INIT_SERVICE)
public void initialize() {
    SecurityUtils.setSecurityManager(securityManager);
}

From source file:org.killbill.billing.util.security.api.DefaultSecurityService.java

License:Apache License

@LifecycleHandlerType(LifecycleLevel.STOP_SERVICE)
public void stop() {
    SecurityUtils.setSecurityManager(null);
}

From source file:org.killbill.billing.util.security.shiro.realm.TestKillBillJdbcRealm.java

License:Apache License

@Override
@BeforeMethod(groups = "slow")
public void beforeMethod() throws Exception {
    super.beforeMethod();
    final KillBillJdbcRealm realm = new KillBillJdbcRealm(helper.getDataSource(), securityConfig);
    securityManager = new DefaultSecurityManager(realm);
    SecurityUtils.setSecurityManager(securityManager);
}

From source file:org.killbill.billing.util.UtilTestSuiteNoDB.java

License:Apache License

protected void configureShiro() {
    final Ini config = new Ini();
    config.addSection("users");
    config.getSection("users").put("pierre", "password, creditor");
    config.getSection("users").put("stephane", "password, refunder");
    config.addSection("roles");
    config.getSection("roles").put("creditor",
            Permission.INVOICE_CAN_CREDIT.toString() + "," + Permission.INVOICE_CAN_ITEM_ADJUST.toString());
    config.getSection("roles").put("refunder", Permission.PAYMENT_CAN_REFUND.toString());

    // Reset the security manager
    ThreadContext.unbindSecurityManager();

    final Factory<SecurityManager> factory = new IniSecurityManagerFactory(config);
    final SecurityManager securityManager = factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);
}