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.commonjava.auth.shiro.couch.CouchRealm.java

License:Apache License

public void setupSecurityManager(final Realm... fallbackRealms) {
    // make indempotent.
    if (sm == null) {
        final List<Realm> realms = new ArrayList<Realm>();
        realms.add(this);
        for (final Realm realm : fallbackRealms) {
            if (realm != null) {
                realms.add(realm);/*from ww w  . j a  v  a  2s  .  com*/
            }
        }

        sm = new DefaultSecurityManager(realms);
        SecurityUtils.setSecurityManager(sm);
    }
}

From source file:org.commonjava.auth.shiro.couch.test.CouchShiroTestFixture.java

License:Apache License

public static void teardownSecurityManager() {
    clearSubject();//from w  w  w .j  av a2  s  . c  om

    try {
        org.apache.shiro.mgt.SecurityManager securityManager = SecurityUtils.getSecurityManager();

        LifecycleUtils.destroy(securityManager);
    } catch (UnavailableSecurityManagerException e) {
        // we don't care about this when cleaning up the test environment
    }

    SecurityUtils.setSecurityManager(null);
}

From source file:org.commonjava.badgr.shiro.BadgrRealm.java

License:Apache License

public void setupSecurityManager(final Realm... fallbackRealms) {
    System.out.println("Setting security manager.");
    // make indempotent.
    if (sm == null) {
        final List<Realm> realms = new ArrayList<Realm>();
        realms.add(this);
        for (final Realm realm : fallbackRealms) {
            if (realm != null) {
                realms.add(realm);/*from   w w w  .j  a  v a  2 s .co  m*/
            }
        }

        sm = new DefaultSecurityManager(realms);
        SecurityUtils.setSecurityManager(sm);
    }
}

From source file:org.credo.shiro.Quickstart.java

public static void main(String[] args) {
    // ?shiro SecurityManager .
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");

    // SecurityManager?ShiroSecurityManager
    SecurityManager securityManager = factory.getInstance();

    // ?????JVM?//from w  w  w.ja  v  a  2 s  . c  o m
    // ??????web?web.xml
    SecurityUtils.setSecurityManager(securityManager);

    // ---------------??shiro-----------------

    // ???
    Subject currentSubject = SecurityUtils.getSubject();

    // shiro session?,??webejb
    Session session = currentSubject.getSession();
    System.out.println("cuuerntUser:" + currentSubject.toString());
    session.setAttribute("someKey", "aValue");
    String value = (String) session.getAttribute("someKey");
    if (value.equals("aValue")) {
        System.out.println("??:" + value);
    }

    // ?,???
    // ??,???
    if (!currentSubject.isAuthenticated()) {
        // ???,?web??
        UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
        // ???
        token.setRememberMe(true);
        currentSubject.login(token);
    }

    //shiro?subject.??
    System.out.println("User " + currentSubject.getPrincipal() + " Login Successful!");

    //???
    if (currentSubject.hasRole("schwartz")) {
        System.out.println("May the Schwartz be with you!");
    } else {
        System.out.println("Hello, mere mortal.");
    }

    //????? (not instance-level)
    if (currentSubject.isPermitted("lightsaber:weild")) {
        System.out.println("You may use a lightsaber ring.  Use it wisely.");
    } else {
        System.out.println("Sorry, lightsaber rings are for schwartz masters only.");
    }

    //a (very powerful) Instance Level permission:
    if (currentSubject.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!
    currentSubject.logout();

    System.exit(0);
}

From source file:org.debux.webmotion.shiro.ShiroListener.java

License:Open Source License

@Override
public void onStart(Mapping mapping, ServerContext context) {
    // Add filter into webapp
    ServletContext servletContext = context.getServletContext();
    FilterRegistration registration = servletContext.addFilter("shiro", filter);
    if (registration != null) {
        registration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.FORWARD, DispatcherType.INCLUDE,
                DispatcherType.REQUEST, DispatcherType.ERROR), true, "/*");
    }//w  w  w .  ja  v  a  2s.  c  o m

    context.addGlobalController(Shiro.class);

    Realm realm = getRealm();
    if (realm instanceof AuthenticatingRealm) {
        AuthenticatingRealm authenticatingRealm = (AuthenticatingRealm) realm;
        authenticatingRealm.setCredentialsMatcher(getMatcher());
    }

    DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(realm);
    securityManager.setSessionManager(getSessionManager());
    SecurityUtils.setSecurityManager(securityManager);
}

From source file:org.eclipse.kapua.broker.core.KapuaBrokerSecurityPlugin.java

License:Open Source License

public Broker installPlugin(Broker broker) throws Exception {
    logger.info(">> installPlugin {}", KapuaBrokerSecurityPlugin.class.getName());
    try {/*from  www . ja v  a 2s . c o  m*/
        // initialize shiro context for broker plugin from shiro ini file
        URL shiroIniUrl = getClass().getResource("/shiro.ini");
        String shiroIniStr = ResourceUtils.readResource(shiroIniUrl);
        Ini shiroIni = new Ini();
        shiroIni.load(shiroIniStr);

        IniSecurityManagerFactory factory = new IniSecurityManagerFactory(shiroIni);
        org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);

        // install the filters
        broker = new KapuaSecurityBrokerFilter(broker);
        return broker;
    } catch (Throwable t) {
        logger.error("Error in plugin installation.", t);
        throw (SecurityException) new SecurityException(t);
    }
}

From source file:org.fcrepo.auth.webac.WebACFilterTest.java

License:Apache License

@Before
public void setupRequest() {
    SecurityUtils.setSecurityManager(mockSecurityManager);

    mockSubject = Mockito.mock(Subject.class);
    threadState = new SubjectThreadState(mockSubject);
    threadState.bind();//from   ww w.  ja  v a 2  s. c o m

    request = new MockHttpServletRequest();
    response = new MockHttpServletResponse();
    filterChain = new MockFilterChain();

    // set default request URI and path info
    // for the purposes of this test, there is no context path
    // so the request URI and path info are the same
    request.setPathInfo(testPath);
    request.setRequestURI(testPath);

    mockContainer = Mockito.mock(Container.class);
    mockChildContainer = Mockito.mock(Container.class);
    mockBinary = Mockito.mock(FedoraBinary.class);
    mockRoot = Mockito.mock(Container.class);

    when(mockSessionFactory.getInternalSession()).thenReturn(mockFedoraSession);

    when(mockNodeService.exists(mockFedoraSession, testPath)).thenReturn(true);
    when(mockNodeService.exists(mockFedoraSession, testChildPath)).thenReturn(false);
    when(mockNodeService.exists(mockFedoraSession, "/")).thenReturn(true);

    when(mockNodeService.find(mockFedoraSession, "/")).thenReturn(mockRoot);
    when(mockContainer.getContainer()).thenReturn(mockRoot);
    when(mockChildContainer.getContainer()).thenReturn(mockContainer);

    when(mockContainer.getTypes()).thenReturn(Arrays.asList(URI.create(BASIC_CONTAINER.toString())));
    when(mockChildContainer.getTypes()).thenReturn(Arrays.asList(URI.create(BASIC_CONTAINER.toString())));
    when(mockBinary.getTypes()).thenReturn(Arrays.asList(URI.create(NON_RDF_SOURCE.toString())));

    final List<URI> rootTypes = new ArrayList<>();
    of("RepositoryRoot", "Resource", "Container")
            .forEach(x -> rootTypes.add(URI.create(REPOSITORY_NAMESPACE + x)));
    when(mockRoot.getTypes()).thenReturn(rootTypes);

    // Setup Container by default
    setupContainerResource();
}

From source file:org.gear.examples.shiro.quickstart.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):
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:quickstart/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")) {
        logger.info("Retrieved the correct value ! [" + value + "]");
    }/*  w w w  .j  a va 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("guest", "guest");
        token.setRememberMe(true);

        try {
            currentUser.login(token);
        } catch (UnknownAccountException e) {
            logger.info("There is no user with username of " + token.getPrincipal());
            System.exit(0);
        } catch (IncorrectCredentialsException e) {
            logger.info("Password for account " + token.getPrincipal() + " was incorrect!");
            System.exit(0);
        } catch (LockedAccountException e) {
            logger.info("The account for username " + token.getPrincipal() + " is locked."
                    + " Please contract your administrator to unlock it.");
            System.exit(0);
        } catch (AuthenticationException e) {
            logger.info("unexpected exception ...");
            logger.error(e.getMessage(), e);
            System.exit(0);
        }
    }

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

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

    System.exit(0);
}

From source file:org.gradle.Tutorial.java

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

    //1./*from www.ja  v  a  2s  .  c  om*/
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");

    //2.
    SecurityManager securityManager = factory.getInstance();

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

    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("lonestarr", "vespa");

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

        try {
            currentUser.login(token);
            //if no exception, that's it, we're done!

            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!");
            }
        } catch (UnknownAccountException uae) {
            //username wasn't in the system, show them an error message?
            uae.printStackTrace();
        } catch (IncorrectCredentialsException ice) {
            //password didn't match, try again?
            ice.printStackTrace();
        } catch (LockedAccountException lae) {
            //account for that username is locked - can't login.  Show them a message?
            lae.printStackTrace();
        } catch (AuthenticationException ae) {
            //unexpected condition - error?
            ae.printStackTrace();
        }
    }

    currentUser.logout(); //removes all identifying information and invalidates their session too.

    System.exit(0);
}

From source file:org.graylog2.bindings.providers.DefaultSecurityManagerProvider.java

License:Open Source License

@Inject
public DefaultSecurityManagerProvider(MongoDbSessionDAO mongoDbSessionDAO,
        PasswordAuthenticator passwordAuthenticator, MongoDbAuthorizationRealm mongoDbAuthorizationRealm,
        LdapUserAuthenticator ldapUserAuthenticator, SessionAuthenticator sessionAuthenticator,
        AccessTokenAuthenticator accessTokenAuthenticator, Configuration configuration) {
    final GraylogSimpleAccountRealm inMemoryRealm = new GraylogSimpleAccountRealm();
    inMemoryRealm.setCachingEnabled(false);
    inMemoryRealm.addRootAccount(configuration.getRootUsername(), configuration.getRootPasswordSha2());
    inMemoryRealm.setCredentialsMatcher(new HashedCredentialsMatcher("SHA-256"));

    passwordAuthenticator.setCachingEnabled(false);
    passwordAuthenticator.setCredentialsMatcher(new HashedCredentialsMatcher("SHA-1"));
    mongoDbAuthorizationRealm.setCachingEnabled(false);

    ldapUserAuthenticator.setCachingEnabled(false);

    sessionAuthenticator.setCachingEnabled(false);
    accessTokenAuthenticator.setCachingEnabled(false);

    sm = new DefaultSecurityManager(Lists.<Realm>newArrayList(sessionAuthenticator, accessTokenAuthenticator,
            ldapUserAuthenticator, passwordAuthenticator, inMemoryRealm));
    final Authenticator authenticator = sm.getAuthenticator();
    if (authenticator instanceof ModularRealmAuthenticator) {
        ((ModularRealmAuthenticator) authenticator).setAuthenticationStrategy(new FirstSuccessfulStrategy());
    }/*  w ww.j  a  v a  2s.  com*/
    sm.setAuthorizer(
            new ModularRealmAuthorizer(Lists.<Realm>newArrayList(mongoDbAuthorizationRealm, inMemoryRealm)));

    final DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
    final DefaultSessionStorageEvaluator sessionStorageEvaluator = new DefaultSessionStorageEvaluator() {
        @Override
        public boolean isSessionStorageEnabled(Subject subject) {
            // save to session if we already have a session. do not create on just for saving the subject
            return (subject.getSession(false) != null);
        }
    };
    sessionStorageEvaluator.setSessionStorageEnabled(false);
    subjectDAO.setSessionStorageEvaluator(sessionStorageEvaluator);
    sm.setSubjectDAO(subjectDAO);

    final DefaultSessionManager defaultSessionManager = (DefaultSessionManager) sm.getSessionManager();
    defaultSessionManager.setSessionDAO(mongoDbSessionDAO);
    defaultSessionManager.setDeleteInvalidSessions(true);
    defaultSessionManager.setCacheManager(new MemoryConstrainedCacheManager());
    // DO NOT USE global session timeout!!! It's fucky.
    //defaultSessionManager.setGlobalSessionTimeout(TimeUnit.SECONDS.toMillis(5));

    SecurityUtils.setSecurityManager(sm);
}