Example usage for org.apache.shiro.subject Subject getPrincipal

List of usage examples for org.apache.shiro.subject Subject getPrincipal

Introduction

In this page you can find the example usage for org.apache.shiro.subject Subject getPrincipal.

Prototype

Object getPrincipal();

Source Link

Document

Returns this Subject's application-wide uniquely identifying principal, or null if this Subject is anonymous because it doesn't yet have any associated account data (for example, if they haven't logged in).

Usage

From source file:Homework4ShiroCommandLineClient.java

/**
 * @param args/*  w w  w .j  av  a  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(//from   ww w. j  a  v a 2  s  . com
            "\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  av a2 s  . co  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:$.AuthRS.java

License:Open Source License

@GET
    @Path("/islogged")
    @Produces(MediaType.APPLICATION_JSON)
    public Map<String, Object> isLogguedIn() {
        System.out.println("======== Is Logged IN");
        Map<String, Object> root = new HashMap<String, Object>();
        Subject _subject = null;

        boolean loggedIn = false;
        try {/* w ww .j  a v  a 2s . c o m*/
            _subject = SecurityUtils.getSubject();
            loggedIn = _subject.isAuthenticated();

        } catch (Exception e) {
            loggedIn = false;
        }

        if (loggedIn) {
            PermissionManager pm = new PermissionManager(permisoBC.findAllKeys());
            root.put("success", true);
            root.put("username", _subject.getPrincipal());
            root.put("permissions", pm.getJsonPermissions(_subject));
        } else {
            root.put("success", false);
        }

        return root;
    }

From source file:$.AuthRS.java

License:Open Source License

@POST
    @Path("/login")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Map<String, Object> login(Credential credential) {
        System.out.println("========  LOGIN");
        Map<String, Object> root = new HashMap<String, Object>();
        Subject _subject = null;

        boolean failure = false;
        try {//from w ww.j av  a  2 s.  co  m
            _subject = SecurityUtils.getSubject();
            if (_subject != null) {
                System.out.println("========  User:" + credential.getUsername());
                System.out.println("========  Password:" + credential.getPassword());
                _subject.login(new UsernamePasswordToken(credential.getUsername(), credential.getPassword()));
            }
        } catch (Exception e) {
            failure = true;
        }

        if (failure) {
            root.put("success", false);
        } else {
            PermissionManager pm = new PermissionManager(permisoBC.findAllKeys());
            root.put("success", true);
            root.put("username", _subject.getPrincipal());
            root.put("permissions", pm.getJsonPermissions(_subject));
        }

        return root;
    }

From source file:$.SecurityInterceptor.java

License:Open Source License

@Override
    public void filter(ContainerRequestContext requestContext) {
        ResourceMethodInvoker methodInvoker = (ResourceMethodInvoker) requestContext
                .getProperty("org.jboss.resteasy.core.ResourceMethodInvoker");
        Method method = methodInvoker.getMethod();

        Subject subject = SecurityUtils.getSubject();

        if (!subject.isAuthenticated() && method.isAnnotationPresent(RequiresAuthentication.class)) {
            //throw new UnauthenticatedException("Authentication required");
            requestContext.abortWith(ACCESS_DENIED);
        }// w  w w  . jav a2  s.  c  om

        if (subject.getPrincipal() != null && method.isAnnotationPresent(RequiresGuest.class)) {
            //throw new UnauthenticatedException("Guest required");
            requestContext.abortWith(ACCESS_DENIED);
        }

        if (subject.getPrincipal() == null && method.isAnnotationPresent(RequiresUser.class)) {
            // throw new UnauthenticatedException("User required");
            requestContext.abortWith(ACCESS_DENIED);
        }

        RequiresRoles roles = method.getAnnotation(RequiresRoles.class);

        if (roles != null) {
            subject.checkRoles(Arrays.asList(roles.value()));
        }

        RequiresPermissions permissions = method.getAnnotation(RequiresPermissions.class);

        if (permissions != null) {
            try {
                subject.checkPermissions(permissions.value());
            } catch (AuthorizationException e) {
                //e.printStackTrace();
                //requestContext.abortWith(SERVER_ERROR);
                requestContext.abortWith(ACCESS_DENIED);
                return;
            }

        }

    }

From source file:annis.service.internal.AdminService.java

License:Apache License

/**
 * Get the user configuration for the currentl logged in user.
 *//*w  w  w . jav  a 2s .  c  o  m*/
@GET
@Path("userconfig")
@Produces("application/xml")
public AnnisUserConfig getUserConfig() {
    Subject user = SecurityUtils.getSubject();
    user.checkPermission("admin:read:userconfig");

    return adminDao.retrieveUserConfig((String) user.getPrincipal());
}

From source file:annis.service.internal.AdminServiceImpl.java

License:Apache License

@GET
@Path("is-authenticated")
@Produces("text/plain")
public Response isAuthenticated() {
    Subject user = SecurityUtils.getSubject();
    Object principal = user.getPrincipal();
    if (principal instanceof String) {
        // if a use has an expired account it won't have it's own name as role
        boolean hasOwnRole = user.hasRole((String) principal);
        if (!hasOwnRole) {
            return Response.status(Response.Status.FORBIDDEN).entity("Account expired").build();
        }//ww w  .  ja v a  2s .  co  m
    }

    return Response.ok(Boolean.toString(user.isAuthenticated())).build();
}

From source file:annis.service.internal.AdminServiceImpl.java

License:Apache License

/**
 * Get the user configuration for the currently logged in user.
 *
 * @return//from   w  w  w  .j  a v  a2 s.c o m
 */
@GET
@Path("userconfig")
@Produces("application/xml")
public UserConfig getUserConfig() {
    Subject user = SecurityUtils.getSubject();
    user.checkPermission("admin:read:userconfig");

    return adminDao.retrieveUserConfig((String) user.getPrincipal());
}

From source file:annis.service.internal.AdminServiceImpl.java

License:Apache License

/**
 * Sets the user configuration for the currently logged in user.
 *///  ww  w.  j a  v a 2  s.  co  m
@POST
@Path("userconfig")
@Consumes("application/xml")
public Response setUserConfig(JAXBElement<UserConfig> config) {
    Subject user = SecurityUtils.getSubject();
    user.checkPermission("admin:write:userconfig");

    String userName = (String) user.getPrincipal();

    adminDao.storeUserConfig(userName, config.getValue());
    return Response.ok().build();
}