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

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

Introduction

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

Prototype

boolean[] isPermitted(List<Permission> permissions);

Source Link

Document

Checks if this Subject implies the given Permissions and returns a boolean array indicating which permissions are implied.

Usage

From source file:Homework4ShiroCommandLineClient.java

/**
 * @param args/* w ww .j  a va2s  .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(/*  w  ww . j a v a 2s  .  c o m*/
            "\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   www .j a  v  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:$.PermissionManager.java

License:Open Source License

public Map<String, Object> getJsonPermissions(Subject subject) {
        Map<String, Set<String>> permisosMap = new HashMap<String, Set<String>>();
        Map<String, Object> root = new HashMap<String, Object>();
        Map<String, Object> per;

        boolean hasAllOperationPermission = false;

        for (String key : keys) {
            //TODO Controlar que en la bd no hayan permisos repetidos
            String[] parts = key.split(":");
            String recurso = parts[0];
            String operacion = parts[1];

            Set<String> ops = permisosMap.get(recurso);
            if (ops == null) {
                ops = new HashSet<String>();
            }/*from  w  ww. ja v  a2s . com*/
            ops.add(operacion);
            permisosMap.put(recurso, ops);
        }

        for (Map.Entry<String, Set<String>> entry : permisosMap.entrySet()) {
            per = new HashMap<String, Object>();

            hasAllOperationPermission = false;
            //existe un permiso de all operation
            if (entry.getValue().contains("*")) {
                entry.getValue().remove("*");
                if (subject.isPermitted(entry.getKey() + ":*")) {
                    hasAllOperationPermission = true;
                }
            }

            for (String val : entry.getValue()) {
                if (hasAllOperationPermission || subject.isPermitted(entry.getKey() + ":" + val)) {
                    per.put(val, true);
                } else {
                    per.put(val, false);
                }
            }
            root.put(entry.getKey(), per);
        }

        return root;
    }

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

License:Apache License

@GET
@Path("corpora")
@Produces("application/xml")
public List<AnnisCorpus> corpora() {
    List<AnnisCorpus> allCorpora = annisDao.listCorpora();
    List<AnnisCorpus> allowedCorpora = new LinkedList<AnnisCorpus>();

    // filter by which corpora the user is allowed to access
    Subject user = SecurityUtils.getSubject();
    for (AnnisCorpus c : allCorpora) {
        if (user.isPermitted("query:*:" + c.getName())) {
            allowedCorpora.add(c);//from   w w  w.j  a  v a 2  s.c  o m
        }
    }

    return allowedCorpora;
}

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

License:Apache License

/**
* Fetches the example queries for a specific corpus.
*
* @param rawCorpusNames specifies the corpora the examples are fetched from.
*
*///  w w  w.  j ava2  s .  co m
@GET
@Path("corpora/example-queries/")
@Produces(MediaType.APPLICATION_XML)
public List<ExampleQuery> getExampleQueries(@QueryParam("corpora") String rawCorpusNames)
        throws WebApplicationException {

    try {
        String[] corpusNames;
        if (rawCorpusNames != null) {
            corpusNames = rawCorpusNames.split(",");
        } else {
            List<AnnisCorpus> allCorpora = annisDao.listCorpora();
            corpusNames = new String[allCorpora.size()];
            for (int i = 0; i < corpusNames.length; i++) {
                corpusNames[i] = allCorpora.get(i).getName();
            }
        }

        List<String> allowedCorpora = new ArrayList<String>();

        // filter by which corpora the user is allowed to access
        Subject user = SecurityUtils.getSubject();
        for (String c : corpusNames) {
            if (user.isPermitted("query:*:" + c)) {
                allowedCorpora.add(c);
            }
        }

        List<Long> corpusIDs = annisDao.mapCorpusNamesToIds(allowedCorpora);
        return annisDao.getExampleQueries(corpusIDs);
    } catch (Exception ex) {
        throw new WebApplicationException(400);
    }
}

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

License:Apache License

@GET
@Path("corpora")
@Produces("application/xml")
public List<AnnisCorpus> corpora() {
    List<AnnisCorpus> allCorpora = queryDao.listCorpora();

    List<AnnisCorpus> allowedCorpora = new LinkedList<>();

    // filter by which corpora the user is allowed to access
    Subject user = SecurityUtils.getSubject();
    for (AnnisCorpus c : allCorpora) {
        if (user.isPermitted("query:show:" + c.getName())) {
            allowedCorpora.add(c);//from   ww w .  j  a v a 2s.c o  m
        }
    }

    return allowedCorpora;
}

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

License:Apache License

@GET
@Path("corpora/config")
@Produces("application/xml")
public CorpusConfigMap corpusConfigs() {
    CorpusConfigMap corpusConfigs = queryDao.getCorpusConfigurations();
    CorpusConfigMap result = new CorpusConfigMap();
    Subject user = SecurityUtils.getSubject();

    if (corpusConfigs != null) {
        for (String c : corpusConfigs.getCorpusConfigs().keySet()) {
            if (user.isPermitted("query:*:" + c)) {
                result.put(c, corpusConfigs.get(c));
            }/* w w  w  . j  a  v  a  2  s  .  c o m*/
        }
    }

    return result;
}

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

License:Apache License

@GET
@Path("corpora/{top}")
@Produces("application/xml")
public List<AnnisCorpus> singleCorpus(@PathParam("top") String toplevelName) {
    List<AnnisCorpus> result = new ArrayList<>();

    Subject user = SecurityUtils.getSubject();

    LinkedList<String> originalCorpusNames = new LinkedList<>();
    originalCorpusNames.add(toplevelName);
    List<Long> ids = queryDao.mapCorpusNamesToIds(originalCorpusNames);

    // also add all corpora that match the alias name
    ids.addAll(queryDao.mapCorpusAliasToIds(toplevelName));
    if (!ids.isEmpty()) {
        List<AnnisCorpus> allCorpora = queryDao.listCorpora(ids);
        for (AnnisCorpus c : allCorpora) {
            if (user.isPermitted("query:show:" + c.getName())) {
                result.add(c);//from   w w  w.j a  v  a 2s.co m
            }
        }
    }

    return result;
}

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

License:Apache License

/**
 * Fetches the example queries for a specific corpus.
 *
 * @param rawCorpusNames specifies the corpora the examples are fetched from.
 *
 *///from   w  ww .  j a  v a 2  s  .c  o m
@GET
@Path("corpora/example-queries/")
@Produces(MediaType.APPLICATION_XML)
public List<ExampleQuery> getExampleQueries(@QueryParam("corpora") String rawCorpusNames)
        throws WebApplicationException {

    Subject user = SecurityUtils.getSubject();

    try {
        String[] corpusNames;
        if (rawCorpusNames != null) {
            corpusNames = rawCorpusNames.split(",");
        } else {
            List<AnnisCorpus> allCorpora = queryDao.listCorpora();
            corpusNames = new String[allCorpora.size()];
            for (int i = 0; i < corpusNames.length; i++) {
                corpusNames[i] = allCorpora.get(i).getName();
            }
        }

        List<String> allowedCorpora = new ArrayList<>();

        // filter by which corpora the user is allowed to access
        for (String c : corpusNames) {
            if (user.isPermitted("query:*:" + c)) {
                allowedCorpora.add(c);
            }
        }

        List<Long> corpusIDs = queryDao.mapCorpusNamesToIds(allowedCorpora);
        return queryDao.getExampleQueries(corpusIDs);
    } catch (Exception ex) {
        log.error("Problem accessing example queries", ex);
        throw new WebApplicationException(ex, 500);
    }
}