use of org.wso2.carbon.identity.application.common.model.idp.xsd.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;
}
use of org.wso2.carbon.identity.application.common.model.idp.xsd.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);
}
use of org.wso2.carbon.identity.application.common.model.idp.xsd.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));
}
use of org.wso2.carbon.identity.application.common.model.idp.xsd.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;
}
use of org.wso2.carbon.identity.application.common.model.idp.xsd.Property in project carbon-apimgt by wso2.
the class APIMappingUtil method fromDTOtoAPIProduct.
public static APIProduct fromDTOtoAPIProduct(APIProductDTO dto, String provider) throws APIManagementException {
APIProduct product = new APIProduct();
APIProductIdentifier id = new APIProductIdentifier(APIUtil.replaceEmailDomain(provider), dto.getName(), // todo: replace this with dto.getVersion
APIConstants.API_PRODUCT_VERSION);
product.setID(id);
product.setUuid(dto.getId());
product.setDescription(dto.getDescription());
String context = dto.getContext();
if (context.endsWith("/" + RestApiConstants.API_VERSION_PARAM)) {
context = context.replace("/" + RestApiConstants.API_VERSION_PARAM, "");
}
context = context.startsWith("/") ? context : ("/" + context);
String providerDomain = MultitenantUtils.getTenantDomain(provider);
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(providerDomain) && dto.getId() == null) {
// Create tenant aware context for API
context = "/t/" + providerDomain + context;
}
product.setType(APIConstants.API_PRODUCT_IDENTIFIER_TYPE.replaceAll("\\s", ""));
product.setContext(context);
context = checkAndSetVersionParam(context);
product.setContextTemplate(context);
List<String> apiProductTags = dto.getTags();
Set<String> tagsToReturn = new HashSet<>(apiProductTags);
product.addTags(tagsToReturn);
if (dto.isEnableSchemaValidation() != null) {
product.setEnableSchemaValidation(dto.isEnableSchemaValidation());
}
product.setEnableStore(true);
if (dto.isResponseCachingEnabled() != null && dto.isResponseCachingEnabled()) {
product.setResponseCache(APIConstants.ENABLED);
} else {
product.setResponseCache(APIConstants.DISABLED);
}
if (dto.getCacheTimeout() != null) {
product.setCacheTimeout(dto.getCacheTimeout());
} else {
product.setCacheTimeout(APIConstants.API_RESPONSE_CACHE_TIMEOUT);
}
if (dto.getBusinessInformation() != null) {
product.setBusinessOwner(dto.getBusinessInformation().getBusinessOwner());
product.setBusinessOwnerEmail(dto.getBusinessInformation().getBusinessOwnerEmail());
product.setTechnicalOwner(dto.getBusinessInformation().getTechnicalOwner());
product.setTechnicalOwnerEmail(dto.getBusinessInformation().getTechnicalOwnerEmail());
}
Set<Tier> apiTiers = new HashSet<>();
List<String> tiersFromDTO = dto.getPolicies();
if (dto.getVisibility() != null) {
product.setVisibility(mapVisibilityFromDTOtoAPIProduct(dto.getVisibility()));
}
if (dto.getVisibleRoles() != null) {
String visibleRoles = StringUtils.join(dto.getVisibleRoles(), ',');
product.setVisibleRoles(visibleRoles);
}
if (dto.getVisibleTenants() != null) {
String visibleTenants = StringUtils.join(dto.getVisibleTenants(), ',');
product.setVisibleTenants(visibleTenants);
}
List<String> accessControlRoles = dto.getAccessControlRoles();
if (accessControlRoles == null || accessControlRoles.isEmpty()) {
product.setAccessControl(APIConstants.NO_ACCESS_CONTROL);
product.setAccessControlRoles("null");
} else {
product.setAccessControlRoles(StringUtils.join(accessControlRoles, ',').toLowerCase());
product.setAccessControl(APIConstants.API_RESTRICTED_VISIBILITY);
}
for (String tier : tiersFromDTO) {
apiTiers.add(new Tier(tier));
}
product.setAvailableTiers(apiTiers);
product.setProductLevelPolicy(dto.getApiThrottlingPolicy());
product.setGatewayVendor(dto.getGatewayVendor());
if (dto.getSubscriptionAvailability() != null) {
product.setSubscriptionAvailability(mapSubscriptionAvailabilityFromDTOtoAPIProduct(dto.getSubscriptionAvailability()));
}
List<APIInfoAdditionalPropertiesDTO> additionalProperties = dto.getAdditionalProperties();
if (additionalProperties != null) {
for (APIInfoAdditionalPropertiesDTO property : additionalProperties) {
if (property.isDisplay()) {
product.addProperty(property.getName() + APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX, property.getValue());
} else {
product.addProperty(property.getName(), property.getValue());
}
}
}
if (dto.getSubscriptionAvailableTenants() != null) {
product.setSubscriptionAvailableTenants(StringUtils.join(dto.getSubscriptionAvailableTenants(), ","));
}
String transports = StringUtils.join(dto.getTransport(), ',');
product.setTransports(transports);
List<APIProductResource> productResources = new ArrayList<APIProductResource>();
Set<String> verbResourceCombo = new HashSet<>();
for (ProductAPIDTO res : dto.getApis()) {
List<APIOperationsDTO> productAPIOperationsDTO = res.getOperations();
for (APIOperationsDTO resourceItem : productAPIOperationsDTO) {
if (!verbResourceCombo.add(resourceItem.getVerb() + resourceItem.getTarget())) {
throw new APIManagementException("API Product resource: " + resourceItem.getTarget() + ", with verb: " + resourceItem.getVerb() + " , is duplicated for id " + id, ExceptionCodes.from(ExceptionCodes.API_PRODUCT_DUPLICATE_RESOURCE, resourceItem.getTarget(), resourceItem.getVerb()));
}
URITemplate template = new URITemplate();
template.setHTTPVerb(resourceItem.getVerb());
template.setHttpVerbs(resourceItem.getVerb());
template.setResourceURI(resourceItem.getTarget());
template.setUriTemplate(resourceItem.getTarget());
template.setOperationPolicies(OperationPolicyMappingUtil.fromDTOToAPIOperationPoliciesList(resourceItem.getOperationPolicies()));
APIProductResource resource = new APIProductResource();
resource.setApiId(res.getApiId());
resource.setUriTemplate(template);
productResources.add(resource);
}
}
Set<Scope> scopes = getScopes(dto);
product.setScopes(scopes);
APICorsConfigurationDTO apiCorsConfigurationDTO = dto.getCorsConfiguration();
CORSConfiguration corsConfiguration;
if (apiCorsConfigurationDTO != null) {
corsConfiguration = new CORSConfiguration(apiCorsConfigurationDTO.isCorsConfigurationEnabled(), apiCorsConfigurationDTO.getAccessControlAllowOrigins(), apiCorsConfigurationDTO.isAccessControlAllowCredentials(), apiCorsConfigurationDTO.getAccessControlAllowHeaders(), apiCorsConfigurationDTO.getAccessControlAllowMethods());
} else {
corsConfiguration = APIUtil.getDefaultCorsConfiguration();
}
product.setCorsConfiguration(corsConfiguration);
product.setProductResources(productResources);
product.setApiSecurity(getSecurityScheme(dto.getSecurityScheme()));
product.setAuthorizationHeader(dto.getAuthorizationHeader());
// attach api categories to API model
setAPICategoriesToModel(dto, product, provider);
return product;
}
Aggregations