Search in sources :

Example 51 with Property

use of org.wso2.carbon.event.output.adapter.core.Property in project carbon-apimgt by wso2.

the class SystemScopesIssuer method getScopes.

/**
 * This method is used to retrieve the authorized scopes with respect to a token.
 *
 * @param tokReqMsgCtx token message context
 * @return authorized scopes list
 */
public List<String> getScopes(OAuthTokenReqMessageContext tokReqMsgCtx) {
    List<String> authorizedScopes = null;
    List<String> requestedScopes = new ArrayList<>(Arrays.asList(tokReqMsgCtx.getScope()));
    String clientId = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId();
    AuthenticatedUser authenticatedUser = tokReqMsgCtx.getAuthorizedUser();
    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)) {
            return getAllowedScopes(requestedScopes);
        }
        String grantType = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getGrantType();
        String[] userRoles = null;
        // If GrantType is SAML20_BEARER and CHECK_ROLES_FROM_SAML_ASSERTION is true, or if GrantType is
        // JWT_BEARER and retrieveRolesFromUserStoreForScopeValidation system property is true,
        // use user roles from assertion or jwt otherwise use roles from userstore.
        String isSAML2Enabled = System.getProperty(APIConstants.SystemScopeConstants.CHECK_ROLES_FROM_SAML_ASSERTION);
        String isRetrieveRolesFromUserStoreForScopeValidation = System.getProperty(APIConstants.SystemScopeConstants.RETRIEVE_ROLES_FROM_USERSTORE_FOR_SCOPE_VALIDATION);
        if (GrantType.SAML20_BEARER.toString().equals(grantType) && Boolean.parseBoolean(isSAML2Enabled)) {
            authenticatedUser.setUserStoreDomain("FEDERATED");
            tokReqMsgCtx.setAuthorizedUser(authenticatedUser);
            Assertion assertion = (Assertion) tokReqMsgCtx.getProperty(APIConstants.SystemScopeConstants.SAML2_ASSERTION);
            userRoles = getRolesFromAssertion(assertion);
        } else if (APIConstants.SystemScopeConstants.OAUTH_JWT_BEARER_GRANT_TYPE.equals(grantType) && !(Boolean.parseBoolean(isRetrieveRolesFromUserStoreForScopeValidation))) {
            configureForJWTGrant(tokReqMsgCtx);
            Map<ClaimMapping, String> userAttributes = authenticatedUser.getUserAttributes();
            if (tokReqMsgCtx.getProperty(APIConstants.SystemScopeConstants.ROLE_CLAIM) != null) {
                userRoles = getRolesFromUserAttribute(userAttributes, tokReqMsgCtx.getProperty(APIConstants.SystemScopeConstants.ROLE_CLAIM).toString());
            }
        } else {
            userRoles = getUserRoles(authenticatedUser);
        }
        authorizedScopes = getAuthorizedScopes(userRoles, requestedScopes, appScopes);
    }
    return authorizedScopes;
}
Also used : Assertion(org.opensaml.saml.saml2.core.Assertion) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Example 52 with Property

use of org.wso2.carbon.event.output.adapter.core.Property 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 53 with Property

use of org.wso2.carbon.event.output.adapter.core.Property in project carbon-apimgt by wso2.

the class APIUtilTest method testGetOAuthConfigurationFromAPIMConfig.

@Test
public void testGetOAuthConfigurationFromAPIMConfig() throws Exception {
    String property = "AuthorizationHeader";
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    APIManagerConfigurationService apiManagerConfigurationService = Mockito.mock(APIManagerConfigurationService.class);
    APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
    Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.OAUTH_CONFIGS + property)).thenReturn("APIM_AUTH");
    String authHeader = getOAuthConfigurationFromAPIMConfig(property);
    Assert.assertEquals("APIM_AUTH", authHeader);
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 54 with Property

use of org.wso2.carbon.event.output.adapter.core.Property in project carbon-apimgt by wso2.

the class CustomAPIIndexerTest method testIndexDocumentForNewAPI.

/**
 * This method checks the indexer's behaviour for new APIs which does not have the relevant properties.
 *
 * @throws RegistryException Registry Exception.
 * @throws APIManagementException API Management Exception.
 */
@Test
public void testIndexDocumentForNewAPI() throws APIManagementException, RegistryException {
    Resource resource = new ResourceImpl();
    PowerMockito.mockStatic(APIUtil.class);
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry) (Mockito.anyObject()), Mockito.anyString())).thenReturn(artifactManager);
    GenericArtifact genericArtifact = Mockito.mock(GenericArtifact.class);
    Mockito.when(artifactManager.getGenericArtifact(Mockito.anyString())).thenReturn(genericArtifact);
    Mockito.when(genericArtifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY)).thenReturn("public");
    PowerMockito.when(APIUtil.getAPI(genericArtifact, userRegistry)).thenReturn(Mockito.mock(API.class));
    resource.setProperty(APIConstants.ACCESS_CONTROL, APIConstants.NO_ACCESS_CONTROL);
    resource.setProperty(APIConstants.PUBLISHER_ROLES, APIConstants.NULL_USER_ROLE_LIST);
    resource.setProperty(APIConstants.STORE_VIEW_ROLES, APIConstants.NULL_USER_ROLE_LIST);
    Mockito.doReturn(resource).when(userRegistry).get(Mockito.anyString());
    indexer.getIndexedDocument(file2Index);
    Assert.assertNull(APIConstants.CUSTOM_API_INDEXER_PROPERTY + " property was set for the API which does not " + "require migration", resource.getProperty(APIConstants.CUSTOM_API_INDEXER_PROPERTY));
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) ResourceImpl(org.wso2.carbon.registry.core.ResourceImpl) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Resource(org.wso2.carbon.registry.core.Resource) API(org.wso2.carbon.apimgt.api.model.API) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 55 with Property

use of org.wso2.carbon.event.output.adapter.core.Property in project carbon-apimgt by wso2.

the class CommonThrottleMappingUtil method fromDTOListToConditionList.

/**
 * Converts a list of Throttle Condition DTOs into a list of Condition model objects
 *
 * @param throttleConditionDTOs list of Throttle Condition DTOs
 * @return Derived list of Condition model objects from Throttle Condition DTOs
 * @throws UnsupportedThrottleConditionTypeException
 */
public static List<Condition> fromDTOListToConditionList(List<ThrottleConditionDTO> throttleConditionDTOs) throws UnsupportedThrottleConditionTypeException {
    List<Condition> conditions = new ArrayList<>();
    String errorMessage;
    if (throttleConditionDTOs != null) {
        for (ThrottleConditionDTO dto : throttleConditionDTOs) {
            ThrottleConditionDTO.TypeEnum conditionType = dto.getType();
            if (conditionType != null) {
                switch(conditionType) {
                    case HEADERCONDITION:
                        {
                            if (dto.getHeaderCondition() != null) {
                                conditions.add(fromDTOToHeaderCondition(dto.getHeaderCondition(), dto.isInvertCondition()));
                            } else {
                                errorMessage = RestApiAdminUtils.constructMissingThrottleObjectErrorMessage(ThrottleConditionDTO.TypeEnum.HEADERCONDITION) + dto.toString();
                                throw new UnsupportedThrottleConditionTypeException(errorMessage);
                            }
                            break;
                        }
                    case IPCONDITION:
                        {
                            if (dto.getIpCondition() != null) {
                                conditions.add(fromDTOToIPCondition(dto.getIpCondition(), dto.isInvertCondition()));
                            } else {
                                errorMessage = RestApiAdminUtils.constructMissingThrottleObjectErrorMessage(ThrottleConditionDTO.TypeEnum.IPCONDITION) + dto.toString();
                                throw new UnsupportedThrottleConditionTypeException(errorMessage);
                            }
                            break;
                        }
                    case QUERYPARAMETERCONDITION:
                        {
                            if (dto.getQueryParameterCondition() != null) {
                                conditions.add(fromDTOToQueryParameterCondition(dto.getQueryParameterCondition(), dto.isInvertCondition()));
                            } else {
                                errorMessage = RestApiAdminUtils.constructMissingThrottleObjectErrorMessage(ThrottleConditionDTO.TypeEnum.QUERYPARAMETERCONDITION) + dto.toString();
                                throw new UnsupportedThrottleConditionTypeException(errorMessage);
                            }
                            break;
                        }
                    case JWTCLAIMSCONDITION:
                        {
                            if (dto.getJwtClaimsCondition() != null) {
                                conditions.add(fromDTOToJWTClaimsCondition(dto.getJwtClaimsCondition(), dto.isInvertCondition()));
                            } else {
                                errorMessage = RestApiAdminUtils.constructMissingThrottleObjectErrorMessage(ThrottleConditionDTO.TypeEnum.JWTCLAIMSCONDITION) + dto.toString();
                                throw new UnsupportedThrottleConditionTypeException(errorMessage);
                            }
                            break;
                        }
                    default:
                        return null;
                }
            } else {
                errorMessage = "Condition item 'type' property has not been specified\n" + dto.toString();
                throw new UnsupportedThrottleConditionTypeException(errorMessage);
            }
        }
    }
    return conditions;
}
Also used : IPCondition(org.wso2.carbon.apimgt.api.model.policy.IPCondition) QueryParameterCondition(org.wso2.carbon.apimgt.api.model.policy.QueryParameterCondition) HeaderCondition(org.wso2.carbon.apimgt.api.model.policy.HeaderCondition) Condition(org.wso2.carbon.apimgt.api.model.policy.Condition) JWTClaimsCondition(org.wso2.carbon.apimgt.api.model.policy.JWTClaimsCondition) ArrayList(java.util.ArrayList) UnsupportedThrottleConditionTypeException(org.wso2.carbon.apimgt.api.UnsupportedThrottleConditionTypeException) ThrottleConditionDTO(org.wso2.carbon.apimgt.rest.api.admin.v1.dto.ThrottleConditionDTO)

Aggregations

HashMap (java.util.HashMap)42 ArrayList (java.util.ArrayList)32 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)32 Resource (org.wso2.carbon.registry.core.Resource)23 Map (java.util.Map)21 Test (org.junit.Test)21 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)21 DataResponse (org.wso2.carbon.bpmn.rest.model.common.DataResponse)17 API (org.wso2.carbon.apimgt.api.model.API)16 UserStoreException (org.wso2.carbon.user.api.UserStoreException)16 Path (javax.ws.rs.Path)14 Produces (javax.ws.rs.Produces)14 JSONObject (org.json.simple.JSONObject)14 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)14 List (java.util.List)13 IOException (java.io.IOException)11 QName (javax.xml.namespace.QName)11 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)11 Properties (java.util.Properties)10 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)10