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

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

Introduction

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

Prototype

void checkRole(String roleIdentifier) throws AuthorizationException;

Source Link

Document

Asserts this Subject has the specified role by returning quietly if they do or throwing an org.apache.shiro.authz.AuthorizationException if they do not.

Usage

From source file:cn.dreampie.common.plugin.shiro.plugin.RoleAuthzHandler.java

License:Apache License

@Override
public void assertAuthorized() throws AuthorizationException {

    Subject subject = getSubject();

    if (!(annotation instanceof RequiresRoles))
        return;//from  ww  w  . j  a v  a 2  s .  co m
    RequiresRoles rrAnnotation = (RequiresRoles) annotation;
    String[] roles = rrAnnotation.value();

    if (roles.length == 1) {
        subject.checkRole(roles[0]);
        return;
    }
    if (Logical.AND.equals(rrAnnotation.logical())) {
        subject.checkRoles(Arrays.asList(roles));
        return;
    }
    if (Logical.OR.equals(rrAnnotation.logical())) {
        // Avoid processing exceptions unnecessarily - "delay" throwing the exception by calling hasRole first
        boolean hasAtLeastOneRole = false;
        for (String role : roles)
            if (subject.hasRole(role))
                hasAtLeastOneRole = true;
        // Cause the exception if none of the role match, note that the exception message will be a bit misleading
        if (!hasAtLeastOneRole)
            subject.checkRole(roles[0]);
    }
}

From source file:com.ftww.basic.plugin.shiro.core.handler.RoleAuthzHandler.java

License:Apache License

@Override
public void assertAuthorized() throws AuthorizationException {
    Subject subject = getSubject();
    if (!(annotation instanceof RequiresRoles))
        return;/* ww  w. j a v a  2  s .c  o  m*/
    RequiresRoles rrAnnotation = (RequiresRoles) annotation;
    String[] roles = rrAnnotation.value();

    if (roles.length == 1) {
        subject.checkRole(roles[0]);
        return;
    }
    //?&&?
    if (Logical.AND.equals(rrAnnotation.logical())) {
        subject.checkRoles(Arrays.asList(roles));
        return;
    }
    //?||?
    if (Logical.OR.equals(rrAnnotation.logical())) {
        boolean hasAtLeastOneRole = false;
        for (String role : roles)
            if (subject.hasRole(role))//?
                hasAtLeastOneRole = true;
        //???role??
        if (!hasAtLeastOneRole)
            subject.checkRole(roles[0]);//?
    }
}

From source file:com.wegas.core.security.rest.UserController.java

License:MIT License

/**
 * See like an other user specified by it's jpaAccount id. Administrators
 * only./*from  w  w  w  . j  a va  2 s .  co m*/
 *
 * @param accountId jpaAccount id
 */
@POST
@Path("Be/{accountId: [1-9][0-9]*}")
public void runAs(@PathParam("accountId") Long accountId) {
    Subject oSubject = SecurityUtils.getSubject();

    if (oSubject.isRunAs()) {
        oSubject.releaseRunAs(); //@TODO: check shiro version > 1.2.1 (SHIRO-380)
    }
    oSubject.checkRole("Administrator");
    SimplePrincipalCollection subject = new SimplePrincipalCollection(accountId, "jpaRealm");
    oSubject.runAs(subject);
}

From source file:griffon.plugins.shiro.RolesRequirementEvaluator.java

License:Apache License

@Override
protected boolean doEval(@Nonnull RequirementConfiguration requirementConfig, @Nonnull Subject subject) {
    String[] roles = requirementConfig.getValues();
    Logical logical = requirementConfig.getLogical();

    try {/*  w  w w.ja va  2 s  .  c om*/
        if (roles.length == 1) {
            subject.checkRole(roles[0]);
        } else if (Logical.AND.equals(logical)) {
            subject.checkRoles(Arrays.asList(roles));
        } else if (Logical.OR.equals(logical)) {
            boolean hasAtLeastOneRole = false;
            for (String role : roles) {
                if (subject.hasRole(role)) {
                    hasAtLeastOneRole = true;
                }
            }
            if (!hasAtLeastOneRole) {
                subject.checkRole(roles[0]);
            } else {
                return true;
            }
        }
    } catch (AuthorizationException ae) {
        return false;
    }

    return true;
}

From source file:org.apache.usergrid.management.RoleIT.java

License:Apache License

@Test
public void testRoleInactivity() throws Exception {

    OrganizationOwnerInfo ooi = setup.getMgmtSvc().createOwnerAndOrganization("RoleIT", "edanuff5", "Ed Anuff",
            "ed@anuff.com5", "test", true, false);

    OrganizationInfo organization = ooi.getOrganization();

    UUID applicationId = setup.getMgmtSvc().createApplication(organization.getUuid(), "test-app").getId();
    EntityManager em = setup.getEmf().getEntityManager(applicationId);
    setup.getEntityIndex().refresh(em.getApplicationId());

    Map<String, Object> properties = new LinkedHashMap<String, Object>();
    properties.put("username", "edanuff5");
    properties.put("email", "ed@anuff.com5");
    properties.put("activated", true);
    User user = em.create(User.ENTITY_TYPE, User.class, properties);

    em.createRole("logged-in", "Logged In", 2000);
    setup.getEntityIndex().refresh(em.getApplicationId());
    setup.getEntityIndex().refresh(em.getApplicationId());
    em.addUserToRole(user.getUuid(), "logged-in");

    String accessToken = setup.getMgmtSvc().getAccessTokenForAppUser(applicationId, user.getUuid(), 0);

    UserInfo user_info = setup.getMgmtSvc().getAppUserFromAccessToken(accessToken);

    PrincipalCredentialsToken token = PrincipalCredentialsToken.getFromAppUserInfoAndAccessToken(user_info,
            accessToken);//from   w w  w  .  j  a  v  a 2s  . co m

    Subject subject = SubjectUtils.getSubject();
    subject.login(token);

    subject.checkRole("application-role:" + applicationId + ":logged-in");

    logger.info("Has role \"logged-in\"");

    Thread.sleep(2100);

    subject.login(token);

    assertFalse(subject.hasRole("application-role:" + applicationId + ":logged-in"));

    logger.info("Doesn't have role \"logged-in\"");
}

From source file:org.bigmouth.nvwa.authority.NvwaAuthorityFilter.java

License:Apache License

@Override
public boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
    if (request instanceof HttpServletRequest) {
        String uri = WebUtils.getPathWithinApplication(WebUtils.toHttp(request));
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Access url: {}", uri);
        }//from w w w.  jav a 2s.  c om
    }
    Subject subject = SecurityUtils.getSubject();
    subject.checkRole("admin");
    return true;
}

From source file:org.obiba.agate.web.rest.security.CurrentSessionResource.java

License:Open Source License

@GET
public Agate.SessionDto get() {
    Subject subject = SecurityUtils.getSubject();
    Agate.SessionDto.Builder builder = Agate.SessionDto.newBuilder() //
            .setUsername(subject.getPrincipal().toString()) //
            .setRealm(subject.getPrincipals().getRealmNames().iterator().next());

    try {/*from  w  ww.j a  v  a 2  s  . c  o  m*/
        subject.checkRole(Roles.AGATE_ADMIN.toString());
        builder.setRole(Roles.AGATE_ADMIN.toString());
    } catch (AuthorizationException e) {
        builder.setRole(Roles.AGATE_USER.toString());
    }

    return builder.build();
}

From source file:org.sonatype.nexus.kenai.internal.KenaiClearCacheTest.java

License:Open Source License

@Test
public void testClearCache() throws Exception {
    // so here is the problem, we clear the authz cache when ever config changes happen

    // now log the user in
    Subject subject1 = securitySystem.login(new UsernamePasswordToken(username, password));
    // check authz
    subject1.checkRole(DEFAULT_ROLE);

    // clear the cache
    KenaiRealm realm = (KenaiRealm) this.lookup(Realm.class, "kenai");
    realm.getAuthorizationCache().clear();

    // user should still have the role
    subject1.checkRole(DEFAULT_ROLE);//w ww  . j a v  a 2 s  . c om

    // the user should be able to login again as well
    Subject subject2 = securitySystem.login(new UsernamePasswordToken(username, password));
    subject2.checkRole(DEFAULT_ROLE);
}

From source file:org.usergrid.management.RoleIT.java

License:Apache License

@Test
public void testRoleInactivity() throws Exception {

    OrganizationOwnerInfo ooi = setup.getMgmtSvc().createOwnerAndOrganization("RoleIT", "edanuff5", "Ed Anuff",
            "ed@anuff.com5", "test", true, false);

    OrganizationInfo organization = ooi.getOrganization();

    UUID applicationId = setup.getMgmtSvc().createApplication(organization.getUuid(), "test-app").getId();
    EntityManager em = setup.getEmf().getEntityManager(applicationId);

    Map<String, Object> properties = new LinkedHashMap<String, Object>();
    properties.put("username", "edanuff5");
    properties.put("email", "ed@anuff.com5");
    properties.put("activated", true);
    User user = em.create(User.ENTITY_TYPE, User.class, properties);

    em.createRole("logged-in", "Logged In", 1000);
    em.addUserToRole(user.getUuid(), "logged-in");

    String accessToken = setup.getMgmtSvc().getAccessTokenForAppUser(applicationId, user.getUuid(), 0);

    UserInfo user_info = setup.getMgmtSvc().getAppUserFromAccessToken(accessToken);

    PrincipalCredentialsToken token = PrincipalCredentialsToken.getFromAppUserInfoAndAccessToken(user_info,
            accessToken);/*from  www. ja v a2s . co m*/

    Subject subject = SubjectUtils.getSubject();
    subject.login(token);

    subject.checkRole("application-role:" + applicationId + ":logged-in");

    LOG.info("Has role \"logged-in\"");

    Thread.sleep(1000);

    subject.login(token);

    assertFalse(subject.hasRole("application-role:" + applicationId + ":logged-in"));

    LOG.info("Doesn't have role \"logged-in\"");
}

From source file:org.usergrid.management.RoleTest.java

License:Apache License

@Test
public void testRoleInactivity() throws Exception {

    OrganizationOwnerInfo ooi = management.createOwnerAndOrganization("ed-organization", "edanuff", "Ed Anuff",
            "ed@anuff.com", "test", true, false);

    OrganizationInfo organization = ooi.getOrganization();

    UUID applicationId = management.createApplication(organization.getUuid(), "test-app").getId();
    EntityManager em = emf.getEntityManager(applicationId);

    Map<String, Object> properties = new LinkedHashMap<String, Object>();
    properties.put("username", "edanuff");
    properties.put("email", "ed@anuff.com");
    properties.put("activated", true);
    User user = em.create(User.ENTITY_TYPE, User.class, properties);

    em.createRole("logged-in", "Logged In", 1000);
    em.addUserToRole(user.getUuid(), "logged-in");

    String accessToken = management.getAccessTokenForAppUser(applicationId, user.getUuid(), 0);

    UserInfo user_info = management.getAppUserFromAccessToken(accessToken);

    PrincipalCredentialsToken token = PrincipalCredentialsToken.getFromAppUserInfoAndAccessToken(user_info,
            accessToken);/*  w  w  w .jav a 2 s .  c  om*/

    Subject subject = SubjectUtils.getSubject();
    subject.login(token);

    subject.checkRole("application-role:" + applicationId + ":logged-in");

    logger.info("Has role \"logged-in\"");

    Thread.sleep(1000);

    subject.login(token);

    assertFalse(subject.hasRole("application-role:" + applicationId + ":logged-in"));

    logger.info("Doesn't have role \"logged-in\"");

}