Example usage for org.apache.shiro.authz AuthorizationException AuthorizationException

List of usage examples for org.apache.shiro.authz AuthorizationException AuthorizationException

Introduction

In this page you can find the example usage for org.apache.shiro.authz AuthorizationException AuthorizationException.

Prototype

public AuthorizationException(String message, Throwable cause) 

Source Link

Document

Constructs a new AuthorizationException.

Usage

From source file:com.redhat.rcm.nexus.security.GracefulUNFAuthorizationRealm.java

License:Open Source License

@Override
protected AuthorizationInfo doGetAuthorizationInfo(final PrincipalCollection principals) {
    AuthorizationInfo result = null;//from w w w.j a  v a  2s .  c  o m
    try {
        if (configuration.isAutoCreateEnabled()) {
            User user = autoCreateOnDemand(principals);
            if (user != null) {
                Set<String> roles = new LinkedHashSet<String>();

                if (logger.isDebugEnabled()) {
                    logger.debug("Roles for user: " + user + " are: " + roles);
                }

                if (user.getRoles() != null) {
                    for (RoleIdentifier rid : user.getRoles()) {
                        roles.add(rid.getRoleId());
                    }
                }

                result = new SimpleAuthorizationInfo(roles);
            }
        }
    } catch (ConfigurationException e) {
        throw new AuthorizationException("Error loading nx-sec configuration.", e);
    }

    if (result == null) {
        final String username = (String) principals.iterator().next();
        if (logger.isDebugEnabled()) {
            logger.debug("delegating doGetAuthorizationInfo(..) for: " + username + ".");
        }

        try {
            result = super.doGetAuthorizationInfo(principals);
        } catch (AuthorizationException e) {
            logger.error("Delegated authorization failed for: " + username + ".", e);
            throw e;
        }
    }

    if (logger.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder();
        sb.append("AuthorizationInfo result: ");

        if (result.getRoles() != null) {
            sb.append("\n\nRoles:");
            for (String role : result.getRoles()) {
                sb.append("\n\t").append(role);
            }
        }

        if (result.getStringPermissions() != null) {
            sb.append("\n\nString Permissions:");
            for (String perm : result.getStringPermissions()) {
                sb.append("\n\t").append(perm);
            }
        }

        if (result.getObjectPermissions() != null) {
            sb.append("\n\nObject Permissions:");
            for (Object perm : result.getObjectPermissions()) {
                sb.append("\n\t").append(perm);
            }
        }
        sb.append("\n\n");

        logger.debug(sb.toString());
    }

    return result;
}

From source file:com.redhat.rcm.nexus.security.GracefulUNFAuthorizationRealm.java

License:Open Source License

private User autoCreateOnDemand(PrincipalCollection principals) {
    final String username = (String) principals.iterator().next();

    SecuritySystem securitySystem;/* w w w.j  a v  a2s .  c o m*/
    try {
        securitySystem = getSecuritySystem();
    } catch (final ComponentLookupException e) {
        logger.error("Cannot retrieve handle to security system for user lookup.");

        throw new AuthorizationException("Unable to lookup SecuritySystem", e);
    }

    User user;
    try {
        user = securitySystem.getUser(username);

        if (logger.isDebugEnabled()) {
            StringBuffer sb = new StringBuffer();

            sb.append("User already exists in Nexus: ").append(username).append(":");
            sb.append("\nUser ID: ").append(user.getUserId());
            sb.append("\nSource: ").append(user.getSource());
            sb.append("\nEmail: ").append(user.getEmailAddress());

            Set<RoleIdentifier> roles = user.getRoles();
            sb.append("\nRoles: ");
            for (RoleIdentifier ri : roles) {
                sb.append("\n\t").append(ri.getRoleId());
            }

            logger.debug(sb.toString());
        }
    } catch (final UserNotFoundException unfe) {
        String templateUserId;
        String emailDomain;
        try {
            templateUserId = configuration.getTemplateUserId();
            emailDomain = configuration.getAutoCreateEmailDomain();

        } catch (ConfigurationException e) {
            throw new AuthorizationException("Error loading nx-sec configuration.", e);
        }

        if (templateUserId == null) {
            templateUserId = securitySystem.getAnonymousUsername();
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Cannot find pre-existing user: " + username
                    + ". Creating as a clone of anonymous user: " + templateUserId + "...");
        }

        user = new DefaultUser();
        user.setEmailAddress(username.indexOf('@') > 0 ? username : username + "@" + emailDomain);
        user.setUserId(username);
        user.setStatus(UserStatus.active);
        user.setSource(SecurityXmlUserManager.SOURCE);

        try {
            final User anonUser = securitySystem.getUser(templateUserId);
            user.setRoles(anonUser.getRoles());
        } catch (final UserNotFoundException e) {
            logger.error("Anonymous user is missing. Unable to create user: " + username);

            throw new AuthorizationException("Anonymous user is missing. Unable to create user: " + username,
                    e);
        }

        try {
            securitySystem.addUser(user);
        } catch (final InvalidConfigurationException e) {
            logger.error("Unable to create user: " + username + ". Invalid configuration: " + e.getMessage());

            throw new AuthorizationException(
                    "Invalid configuration: " + e.getMessage() + "\nUnable to create user: " + username, e);
        } catch (final NoSuchUserManagerException e) {
            logger.error("Unable to create user: " + username + ". No such user manager: " + e.getMessage());

            throw new AuthorizationException(
                    "No such user-manager: " + e.getMessage() + "\nUnable to create user: " + username, e);
        }
    }

    return user;
}

From source file:org.apache.zeppelin.realm.ActiveDirectoryGroupRealm.java

License:Apache License

protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    try {//from  ww  w.ja  va 2  s  .  c  om
        AuthorizationInfo info = this.queryForAuthorizationInfo(principals, this.getLdapContextFactory());
        return info;
    } catch (NamingException var5) {
        String msg = "LDAP naming error while attempting to " + "retrieve authorization for user [" + principals
                + "].";
        throw new AuthorizationException(msg, var5);
    }
}

From source file:org.onehippo.forge.security.support.shiro.realm.HippoRepositoryRealm.java

License:Apache License

protected Set<String> getRoleNames(String username) throws AuthorizationException {
    Set<String> roleNames = new HashSet<String>();
    Session session = null;/*from w w w.  j  av a  2 s  .  c  om*/

    try {
        if (getSystemCredentials() != null) {
            session = getSystemRepository().login(getSystemCredentials());
        } else {
            session = getSystemRepository().login();
        }

        String statement = MessageFormat.format(getGroupsOfUserQuery(), username);

        if (log.isDebugEnabled()) {
            log.debug("Searching groups of user with query: " + statement);
        }

        Query q = session.getWorkspace().getQueryManager().createQuery(statement, getQueryLanguage());
        QueryResult result = q.execute();
        NodeIterator nodeIt = result.getNodes();

        boolean defaultRoleAdded = false;
        Node node;

        while (nodeIt.hasNext()) {
            node = nodeIt.nextNode();
            String roleName = node.getName();
            String prefixedRoleName = (rolePrefix != null ? rolePrefix + roleName : roleName);
            roleNames.add(prefixedRoleName);

            if (defaultRoleName != null && !defaultRoleAdded && roleName.equals(defaultRoleName)) {
                defaultRoleAdded = true;
            }
        }

        if (defaultRoleName != null && !defaultRoleAdded) {
            String prefixedRoleName = (rolePrefix != null ? rolePrefix + defaultRoleName : defaultRoleName);
            roleNames.add(prefixedRoleName);
        }
    } catch (RepositoryException e) {
        final String message = "There was a repository exception while authorizing user [" + username + "]";

        if (log.isErrorEnabled()) {
            log.error(message, e);
        }

        // Rethrow any SQL errors as an authorization exception
        throw new AuthorizationException(message, e);
    } finally {
        if (session != null) {
            try {
                session.logout();
            } catch (Exception e) {
                log.error("Failed to logout jcr session. {}", e);
            }
        }
    }

    return roleNames;
}

From source file:org.onehippo.forge.security.support.shiro.realm.HippoRepositoryRealm.java

License:Apache License

protected Set<String> getPermissions(String username, Set<String> roleNames) throws AuthorizationException {
    Set<String> permissions = new HashSet<String>();

    Session session = null;//from ww  w. jav a2s .  c o  m

    try {
        if (getSystemCredentials() != null) {
            session = getSystemRepository().login(getSystemCredentials());
        } else {
            session = getSystemRepository().login();
        }

        StringBuilder groupsConstraintsBuilder = new StringBuilder(100);

        for (String roleName : roleNames) {
            String groupName = roleName;
            groupsConstraintsBuilder.append("or @hipposys:groups = '").append(groupName).append("' ");
        }

        String statement = MessageFormat.format(getRolesOfUserAndGroupQuery(), username,
                groupsConstraintsBuilder.toString());

        Query q = session.getWorkspace().getQueryManager().createQuery(statement, getQueryLanguage());
        QueryResult result = q.execute();
        NodeIterator nodeIt = result.getNodes();

        Node node;
        Node parentNode;

        String domain;
        String authority;
        String permission;

        boolean defaultPermissionAdded = false;

        while (nodeIt.hasNext()) {
            node = nodeIt.nextNode();
            parentNode = node.getParent();

            domain = parentNode.getName();
            authority = node.getProperty("hipposys:role").getString();

            permission = new StringBuilder(20).append(domain).append(':').append(authority).toString();
            permissions.add(permission);

            if (defaultPermission != null && !defaultPermissionAdded && defaultPermission.equals(permission)) {
                defaultPermissionAdded = true;
            }
        }

        if (!defaultPermissionAdded && defaultPermission != null) {
            permissions.add(defaultPermission);
        }
    } catch (RepositoryException e) {
        final String message = "There was a repository exception while authorizing user [" + username + "]";

        if (log.isErrorEnabled()) {
            log.error(message, e);
        }

        // Rethrow any SQL errors as an authorization exception
        throw new AuthorizationException(message, e);
    } finally {
        if (session != null) {
            try {
                session.logout();
            } catch (Exception e) {
                log.error("Failed to logout jcr session. {}", e);
            }
        }
    }

    return permissions;
}

From source file:org.ow2.proactive.iam.core.realms.LdapRealm.java

License:Open Source License

protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    AuthorizationInfo info;/*w  w  w .java  2 s  .com*/
    try {
        info = queryForAuthorizationInfo(principals, getContextFactory());
    } catch (NamingException e) {
        String msg = "LDAP naming error while attempting to retrieve authorization for user [" + principals
                + "].";
        throw new AuthorizationException(msg, e);
    }

    return info;
}

From source file:org.sonatype.nexus.jsecurity.realms.external.crowd.CrowdAuthenticatingRealm.java

License:Open Source License

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    String username = (String) principals.getPrimaryPrincipal();
    try {/* w  ww  .  j av  a2 s. c  o  m*/
        List<String> roles = crowdClientHolder.getNexusRoleManager().getNexusRoles(username);
        return new SimpleAuthorizationInfo(new HashSet<String>(roles));
    } catch (RemoteException e) {
        throw new AuthorizationException("Could not retrieve info from Crowd.", e);
    } catch (UserNotFoundException e) {
        throw new UnknownAccountException("User " + username + " not found", e);
    } catch (InvalidAuthenticationException e) {
        throw new IncorrectCredentialsException(e);
    } catch (InvalidAuthorizationTokenException e) {
        throw new AuthorizationException("Could not retrieve info from Crowd.", e);
    }
}

From source file:org.sonatype.nexus.plugins.crowd.CrowdAuthenticatingRealm.java

License:Open Source License

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    String username = (String) principals.getPrimaryPrincipal();
    try {//www. ja  va  2s.com
        Set<String> groups = crowdClientHolder.getRestClient().getNestedGroups(username);
        return new SimpleAuthorizationInfo(groups);
    } catch (Exception e) {
        throw new AuthorizationException(DEFAULT_MESSAGE, e);
    }
}