Search in sources :

Example 71 with Scope

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

the class SystemScopesIssuer method validateScope.

@Override
public boolean validateScope(OAuth2TokenValidationMessageContext oAuth2TokenValidationMessageContext) throws IdentityOAuth2Exception {
    AccessTokenDO accessTokenDO = (AccessTokenDO) oAuth2TokenValidationMessageContext.getProperty(ACCESS_TOKEN_DO);
    if (accessTokenDO == null) {
        return false;
    }
    String resource = getResourceFromMessageContext(oAuth2TokenValidationMessageContext);
    // Return true if there is no resource to validate the token against.
    if (resource == null) {
        return true;
    }
    // Get the list of scopes associated with the access token
    String[] scopes = accessTokenDO.getScope();
    // If no scopes are associated with the token
    if (scopes == null || scopes.length == 0) {
        return true;
    }
    String resourceScope = null;
    int resourceTenantId = -1;
    boolean cacheHit = false;
    // Check the cache, if caching is enabled.
    OAuthCacheKey cacheKey = new OAuthCacheKey(resource);
    CacheEntry result = OAuthCache.getInstance().getValueFromCache(cacheKey);
    // Cache hit
    if (result != null && result instanceof ResourceScopeCacheEntry) {
        resourceScope = ((ResourceScopeCacheEntry) result).getScope();
        resourceTenantId = ((ResourceScopeCacheEntry) result).getTenantId();
        cacheHit = true;
    }
    // Cache was not hit. So retrieve from database.
    if (!cacheHit) {
        Pair<String, Integer> scopeMap = OAuthTokenPersistenceFactory.getInstance().getTokenManagementDAO().findTenantAndScopeOfResource(resource);
        if (scopeMap != null) {
            resourceScope = scopeMap.getLeft();
            resourceTenantId = scopeMap.getRight();
        }
        cacheKey = new OAuthCacheKey(resource);
        ResourceScopeCacheEntry cacheEntry = new ResourceScopeCacheEntry(resourceScope);
        cacheEntry.setTenantId(resourceTenantId);
        // Store resourceScope in cache even if it is null (to avoid database calls when accessing resources for
        // which scopes haven't been defined).
        OAuthCache.getInstance().addToCache(cacheKey, cacheEntry);
    }
    // Return TRUE if - There does not exist a scope definition for the resource
    if (resourceScope == null) {
        if (log.isDebugEnabled()) {
            log.debug("Resource '" + resource + "' is not protected with a scope");
        }
        return true;
    }
    List<String> scopeList = new ArrayList<>(Arrays.asList(scopes));
    // If the access token does not bear the scope required for accessing the Resource.
    if (!scopeList.contains(resourceScope)) {
        if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
            log.debug("Access token '" + accessTokenDO.getAccessToken() + "' does not bear the scope '" + resourceScope + "'");
        }
        return false;
    }
    // This system property is set at server start using -D option, Thus will be a permanent property.
    if (accessTokenDO.getAuthzUser().isFederatedUser() && (Boolean.parseBoolean(System.getProperty(CHECK_ROLES_FROM_SAML_ASSERTION)) || !(Boolean.parseBoolean(System.getProperty(RETRIEVE_ROLES_FROM_USERSTORE_FOR_SCOPE_VALIDATION))))) {
        return true;
    }
    AuthenticatedUser authenticatedUser = OAuthUtil.getAuthenticatedUser(oAuth2TokenValidationMessageContext.getResponseDTO().getAuthorizedUser());
    String clientId = accessTokenDO.getConsumerKey();
    List<String> requestedScopes = Arrays.asList(scopes);
    List<String> authorizedScopes = null;
    String[] userRoles = null;
    Map<String, String> appScopes = getAppScopes(clientId, authenticatedUser, requestedScopes);
    if (appScopes != null) {
        // If no scopes can be found in the context of the application
        if (isAppScopesEmpty(appScopes, clientId)) {
            authorizedScopes = getAllowedScopes(requestedScopes);
            oAuth2TokenValidationMessageContext.getResponseDTO().setScope(authorizedScopes.toArray(new String[authorizedScopes.size()]));
            return true;
        }
        userRoles = getUserRoles(authenticatedUser);
        authorizedScopes = getAuthorizedScopes(userRoles, requestedScopes, appScopes);
        oAuth2TokenValidationMessageContext.getResponseDTO().setScope(authorizedScopes.toArray(new String[authorizedScopes.size()]));
    }
    if (ArrayUtils.isEmpty(userRoles)) {
        if (log.isDebugEnabled()) {
            log.debug("No roles associated for the user " + authenticatedUser.getUserName());
        }
        return false;
    }
    return true;
}
Also used : ResourceScopeCacheEntry(org.wso2.carbon.identity.oauth2.model.ResourceScopeCacheEntry) CacheEntry(org.wso2.carbon.identity.oauth.cache.CacheEntry) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) OAuthCacheKey(org.wso2.carbon.identity.oauth.cache.OAuthCacheKey) ResourceScopeCacheEntry(org.wso2.carbon.identity.oauth2.model.ResourceScopeCacheEntry)

Example 72 with Scope

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

the class APIConsumerImpl method getScopesForApplicationSubscription.

public Set<Scope> getScopesForApplicationSubscription(String username, int applicationId, String organization) throws APIManagementException {
    Subscriber subscriber = new Subscriber(username);
    Set<String> scopeKeySet = apiMgtDAO.getScopesForApplicationSubscription(subscriber, applicationId);
    return new LinkedHashSet<>(APIUtil.getScopes(scopeKeySet, organization).values());
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber)

Example 73 with Scope

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

the class AMDefaultKeyManagerImpl method updateScope.

/**
 * This method will be used to update a Scope in the authorization server.
 *
 * @param scope Scope object
 * @throws APIManagementException if an error occurs while updating the scope
 */
@Override
public void updateScope(Scope scope) throws APIManagementException {
    String scopeKey = scope.getKey();
    try {
        ScopeDTO scopeDTO = new ScopeDTO();
        scopeDTO.setDisplayName(scope.getName());
        scopeDTO.setDescription(scope.getDescription());
        if (StringUtils.isNotBlank(scope.getRoles()) && scope.getRoles().trim().split(",").length > 0) {
            scopeDTO.setBindings(Arrays.asList(scope.getRoles().trim().split(",")));
        }
        scopeClient.updateScope(scopeDTO, scope.getKey());
    } catch (KeyManagerClientException e) {
        String errorMessage = "Error occurred while updating scope: " + scopeKey;
        handleException(errorMessage, e);
    }
}
Also used : KeyManagerClientException(org.wso2.carbon.apimgt.impl.kmclient.KeyManagerClientException) ScopeDTO(org.wso2.carbon.apimgt.impl.dto.ScopeDTO)

Example 74 with Scope

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

the class AMDefaultKeyManagerImpl method validateScopes.

/**
 * This method will be used to validate the scope set provided and populate the additional parameters
 * (description and bindings) for each Scope object.
 *
 * @param scopes Scope set to validate
 * @throws APIManagementException if an error occurs while validating and populating
 */
@Override
public void validateScopes(Set<Scope> scopes) throws APIManagementException {
    for (Scope scope : scopes) {
        Scope sharedScope = getScopeByName(scope.getKey());
        scope.setName(sharedScope.getName());
        scope.setDescription(sharedScope.getDescription());
        scope.setRoles(sharedScope.getRoles());
    }
}
Also used : Scope(org.wso2.carbon.apimgt.api.model.Scope)

Example 75 with Scope

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

the class OASTestBase method testGetScopes.

public void testGetScopes(APIDefinition parser, String content) throws Exception {
    JSONObject jsonObject = new JSONObject(content);
    String scopesOnlyInSecurity = jsonObject.getJSONObject("scopesOnlyInSecurity").toString();
    Set<Scope> scopes = parser.getScopes(scopesOnlyInSecurity);
    Assert.assertEquals(2, scopes.size());
    scopes.toArray()[0].equals(sampleScope);
    Assert.assertTrue(scopes.contains(sampleScope));
    Assert.assertTrue(scopes.contains(extensionScope));
    String scopesOnlyInExtension = jsonObject.getJSONObject("scopesOnlyInExtension").toString();
    scopes = parser.getScopes(scopesOnlyInExtension);
    Assert.assertEquals(2, scopes.size());
    Assert.assertTrue(scopes.contains(sampleScope));
    Assert.assertTrue(scopes.contains(extensionScope));
    String scopesInExtensionAndSec = jsonObject.getJSONObject("scopesInExtensionAndSec").toString();
    scopes = parser.getScopes(scopesInExtensionAndSec);
    Assert.assertEquals(2, scopes.size());
    Assert.assertTrue(scopes.contains(sampleScope));
    Assert.assertTrue(scopes.contains(extensionScope));
}
Also used : JSONObject(org.json.JSONObject) Scope(org.wso2.carbon.apimgt.api.model.Scope)

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