Search in sources :

Example 66 with Scope

use of org.wso2.carbon.apimgt.api.model.Scope in project carbon-apimgt by wso2.

the class APIUtil method getAPIScopes.

/**
 * Get scopes attached to the API.
 *
 * @param id   API uuid
 * @param organization Organization
 * @return Scope key to Scope object mapping
 * @throws APIManagementException if an error occurs while getting scope attached to API
 */
public static Map<String, Scope> getAPIScopes(String id, String organization) throws APIManagementException {
    String currentApiUuid;
    APIRevision apiRevision = ApiMgtDAO.getInstance().checkAPIUUIDIsARevisionUUID(id);
    if (apiRevision != null && apiRevision.getApiUUID() != null) {
        currentApiUuid = apiRevision.getApiUUID();
    } else {
        currentApiUuid = id;
    }
    Set<String> scopeKeys = ApiMgtDAO.getInstance().getAPIScopeKeys(currentApiUuid);
    return getScopes(scopeKeys, organization);
}
Also used : APIRevision(org.wso2.carbon.apimgt.api.model.APIRevision)

Example 67 with Scope

use of org.wso2.carbon.apimgt.api.model.Scope in project carbon-apimgt by wso2.

the class APIUtil method isAllowedScope.

/**
 * Determines if the scope is specified in the whitelist.
 *
 * @param scope - The scope key to check
 * @return - 'true' if the scope is white listed. 'false' if not.
 */
public static boolean isAllowedScope(String scope) {
    if (allowedScopes == null) {
        APIManagerConfiguration configuration = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
        // Read scope whitelist from Configuration.
        List<String> whitelist = configuration.getProperty(APIConstants.ALLOWED_SCOPES);
        // If whitelist is null, default scopes will be put.
        if (whitelist == null) {
            whitelist = new ArrayList<String>();
            whitelist.add(APIConstants.OPEN_ID_SCOPE_NAME);
            whitelist.add(APIConstants.DEVICE_SCOPE_PATTERN);
        }
        allowedScopes = new HashSet<String>(whitelist);
    }
    for (String scopeTobeSkipped : allowedScopes) {
        if (scope.matches(scopeTobeSkipped)) {
            return true;
        }
    }
    return false;
}
Also used : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration)

Example 68 with Scope

use of org.wso2.carbon.apimgt.api.model.Scope in project carbon-apimgt by wso2.

the class BasicAuthCredentialValidator method validateScopes.

/**
 * Validates the roles of the given user against the roles of the scopes of the API resource.
 *
 * @param username     given username
 * @param openAPI      OpenAPI of the API
 * @param synCtx       The message to be authenticated
 * @param userRoleList The list of roles of the user
 * @return true if the validation passed
 * @throws APISecurityException If an authentication failure or some other error occurs
 */
@MethodStats
public boolean validateScopes(String username, OpenAPI openAPI, MessageContext synCtx, BasicAuthValidationInfoDTO basicAuthValidationInfoDTO) throws APISecurityException {
    String[] userRoleList = basicAuthValidationInfoDTO.getUserRoleList();
    String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
    String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
    String apiElectedResource = (String) synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE);
    String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
    String httpMethod = (String) axis2MessageContext.getProperty(APIConstants.DigestAuthConstants.HTTP_METHOD);
    String resourceKey = apiContext + ":" + apiVersion + ":" + apiElectedResource + ":" + httpMethod;
    Map<String, Scope> scopeMap = apiKeyValidator.retrieveScopes(tenantDomain);
    String resourceCacheKey = resourceKey + ":" + username;
    if (gatewayKeyCacheEnabled && getGatewayBasicAuthResourceCache().get(resourceCacheKey) != null && basicAuthValidationInfoDTO.isCached()) {
        return true;
    }
    if (openAPI != null) {
        // retrieve the user roles related to the scope of the API resource
        List<String> resourceScopes = OpenAPIUtils.getScopesOfResource(openAPI, synCtx);
        if (resourceScopes != null && resourceScopes.size() > 0) {
            for (String resourceScope : resourceScopes) {
                Scope scope = scopeMap.get(resourceScope);
                if (scope != null) {
                    if (scope.getRoles().isEmpty()) {
                        log.debug("Scope " + resourceScope + " didn't have roles");
                        if (gatewayKeyCacheEnabled) {
                            getGatewayBasicAuthResourceCache().put(resourceCacheKey, resourceKey);
                        }
                        return true;
                    } else {
                        // any of the role of the user
                        if (validateInternalUserRoles(scope.getRoles(), userRoleList)) {
                            if (gatewayKeyCacheEnabled) {
                                getGatewayBasicAuthResourceCache().put(resourceCacheKey, resourceKey);
                            }
                            return true;
                        }
                        // check if the roles related to the API resource contains any of the role of the user
                        for (String role : userRoleList) {
                            if (scope.getRoles().contains(role)) {
                                if (gatewayKeyCacheEnabled) {
                                    getGatewayBasicAuthResourceCache().put(resourceCacheKey, resourceKey);
                                }
                                return true;
                            }
                        }
                    }
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Basic Authentication: No scopes for the API resource: ".concat(resourceKey));
            }
            return true;
        }
    } else if (APIConstants.GRAPHQL_API.equals(synCtx.getProperty(APIConstants.API_TYPE))) {
        HashMap<String, String> operationScopeMappingList = (HashMap<String, String>) synCtx.getProperty(APIConstants.SCOPE_OPERATION_MAPPING);
        String[] operationList = ((String) synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE)).split(",");
        for (String operation : operationList) {
            String operationScope = operationScopeMappingList.get(operation);
            if (operationScope != null) {
                if (scopeMap.containsKey(operationScope)) {
                    List<String> operationRoles = scopeMap.get(operationScope).getRoles();
                    boolean userHasOperationRole = false;
                    if (operationRoles.isEmpty()) {
                        userHasOperationRole = true;
                    } else {
                        for (String role : userRoleList) {
                            if (operationRoles.contains(role)) {
                                userHasOperationRole = true;
                                break;
                            }
                        }
                    }
                    if (!userHasOperationRole) {
                        throw new APISecurityException(APISecurityConstants.INVALID_SCOPE, "Scope validation failed");
                    }
                } else {
                    throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR, APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE);
                }
            }
        }
        if (gatewayKeyCacheEnabled) {
            getGatewayBasicAuthResourceCache().put(resourceCacheKey, resourceKey);
        }
        return true;
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Basic Authentication: No OpenAPI found in the gateway for the API: ".concat(apiContext).concat(":").concat(apiVersion));
        }
        return true;
    }
    if (log.isDebugEnabled()) {
        log.debug("Basic Authentication: Scope validation failed for the API resource: ".concat(apiElectedResource));
    }
    throw new APISecurityException(APISecurityConstants.INVALID_SCOPE, "Scope validation failed");
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) Scope(org.wso2.carbon.apimgt.keymgt.model.entity.Scope) HashMap(java.util.HashMap) List(java.util.List) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) MethodStats(org.wso2.carbon.apimgt.gateway.MethodStats)

Example 69 with Scope

use of org.wso2.carbon.apimgt.api.model.Scope in project carbon-apimgt by wso2.

the class JWTValidator method validateScopesForGraphQLSubscriptions.

/**
 * Validate scopes for GraphQL subscription API calls using token scopes in authentication context.
 *
 * @param apiContext            API Context
 * @param apiVersion            API Version
 * @param matchingResource      Matching resource
 * @param jwtToken              JWT Token
 * @param authenticationContext AuthenticationContext
 * @throws APISecurityException if an error occurs
 */
public void validateScopesForGraphQLSubscriptions(String apiContext, String apiVersion, String matchingResource, SignedJWTInfo jwtToken, AuthenticationContext authenticationContext) throws APISecurityException {
    String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    // Generate TokenValidationContext
    TokenValidationContext tokenValidationContext = new TokenValidationContext();
    APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO();
    Set<String> scopeSet = new HashSet<>();
    scopeSet.addAll(authenticationContext.getRequestTokenScopes());
    apiKeyValidationInfoDTO.setScopes(scopeSet);
    tokenValidationContext.setValidationInfoDTO(apiKeyValidationInfoDTO);
    tokenValidationContext.setAccessToken(jwtToken.getToken());
    tokenValidationContext.setHttpVerb(GraphQLConstants.SubscriptionConstants.HTTP_METHOD_NAME);
    tokenValidationContext.setMatchingResource(matchingResource);
    tokenValidationContext.setContext(apiContext);
    tokenValidationContext.setVersion(apiVersion);
    boolean valid = this.apiKeyValidator.validateScopes(tokenValidationContext, tenantDomain);
    if (valid) {
        if (log.isDebugEnabled()) {
            log.debug("Scope validation successful for the resource: " + matchingResource + ", user: " + authenticationContext.getUsername());
        }
    } else {
        String message = "User is NOT authorized to access the Resource: " + matchingResource + ". Scope validation failed.";
        log.debug(message);
        throw new APISecurityException(APISecurityConstants.INVALID_SCOPE, message);
    }
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) TokenValidationContext(org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) HashSet(java.util.HashSet)

Example 70 with Scope

use of org.wso2.carbon.apimgt.api.model.Scope in project carbon-apimgt by wso2.

the class SystemScopesIssuer method getUserRoles.

/**
 * This method is used to get roles list of the user.
 *
 * @param authenticatedUser Authenticated user
 * @return roles list
 */
private String[] getUserRoles(AuthenticatedUser authenticatedUser) {
    String[] userRoles = null;
    String tenantDomain;
    String username;
    if (authenticatedUser.isFederatedUser()) {
        tenantDomain = MultitenantUtils.getTenantDomain(authenticatedUser.getAuthenticatedSubjectIdentifier());
        username = MultitenantUtils.getTenantAwareUsername(authenticatedUser.getAuthenticatedSubjectIdentifier());
    } else {
        tenantDomain = authenticatedUser.getTenantDomain();
        username = authenticatedUser.getUserName();
    }
    String userStoreDomain = authenticatedUser.getUserStoreDomain();
    RealmService realmService = getRealmService();
    try {
        int tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
        // If tenant Id is not set in the tokenReqContext, deriving it from username.
        if (tenantId == 0 || tenantId == -1) {
            tenantId = getTenantIdOfUser(username);
        }
        UserStoreManager userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
        String endUsernameWithDomain = addDomainToName(username, userStoreDomain);
        userRoles = userStoreManager.getRoleListOfUser(endUsernameWithDomain);
    } catch (UserStoreException e) {
        // Log and return since we do not want to stop issuing the token in case of scope validation failures.
        log.error("Error when getting the tenant's UserStoreManager or when getting roles of user ", e);
    }
    return userRoles;
}
Also used : RealmService(org.wso2.carbon.user.core.service.RealmService) UserStoreException(org.wso2.carbon.user.api.UserStoreException) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager)

Aggregations

Scope (org.wso2.carbon.apimgt.api.model.Scope)97 HashMap (java.util.HashMap)76 ArrayList (java.util.ArrayList)58 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)50 Scope (org.wso2.carbon.apimgt.core.models.Scope)41 Map (java.util.Map)39 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)39 LinkedHashSet (java.util.LinkedHashSet)32 LinkedHashMap (java.util.LinkedHashMap)29 HashSet (java.util.HashSet)26 RestVariable (org.wso2.carbon.bpmn.rest.engine.variable.RestVariable)25 List (java.util.List)24 Test (org.testng.annotations.Test)23 JSONObject (org.json.simple.JSONObject)22 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)19 PreparedStatement (java.sql.PreparedStatement)17 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)17 SQLException (java.sql.SQLException)16 Gson (com.google.gson.Gson)15 Connection (java.sql.Connection)15