001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019
020import com.google.inject.Guice;
021import com.google.inject.Injector;
022import org.apache.shiro.SecurityUtils;
023import org.apache.shiro.authc.*;
024import org.apache.shiro.mgt.SecurityManager;
025import org.apache.shiro.session.Session;
026import org.apache.shiro.subject.Subject;
027import org.slf4j.Logger;
028import org.slf4j.LoggerFactory;
029
030/**
031 * Simple Quickstart application showing how to use Shiro's API with Guice integration.
032 *
033 * @since 0.9 RC2
034 */
035public class QuickstartGuice {
036
037    private static final transient Logger log = LoggerFactory.getLogger(QuickstartGuice.class);
038
039
040    public static void main(String[] args) {
041
042        // We will utilize standard Guice bootstrapping to create a Shiro SecurityManager.
043        Injector injector = Guice.createInjector(new QuickstartShiroModule());
044        SecurityManager securityManager = injector.getInstance(SecurityManager.class);
045
046        // for this simple example quickstart, make the SecurityManager
047        // accessible as a JVM singleton.  Most applications wouldn't do this
048        // and instead rely on their container configuration or web.xml for
049        // webapps.  That is outside the scope of this simple quickstart, so
050        // we'll just do the bare minimum so you can continue to get a feel
051        // for things.
052        SecurityUtils.setSecurityManager(securityManager);
053
054        // Now that a simple Shiro environment is set up, let's see what you can do:
055
056        // get the currently executing user:
057        Subject currentUser = SecurityUtils.getSubject();
058
059        // Do some stuff with a Session (no need for a web or EJB container!!!)
060        Session session = currentUser.getSession();
061        session.setAttribute("someKey", "aValue");
062        String value = (String) session.getAttribute("someKey");
063        if (value.equals("aValue")) {
064            log.info("Retrieved the correct value! [" + value + "]");
065        }
066
067        // let's login the current user so we can check against roles and permissions:
068        if (!currentUser.isAuthenticated()) {
069            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
070            token.setRememberMe(true);
071            try {
072                currentUser.login(token);
073            } catch (UnknownAccountException uae) {
074                log.info("There is no user with username of " + token.getPrincipal());
075            } catch (IncorrectCredentialsException ice) {
076                log.info("Password for account " + token.getPrincipal() + " was incorrect!");
077            } catch (LockedAccountException lae) {
078                log.info("The account for username " + token.getPrincipal() + " is locked.  " +
079                        "Please contact your administrator to unlock it.");
080            }
081            // ... catch more exceptions here (maybe custom ones specific to your application?
082            catch (AuthenticationException ae) {
083                //unexpected condition?  error?
084            }
085        }
086
087        //say who they are:
088        //print their identifying principal (in this case, a username):
089        log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
090
091        //test a role:
092        if (currentUser.hasRole("schwartz")) {
093            log.info("May the Schwartz be with you!");
094        } else {
095            log.info("Hello, mere mortal.");
096        }
097
098        //test a typed permission (not instance-level)
099        if (currentUser.isPermitted("lightsaber:weild")) {
100            log.info("You may use a lightsaber ring.  Use it wisely.");
101        } else {
102            log.info("Sorry, lightsaber rings are for schwartz masters only.");
103        }
104
105        //a (very powerful) Instance Level permission:
106        if (currentUser.isPermitted("winnebago:drive:eagle5")) {
107            log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
108                    "Here are the keys - have fun!");
109        } else {
110            log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
111        }
112
113        //all done - log out!
114        currentUser.logout();
115
116        System.exit(0);
117    }
118}