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

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

Introduction

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

Prototype

boolean hasRole(String roleIdentifier);

Source Link

Document

Returns true if this Subject has the specified role, false otherwise.

Usage

From source file:Homework4ShiroCommandLineClient.java

/**
 * @param args//  www  . j  a va 2 s  . com
 */
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  www  . ja  va  2 s. 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 + "]");
    }/*ww  w.  j a v  a  2s .  c om*/

    // 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:$.HasAnyRolesTag.java

License:Apache License

protected boolean showTagBody(String roleNames) {
        boolean hasAnyRole = false;
        Subject subject = getSubject();

        if (subject != null) {
            // Iterate through roles and check to see if the user has one of the roles
            for (String role : roleNames.split(ROLE_NAMES_DELIMETER)) {
                if (subject.hasRole(role.trim())) {
                    hasAnyRole = true;/*from  w  ww. jav  a  2 s. c  om*/
                    break;
                }
            }
        }

        return hasAnyRole;
    }

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();
        }//from   www  .j a  v a 2  s  .c  om
    }

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

From source file:at.pollux.thymeleaf.shiro.dialect.ShiroDialectTest.java

License:Apache License

@Test
public void testHasRole() {
    Subject subjectUnderTest = new Subject.Builder(getSecurityManager()).buildSubject();
    setSubject(subjectUnderTest);//from  ww w  .  j a  v a2  s .  co m

    Context context = new Context();
    context.setVariable("roleExpression", "roled");
    String result;

    // Guest user
    result = templateEngine.process(TEST_TEMPLATE_PATH, context);
    assertFalse(result.contains("shiro:"));
    assertFalse(result.contains("HASROLE1"));
    assertFalse(result.contains("HASROLE2"));

    // Logged in user 1
    subjectUnderTest.login(new UsernamePasswordToken(USER1, PASS1));
    assertTrue(subjectUnderTest.hasRole("rolea")); // sanity
    result = templateEngine.process(TEST_TEMPLATE_PATH, context);
    assertFalse(result.contains("shiro:"));
    assertTrue(result.contains("HASROLE1"));
    assertTrue(result.contains("HASROLE2"));
    subjectUnderTest.logout();

    // Logged in user 2
    subjectUnderTest.login(new UsernamePasswordToken(USER2, PASS2));
    assertFalse(subjectUnderTest.hasRole("rolea")); // sanity
    result = templateEngine.process(TEST_TEMPLATE_PATH, context);
    assertFalse(result.contains("shiro:"));
    assertFalse(result.contains("HASROLE1"));
    assertFalse(result.contains("HASROLE2"));
    subjectUnderTest.logout();
}

From source file:at.pollux.thymeleaf.shiro.dialect.ShiroDialectTest.java

License:Apache License

@Test
public void testLacksRole() {
    Subject subjectUnderTest = new Subject.Builder(getSecurityManager()).buildSubject();
    setSubject(subjectUnderTest);//from   w w w  .  ja v  a  2s  .  co m

    Context context = new Context();
    String result;

    // Guest user
    result = templateEngine.process(TEST_TEMPLATE_PATH, context);
    assertFalse(result.contains("shiro:"));
    assertTrue(result.contains("LACKSROLE1"));
    assertTrue(result.contains("LACKSROLE2"));

    // Logged in user 1
    subjectUnderTest.login(new UsernamePasswordToken(USER1, PASS1));
    assertTrue(subjectUnderTest.hasRole("rolea")); // sanity
    result = templateEngine.process(TEST_TEMPLATE_PATH, context);
    assertFalse(result.contains("shiro:"));
    assertFalse(result.contains("LACKSROLE1"));
    assertFalse(result.contains("LACKSROLE2"));
    subjectUnderTest.logout();

    // Logged in user 2
    subjectUnderTest.login(new UsernamePasswordToken(USER2, PASS2));
    assertFalse(subjectUnderTest.hasRole("rolea")); // sanity
    result = templateEngine.process(TEST_TEMPLATE_PATH, context);
    assertFalse(result.contains("shiro:"));
    assertTrue(result.contains("LACKSROLE1"));
    assertTrue(result.contains("LACKSROLE2"));
    subjectUnderTest.logout();
}

From source file:at.pollux.thymeleaf.shiro.dialect.ShiroDialectTest.java

License:Apache License

@Test
public void testHasAnyRoles() {
    Subject subjectUnderTest = new Subject.Builder(getSecurityManager()).buildSubject();
    setSubject(subjectUnderTest);/*from  www . j  a va  2  s.co  m*/

    Context context = new Context();
    String result;

    // Guest user
    result = templateEngine.process(TEST_TEMPLATE_PATH, context);
    assertFalse(result.contains("shiro:"));
    assertFalse(result.contains("HASANYROLES1"));
    assertFalse(result.contains("HASANYROLES2"));

    // Logged in user 1
    subjectUnderTest.login(new UsernamePasswordToken(USER1, PASS1));
    assertTrue(subjectUnderTest.hasRole("rolea")); // sanity
    result = templateEngine.process(TEST_TEMPLATE_PATH, context);
    assertFalse(result.contains("shiro:"));
    assertTrue(result.contains("HASANYROLES1"));
    assertTrue(result.contains("HASANYROLES2"));
    subjectUnderTest.logout();

    // Logged in user 2
    subjectUnderTest.login(new UsernamePasswordToken(USER2, PASS2));
    assertFalse(subjectUnderTest.hasRole("rolea")); // sanity
    result = templateEngine.process(TEST_TEMPLATE_PATH, context);
    assertFalse(result.contains("shiro:"));
    assertFalse(result.contains("HASANYROLES1"));
    assertFalse(result.contains("HASANYROLES2"));
    subjectUnderTest.logout();
}

From source file:au.org.theark.core.web.component.AbstractSubContainerPanel.java

License:Open Source License

/**
 * @param id//  www. ja  va 2  s .  c  o  m
 */
public AbstractSubContainerPanel(String id) {
    super(id);
    setOutputMarkupPlaceholderTag(true);
    Subject currentUser = SecurityUtils.getSubject();
    realm.clearCachedAuthorizationInfo(currentUser.getPrincipals());
    currentUser.hasRole("Administrator");
}

From source file:beans.ShiroLoginBean.java

/**
 * Try and authenticate the user//from w  w  w.ja  v  a 2s .  c o  m
 */
public void doLogin() {
    Subject subject = SecurityUtils.getSubject();

    UsernamePasswordToken token = new UsernamePasswordToken(username, password);

    try {
        subject.login(token);

        if (subject.hasRole("admin")) {
            FacesContext.getCurrentInstance().getExternalContext().redirect("admin/index.xhtml");
        } else {
            FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml");
        }
    } catch (UnknownAccountException ex) {
        facesError("Unknown account");
        //log.error(ex.getMessage(), ex);
    } catch (IncorrectCredentialsException ex) {
        facesError("Wrong password");
        //log.error(ex.getMessage(), ex);
    } catch (LockedAccountException ex) {
        facesError("Locked account");
        //log.error(ex.getMessage(), ex);
    } catch (AuthenticationException | IOException ex) {
        facesError("Unknown error: " + ex.getMessage());
        //log.error(ex.getMessage(), ex);
    } finally {
        token.clear();
    }
}