Search in sources :

Example 16 with IdentityOAuth2ScopeServerException

use of org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeServerException in project identity-inbound-auth-oauth by wso2-extensions.

the class JDBCPermissionBasedInternalScopeValidator method getUserAllowedScopes.

private List<Scope> getUserAllowedScopes(AuthenticatedUser authenticatedUser, String[] requestedScopes, String clientId) {
    List<Scope> userAllowedScopes = new ArrayList<>();
    try {
        if (requestedScopes == null) {
            return new ArrayList<>();
        }
        boolean isSystemScope = ArrayUtils.contains(requestedScopes, SYSTEM_SCOPE);
        int tenantId = IdentityTenantUtil.getTenantId(authenticatedUser.getTenantDomain());
        startTenantFlow(authenticatedUser.getTenantDomain(), tenantId);
        AuthorizationManager authorizationManager = OAuthComponentServiceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getAuthorizationManager();
        String[] allowedUIResourcesForUser;
        /*
            Here we handle scope validation for federated user and local user separately.
            For local users - user store is used to get user roles.
            For federated user - get user roles from user attributes.
            Note that if there is association between a federated user and local user () 'Assert identity using
            mapped local subject identifier' flag will be set as true. So authenticated user will be associated
            local user not federated user.
             */
        if (authenticatedUser.isFederatedUser()) {
            /*
                There is a flow where 'Assert identity using mapped local subject identifier' flag enabled but the
                federated user doesn't have any association in localIDP, to handle this case we check for 'Assert
                identity using mapped local subject identifier' flag and get roles from userStore.
                 */
            if (isSPAlwaysSendMappedLocalSubjectId(clientId)) {
                allowedUIResourcesForUser = getAllowedUIResourcesOfUser(authenticatedUser, authorizationManager);
            } else {
                // Handle not account associated federated users.
                allowedUIResourcesForUser = getAllowedUIResourcesForNotAssociatedFederatedUser(authenticatedUser, authorizationManager);
            }
        } else {
            allowedUIResourcesForUser = getAllowedUIResourcesOfUser(authenticatedUser, authorizationManager);
        }
        Set<Scope> allScopes = getScopesOfPermissionType(tenantId);
        if (ArrayUtils.contains(allowedUIResourcesForUser, ROOT) || ArrayUtils.contains(allowedUIResourcesForUser, PERMISSION_ROOT)) {
            return new ArrayList<>(allScopes);
        } else if (ArrayUtils.contains(allowedUIResourcesForUser, ADMIN_PERMISSION_ROOT)) {
            return new ArrayList<>(getAdminAllowedScopes(allScopes, requestedScopes));
        }
        for (Scope scope : allScopes) {
            if (!isSystemScope && !ArrayUtils.contains(requestedScopes, scope.getName())) {
                continue;
            }
            List<ScopeBinding> bindings = scope.getScopeBindings();
            boolean isScopeAllowed = true;
            for (ScopeBinding scopeBinding : bindings) {
                if (PERMISSION_BINDING_TYPE.equalsIgnoreCase(scopeBinding.getBindingType())) {
                    for (String binding : scopeBinding.getBindings()) {
                        boolean isAllowed = false;
                        for (String allowedScope : allowedUIResourcesForUser) {
                            if ((binding + "/").startsWith(allowedScope + "/")) {
                                isAllowed = true;
                                break;
                            }
                        }
                        if (!isAllowed) {
                            isScopeAllowed = false;
                            break;
                        }
                    }
                }
            }
            if (isScopeAllowed) {
                userAllowedScopes.add(scope);
            }
        }
    } catch (UserStoreException e) {
        log.error("Error while accessing Authorization Manager.", e);
    } catch (IdentityOAuth2Exception e) {
        log.error("Error while accessing identity provider manager.", e);
    } catch (IdentityOAuth2ScopeServerException e) {
        log.error("Error while retrieving oAuth2 scopes.", e);
    } catch (UserIdNotFoundException e) {
        log.error("User id not available for user: " + authenticatedUser.getLoggableUserId(), e);
    } finally {
        endTenantFlow();
    }
    return userAllowedScopes;
}
Also used : IdentityOAuth2ScopeServerException(org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeServerException) ArrayList(java.util.ArrayList) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) Scope(org.wso2.carbon.identity.oauth2.bean.Scope) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) UserStoreException(org.wso2.carbon.user.api.UserStoreException) AuthorizationManager(org.wso2.carbon.user.api.AuthorizationManager) ScopeBinding(org.wso2.carbon.identity.oauth2.bean.ScopeBinding)

Example 17 with IdentityOAuth2ScopeServerException

use of org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeServerException in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2Util method dropUnregisteredScopes.

/**
 * Get a filtered set of scopes after dropping unregistered scopes.
 *
 * @param requestedScopesArr Array of requested scopes.
 * @param tenantDomain Tenant domain.
 * @return Filtered set of scopes after dropping unregistered scopes.
 * @throws IdentityOAuth2Exception IdentityOAuth2Exception
 */
public static String[] dropUnregisteredScopes(String[] requestedScopesArr, String tenantDomain) throws IdentityOAuth2Exception {
    if (ArrayUtils.isEmpty(requestedScopesArr)) {
        if (log.isDebugEnabled()) {
            log.debug("Scope string is empty. No scopes to check for unregistered scopes.");
        }
        return requestedScopesArr;
    }
    try {
        int tenantId = IdentityTenantUtil.getTenantId(tenantDomain);
        String requestedScopes = StringUtils.join(requestedScopesArr, " ");
        Set<Scope> registeredScopeSet = OAuthTokenPersistenceFactory.getInstance().getOAuthScopeDAO().getRequestedScopesOnly(tenantId, true, requestedScopes);
        List<String> filteredScopes = new ArrayList<>();
        registeredScopeSet.forEach(scope -> filteredScopes.add(scope.getName()));
        if (log.isDebugEnabled()) {
            log.debug(String.format("Dropping unregistered scopes. Requested scopes: %s | Filtered result: %s", requestedScopes, StringUtils.join(filteredScopes, " ")));
        }
        return filteredScopes.toArray(new String[0]);
    } catch (IdentityOAuth2ScopeServerException e) {
        throw new IdentityOAuth2Exception("Error occurred while retrieving registered scopes.", e);
    }
}
Also used : IdentityOAuth2ScopeServerException(org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeServerException) Scope(org.wso2.carbon.identity.oauth2.bean.Scope) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) ArrayList(java.util.ArrayList)

Example 18 with IdentityOAuth2ScopeServerException

use of org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeServerException in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuthScopeDAOImpl method getScopesWithPagination.

@Override
public Set<Scope> getScopesWithPagination(Integer offset, Integer limit, int tenantID, Boolean includeOIDCScopes) throws IdentityOAuth2ScopeServerException {
    if (log.isDebugEnabled()) {
        log.debug("Get all scopes with pagination for tenantId  :" + tenantID + " including OIDC scope: " + includeOIDCScopes);
    }
    Set<Scope> scopes = new HashSet<>();
    Map<Integer, Scope> scopeMap = new HashMap<>();
    try (Connection conn = IdentityDatabaseUtil.getDBConnection(false)) {
        NamedPreparedStatement namedPreparedStatement;
        if (includeOIDCScopes) {
            namedPreparedStatement = getPreparedStatementForGetAllScopesWithPagination(offset, limit, tenantID, conn);
        } else {
            namedPreparedStatement = getPreparedStatementForGetScopesWithPagination(offset, limit, tenantID, conn);
        }
        try (PreparedStatement preparedStatement = namedPreparedStatement.getPreparedStatement()) {
            try (ResultSet rs = preparedStatement.executeQuery()) {
                while (rs.next()) {
                    int scopeID = rs.getInt(1);
                    String name = rs.getString(2);
                    String displayName = rs.getString(3);
                    String description = rs.getString(4);
                    final String binding = rs.getString(5);
                    if (scopeMap.containsKey(scopeID) && scopeMap.get(scopeID) != null) {
                        scopeMap.get(scopeID).setName(name);
                        scopeMap.get(scopeID).setDescription(description);
                        scopeMap.get(scopeID).setDisplayName(displayName);
                        if (binding != null) {
                            if (scopeMap.get(scopeID).getBindings() != null) {
                                scopeMap.get(scopeID).addBinding(binding);
                            } else {
                                scopeMap.get(scopeID).setBindings(new ArrayList<String>() {

                                    {
                                        add(binding);
                                    }
                                });
                            }
                        }
                    } else {
                        scopeMap.put(scopeID, new Scope(name, displayName, description, new ArrayList<String>()));
                        if (binding != null) {
                            scopeMap.get(scopeID).addBinding(binding);
                        }
                    }
                }
            }
        }
        for (Map.Entry<Integer, Scope> entry : scopeMap.entrySet()) {
            scopes.add(entry.getValue());
        }
        return scopes;
    } catch (SQLException e) {
        String msg = "Error occurred while getting all scopes with pagination ";
        throw new IdentityOAuth2ScopeServerException(msg, e);
    }
}
Also used : IdentityOAuth2ScopeServerException(org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeServerException) HashMap(java.util.HashMap) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ArrayList(java.util.ArrayList) NamedPreparedStatement(org.wso2.carbon.identity.oauth2.util.NamedPreparedStatement) PreparedStatement(java.sql.PreparedStatement) NamedPreparedStatement(org.wso2.carbon.identity.oauth2.util.NamedPreparedStatement) Scope(org.wso2.carbon.identity.oauth2.bean.Scope) ResultSet(java.sql.ResultSet) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 19 with IdentityOAuth2ScopeServerException

use of org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeServerException in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuthScopeDAOImpl method addScope.

/**
 * Add a scope
 *
 * @param scope    Scope
 * @param tenantID tenant ID
 * @throws IdentityOAuth2ScopeException IdentityOAuth2ScopeException
 */
@Override
public void addScope(Scope scope, int tenantID) throws IdentityOAuth2ScopeException {
    if (scope == null || scope.getName() == null) {
        if (log.isDebugEnabled()) {
            log.debug("Scope is not defined");
        }
        throw Oauth2ScopeUtils.generateClientException(Oauth2ScopeConstants.ErrorMessages.ERROR_CODE_BAD_REQUEST_SCOPE_NAME_NOT_SPECIFIED, null);
    }
    if (scope.getName().startsWith(INTERNAL_SCOPE_PREFIX) && Oauth2ScopeUtils.isSystemLevelInternalSystemScopeManagementEnabled()) {
        if (log.isDebugEnabled()) {
            log.debug("Internal Scopes can't be added per tenant as they are managed at system level.");
        }
        throw Oauth2ScopeUtils.generateClientException(Oauth2ScopeConstants.ErrorMessages.ERROR_CODE_INTERNAL_SCOPE_MANAGED_AT_SYSTEM_LEVEL, null);
    }
    if (log.isDebugEnabled()) {
        log.debug("Adding scope :" + scope.getName());
    }
    try (Connection conn = IdentityDatabaseUtil.getDBConnection()) {
        try {
            addScope(scope, conn, tenantID);
            IdentityDatabaseUtil.commitTransaction(conn);
        } catch (SQLException e1) {
            IdentityDatabaseUtil.rollbackTransaction(conn);
            String msg = "SQL error occurred while creating scope :" + scope.getName();
            throw new IdentityOAuth2ScopeServerException(msg, e1);
        }
    } catch (SQLException e) {
        String msg = "Error occurred while creating scope :" + scope.getName();
        throw new IdentityOAuth2ScopeServerException(msg, e);
    }
}
Also used : IdentityOAuth2ScopeServerException(org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeServerException) SQLException(java.sql.SQLException) Connection(java.sql.Connection)

Example 20 with IdentityOAuth2ScopeServerException

use of org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeServerException in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuthScopeDAOImpl method getScopeIDByNameWithoutScopeType.

/**
 * Get scope ID of the provided scope regardless of scope type.
 *
 * @param scopeName Scope name.
 * @param tenantID  Tenant ID.
 * @return
 * @throws IdentityOAuth2ScopeServerException
 */
private int getScopeIDByNameWithoutScopeType(String scopeName, int tenantID) throws IdentityOAuth2ScopeServerException {
    if (log.isDebugEnabled()) {
        log.debug("Get scope ID regardless of scope type, for scope name: " + scopeName);
    }
    int scopeID = Oauth2ScopeConstants.INVALID_SCOPE_ID;
    try (Connection conn = IdentityDatabaseUtil.getDBConnection(false)) {
        try (PreparedStatement ps = conn.prepareStatement(SQLQueries.RETRIEVE_SCOPE_ID_BY_NAME_WITHOUT_SCOPE_TYPE)) {
            ps.setString(1, scopeName);
            ps.setInt(2, tenantID);
            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    scopeID = rs.getInt(1);
                }
            }
        }
        return scopeID;
    } catch (SQLException e) {
        String msg = "Error occurred while getting scope ID by name.";
        throw new IdentityOAuth2ScopeServerException(msg, e);
    }
}
Also used : IdentityOAuth2ScopeServerException(org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeServerException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) NamedPreparedStatement(org.wso2.carbon.identity.oauth2.util.NamedPreparedStatement) PreparedStatement(java.sql.PreparedStatement)

Aggregations

IdentityOAuth2ScopeServerException (org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeServerException)13 Scope (org.wso2.carbon.identity.oauth2.bean.Scope)13 Connection (java.sql.Connection)10 SQLException (java.sql.SQLException)10 ArrayList (java.util.ArrayList)8 PreparedStatement (java.sql.PreparedStatement)7 ResultSet (java.sql.ResultSet)7 HashSet (java.util.HashSet)7 NamedPreparedStatement (org.wso2.carbon.identity.oauth2.util.NamedPreparedStatement)7 OAuthScopeCacheKey (org.wso2.carbon.identity.oauth.cache.OAuthScopeCacheKey)6 HashMap (java.util.HashMap)5 Map (java.util.Map)5 UserApplicationScopeConsentDO (org.wso2.carbon.identity.oauth2.model.UserApplicationScopeConsentDO)5 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)2 OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)1 UserIdNotFoundException (org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException)1 OAuthScopeBindingCacheKey (org.wso2.carbon.identity.oauth.cache.OAuthScopeBindingCacheKey)1 InvalidOAuthClientException (org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)1 OAuthAppDO (org.wso2.carbon.identity.oauth.dao.OAuthAppDO)1 ScopeBinding (org.wso2.carbon.identity.oauth2.bean.ScopeBinding)1