use of org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo in project carbon-apimgt by wso2.
the class AMDefaultKeyManagerImplTest method testCreateApplicationAppNameWithSpecialChars.
@Test
public void testCreateApplicationAppNameWithSpecialChars() throws APIManagementException, KeyManagerClientException {
String applicationName = "ÅÄÖÅÄÖ";
System.setProperty("carbon.home", "jhkjn");
PowerMockito.mockStatic(PrivilegedCarbonContext.class);
OAuthAppRequest oauthRequest = new OAuthAppRequest();
OAuthApplicationInfo oauthApplication = new OAuthApplicationInfo();
oauthApplication.setAppOwner(APP_OWNER);
oauthApplication.setCallBackURL(StringUtils.join(REDIRECT_URIS, ","));
oauthApplication.setClientName(applicationName);
oauthApplication.addParameter(ApplicationConstants.OAUTH_CLIENT_USERNAME, APP_OWNER);
oauthApplication.addParameter(ApplicationConstants.APP_KEY_TYPE, KEY_TYPE);
oauthApplication.setJsonString(getJSONString());
oauthRequest.setMappingId("123");
oauthRequest.setOAuthApplicationInfo(oauthApplication);
PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
ClientInfo response = new ClientInfo();
response.setClientId(CLIENT_ID);
response.setClientName(APP_UUID);
response.setClientSecret(CLIENT_SECRET);
response.setRedirectUris(Arrays.asList(REDIRECT_URIS));
response.setGrantTypes(Arrays.asList(GRANT_TYPES));
Mockito.when(dcrClient.createApplication(Mockito.any(ClientInfo.class))).thenReturn(response);
PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
Mockito.when(APIUtil.getApplicationUUID(Mockito.anyString(), Mockito.anyString())).thenReturn(APP_UUID);
OAuthApplicationInfo oauthApplicationResponse = keyManager.createApplication(oauthRequest);
Assert.assertEquals(StringUtils.join(REDIRECT_URIS, ","), oauthApplicationResponse.getCallBackURL());
Assert.assertEquals(APP_UUID, oauthApplicationResponse.getClientName());
}
use of org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo in project carbon-apimgt by wso2.
the class APIMgtDAOTest method testDeleteSubscriptionsForapiId.
@Test
public void testDeleteSubscriptionsForapiId() throws Exception {
Subscriber subscriber = new Subscriber("testCreateApplicationRegistrationEntry");
String organization = "testOrg";
subscriber.setTenantId(-1234);
subscriber.setEmail("abc@wso2.com");
subscriber.setSubscribedDate(new Date(System.currentTimeMillis()));
apiMgtDAO.addSubscriber(subscriber, null);
Policy applicationPolicy = getApplicationPolicy("testCreateApplicationRegistrationEntry");
SubscriptionPolicy subscriptionPolicy = (SubscriptionPolicy) getSubscriptionPolicy("testCreateApplicationRegistrationEntry");
subscriptionPolicy.setMonetizationPlan(APIConstants.Monetization.FIXED_RATE);
apiMgtDAO.addSubscriptionPolicy((SubscriptionPolicy) subscriptionPolicy);
applicationPolicy.setTenantId(-1234);
apiMgtDAO.addApplicationPolicy((ApplicationPolicy) applicationPolicy);
Application application = new Application("testCreateApplicationRegistrationEntry", subscriber);
application.setTier("testCreateApplicationRegistrationEntry");
application.setId(apiMgtDAO.addApplication(application, "testCreateApplicationRegistrationEntry", organization));
application.setDescription("updated description");
apiMgtDAO.updateApplication(application);
assertEquals(apiMgtDAO.getApplicationById(application.getId()).getDescription(), "updated description");
APIIdentifier apiId = new APIIdentifier("testCreateApplicationRegistrationEntry", "testCreateApplicationRegistrationEntry", "1.0.0");
API api = new API(apiId);
api.setContext("/testCreateApplicationRegistrationEntry");
api.setContextTemplate("/testCreateApplicationRegistrationEntry/{version}");
api.setVersionTimestamp(String.valueOf(System.currentTimeMillis()));
APIPolicy apiPolicy = (APIPolicy) getPolicyAPILevelPerUser("testCreateApplicationRegistrationEntry");
api.setApiLevelPolicy(apiPolicy.getPolicyName());
api.setUUID(UUID.randomUUID().toString());
api.getId().setId(apiMgtDAO.addAPI(api, -1234, organization));
apiId.setTier(subscriptionPolicy.getPolicyName());
ApiTypeWrapper apiTypeWrapper = new ApiTypeWrapper(api);
int subsId = apiMgtDAO.addSubscription(apiTypeWrapper, application, APIConstants.SubscriptionStatus.ON_HOLD, subscriber.getName());
assertTrue(apiMgtDAO.getApplicationsByTier(subscriptionPolicy.getPolicyName()).length > 0);
String subStatus = apiMgtDAO.getSubscriptionStatusById(subsId);
assertEquals(subStatus, APIConstants.SubscriptionStatus.ON_HOLD);
SubscribedAPI subscribedAPI = apiMgtDAO.getSubscriptionById(subsId);
String clientIdProduction = UUID.randomUUID().toString();
String clientIdSandbox = UUID.randomUUID().toString();
apiMgtDAO.createApplicationKeyTypeMappingForManualClients(APIConstants.API_KEY_TYPE_PRODUCTION, application.getId(), clientIdProduction, "Default", UUID.randomUUID().toString());
apiMgtDAO.createApplicationKeyTypeMappingForManualClients(APIConstants.API_KEY_TYPE_SANDBOX, application.getId(), clientIdSandbox, "Default", UUID.randomUUID().toString());
assertTrue(apiMgtDAO.getSubscriptionCount(subscriber, application.getName(), null) > 0);
OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
Mockito.when(keyManager.retrieveApplication(clientIdProduction)).thenReturn(oAuthApplicationInfo);
Mockito.when(keyManager.retrieveApplication(clientIdSandbox)).thenReturn(oAuthApplicationInfo);
assertTrue(apiMgtDAO.getSubscribedAPIs(organization, subscriber, null).size() > 0);
assertEquals(subscribedAPI.getSubCreatedStatus(), APIConstants.SubscriptionCreatedStatus.SUBSCRIBE);
assertEquals(subscribedAPI.getApiId(), apiId);
assertEquals(subscribedAPI.getApplication().getId(), application.getId());
SubscribedAPI subscribedAPIFromUuid = apiMgtDAO.getSubscriptionByUUID(subscribedAPI.getUUID());
assertEquals(subscribedAPIFromUuid.getSubCreatedStatus(), APIConstants.SubscriptionCreatedStatus.SUBSCRIBE);
assertEquals(subscribedAPIFromUuid.getApiId(), apiId);
assertEquals(subscribedAPIFromUuid.getApplication().getId(), application.getId());
apiMgtDAO.updateApplicationStatus(application.getId(), APIConstants.ApplicationStatus.APPLICATION_APPROVED);
String status = apiMgtDAO.getApplicationStatus("testCreateApplicationRegistrationEntry", "testCreateApplicationRegistrationEntry");
assertEquals(status, APIConstants.ApplicationStatus.APPLICATION_APPROVED);
boolean applicationExist = apiMgtDAO.isApplicationExist(application.getName(), subscriber.getName(), null, organization);
assertTrue(applicationExist);
Set<SubscribedAPI> subscribedAPIS = apiMgtDAO.getSubscribedAPIs(subscriber, application.getName(), null);
assertEquals(subscribedAPIS.size(), 1);
apiMgtDAO.updateSubscription(apiId, APIConstants.SubscriptionStatus.BLOCKED, application.getId(), organization);
subscribedAPI.setSubStatus(APIConstants.SubscriptionStatus.REJECTED);
apiMgtDAO.updateSubscription(subscribedAPI);
assertTrue(apiMgtDAO.hasSubscription(subscriptionPolicy.getPolicyName(), subscriber.getName(), PolicyConstants.POLICY_LEVEL_SUB));
assertTrue(apiMgtDAO.hasSubscription(applicationPolicy.getPolicyName(), subscriber.getName(), PolicyConstants.POLICY_LEVEL_APP));
assertTrue(apiMgtDAO.hasSubscription(apiPolicy.getPolicyName(), subscriber.getName(), PolicyConstants.POLICY_LEVEL_API));
assertTrue(apiPolicy.getPolicyName().equals(apiMgtDAO.getAPILevelTier(apiMgtDAO.getAPIID(api.getUuid()))));
apiMgtDAO.recordAPILifeCycleEvent(api.getUuid(), "CREATED", "PUBLISHED", "testCreateApplicationRegistrationEntry", -1234);
apiMgtDAO.updateDefaultAPIPublishedVersion(apiId);
apiMgtDAO.removeAllSubscriptions(api.getUuid());
assertTrue(apiMgtDAO.getAPINamesMatchingContext(api.getContext()).size() > 0);
apiMgtDAO.deleteAPI(api.getUuid());
apiMgtDAO.deleteApplication(application);
apiMgtDAO.removeThrottlePolicy(PolicyConstants.POLICY_LEVEL_APP, "testCreateApplicationRegistrationEntry", -1234);
apiMgtDAO.deleteApplicationKeyMappingByConsumerKey(clientIdProduction);
apiMgtDAO.deleteApplicationMappingByConsumerKey(clientIdSandbox);
deleteSubscriber(subscriber.getId());
}
use of org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo in project carbon-apimgt by wso2.
the class AbstractKeyManagerTestCase method buildFromJSONTest.
@Test
public void buildFromJSONTest() throws APIManagementException {
AbstractKeyManager keyManager = new AMDefaultKeyManagerImpl();
KeyManagerConnectorConfiguration keyManagerConnectorConfiguration = Mockito.mock(DefaultKeyManagerConnectorConfiguration.class);
ServiceReferenceHolder serviceReferenceHolder = PowerMockito.mock(ServiceReferenceHolder.class);
PowerMockito.mockStatic(ServiceReferenceHolder.class);
PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
Mockito.when(serviceReferenceHolder.getKeyManagerConnectorConfiguration(APIConstants.KeyManager.DEFAULT_KEY_MANAGER_TYPE)).thenReturn(keyManagerConnectorConfiguration);
// test with empty json payload
assertNotNull(keyManager.buildFromJSON(new OAuthApplicationInfo(), "{}"));
// test with valid json
String jsonPayload2 = "{ \"callbackUrl\": \"www.google.lk\", \"client_id\": \"XBPcXSfGK47WiEX7enchoP2Dcvga\"," + "\"client_secret\": \"4UD8VX8NaQMtrHCwqzI1tHJLPoca\", \"owner\": \"admin\", \"grantType\": \"password" + " refresh_token\", " + "\"validityPeriod\": \"3600\" }";
OAuthApplicationInfo oAuthApplicationInfo1 = keyManager.buildFromJSON(new OAuthApplicationInfo(), jsonPayload2);
assertEquals("XBPcXSfGK47WiEX7enchoP2Dcvga", oAuthApplicationInfo1.getClientId());
// test with invalid json
try {
keyManager.buildFromJSON(new OAuthApplicationInfo(), "{invalid}");
assertTrue(false);
} catch (APIManagementException e) {
assertEquals("Error occurred while parsing JSON String", e.getMessage());
}
// test with invalid additionalProperties
OAuthApplicationInfo applicationInfo = new OAuthApplicationInfo();
applicationInfo.addParameter("additionalProperties", "{invalid}");
try {
keyManager.buildFromJSON(applicationInfo, "{}");
fail();
} catch (APIManagementException e) {
assertEquals("Error while parsing the addition properties of OAuth application", e.getMessage());
}
}
use of org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo in project carbon-apimgt by wso2.
the class APIConsumerImpl method updateAuthClient.
/**
* @param userId Subscriber name.
* @param application The Application.
* @param tokenType Token type (PRODUCTION | SANDBOX)
* @param callbackUrl callback URL
* @param allowedDomains allowedDomains for token.
* @param validityTime validity time period.
* @param tokenScope Scopes for the requested tokens.
* @param groupingId APIM application id.
* @param jsonString Callback URL for the Application.
* @param keyManagerID Key Manager ID of the relevant Key Manager
* @return
* @throws APIManagementException
*/
@Override
public OAuthApplicationInfo updateAuthClient(String userId, Application application, String tokenType, String callbackUrl, String[] allowedDomains, String validityTime, String tokenScope, String groupingId, String jsonString, String keyManagerID) throws APIManagementException {
boolean tenantFlowStarted = false;
try {
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
tenantFlowStarted = true;
}
final String subscriberName = application.getSubscriber().getName();
boolean isCaseInsensitiveComparisons = Boolean.parseBoolean(getAPIManagerConfiguration().getFirstProperty(APIConstants.API_STORE_FORCE_CI_COMPARISIONS));
boolean isUserAppOwner;
if (isCaseInsensitiveComparisons) {
isUserAppOwner = subscriberName.equalsIgnoreCase(userId);
} else {
isUserAppOwner = subscriberName.equals(userId);
}
if (!isUserAppOwner) {
throw new APIManagementException("user: " + userId + ", attempted to update OAuth application " + "owned by: " + subscriberName);
}
String keyManagerName;
KeyManagerConfigurationDTO keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByUUID(keyManagerID);
String keyManagerTenant;
if (keyManagerConfiguration != null) {
keyManagerName = keyManagerConfiguration.getName();
keyManagerTenant = keyManagerConfiguration.getOrganization();
} else {
// keeping this just in case the name is sent by mistake.
keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByName(tenantDomain, keyManagerID);
if (keyManagerConfiguration == null) {
throw new APIManagementException("Key Manager " + keyManagerID + " couldn't found.", ExceptionCodes.KEY_MANAGER_NOT_REGISTERED);
} else {
keyManagerName = keyManagerID;
keyManagerID = keyManagerConfiguration.getUuid();
keyManagerTenant = keyManagerConfiguration.getOrganization();
}
}
if (!keyManagerConfiguration.isEnabled()) {
throw new APIManagementException("Key Manager " + keyManagerName + " not activated in the requested " + "Tenant", ExceptionCodes.KEY_MANAGER_NOT_ENABLED);
}
if (KeyManagerConfiguration.TokenType.EXCHANGED.toString().equals(keyManagerConfiguration.getTokenType())) {
throw new APIManagementException("Key Manager " + keyManagerName + " doesn't support to generate" + " Client Application", ExceptionCodes.KEY_MANAGER_NOT_SUPPORTED_TOKEN_GENERATION);
}
// Create OauthAppRequest object by passing json String.
OAuthAppRequest oauthAppRequest = ApplicationUtils.createOauthAppRequest(application.getName(), null, callbackUrl, tokenScope, jsonString, application.getTokenType(), keyManagerTenant, keyManagerName);
oauthAppRequest.getOAuthApplicationInfo().addParameter(ApplicationConstants.APP_KEY_TYPE, tokenType);
String consumerKey = apiMgtDAO.getConsumerKeyByApplicationIdKeyTypeKeyManager(application.getId(), tokenType, keyManagerID);
oauthAppRequest.getOAuthApplicationInfo().setClientId(consumerKey);
// get key manager instance.
KeyManager keyManager = KeyManagerHolder.getKeyManagerInstance(keyManagerTenant, keyManagerName);
if (keyManager == null) {
throw new APIManagementException("Key Manager " + keyManagerName + " not initialized in the requested" + "Tenant", ExceptionCodes.KEY_MANAGER_INITIALIZATION_FAILED);
}
// set application attributes
oauthAppRequest.getOAuthApplicationInfo().putAllAppAttributes(application.getApplicationAttributes());
oauthAppRequest.getOAuthApplicationInfo().setApplicationUUID(application.getUUID());
// call update method.
OAuthApplicationInfo updatedAppInfo = keyManager.updateApplication(oauthAppRequest);
apiMgtDAO.updateApplicationKeyTypeMetaData(application.getId(), tokenType, keyManagerID, updatedAppInfo);
JSONObject appLogObject = new JSONObject();
appLogObject.put(APIConstants.AuditLogConstants.APPLICATION_NAME, updatedAppInfo.getClientName());
appLogObject.put("Updated Oauth app with Call back URL", callbackUrl);
appLogObject.put("Updated Oauth app with grant types", jsonString);
APIUtil.logAuditMessage(APIConstants.AuditLogConstants.APPLICATION, appLogObject.toString(), APIConstants.AuditLogConstants.UPDATED, this.username);
return updatedAppInfo;
} finally {
if (tenantFlowStarted) {
endTenantFlow();
}
}
}
use of org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo in project carbon-apimgt by wso2.
the class AMDefaultKeyManagerImpl method validateOAuthAppCreationProperties.
@Override
protected void validateOAuthAppCreationProperties(OAuthApplicationInfo oAuthApplicationInfo) throws APIManagementException {
super.validateOAuthAppCreationProperties(oAuthApplicationInfo);
String type = getType();
KeyManagerConnectorConfiguration keyManagerConnectorConfiguration = ServiceReferenceHolder.getInstance().getKeyManagerConnectorConfiguration(type);
if (keyManagerConnectorConfiguration != null) {
Object additionalProperties = oAuthApplicationInfo.getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES);
if (additionalProperties != null) {
JsonObject additionalPropertiesJson = (JsonObject) new JsonParser().parse((String) additionalProperties);
for (Map.Entry<String, JsonElement> entry : additionalPropertiesJson.entrySet()) {
String additionalProperty = entry.getValue().getAsString();
if (StringUtils.isNotBlank(additionalProperty) && !StringUtils.equals(additionalProperty, APIConstants.KeyManager.NOT_APPLICABLE_VALUE)) {
try {
if (APIConstants.KeyManager.PKCE_MANDATORY.equals(entry.getKey()) || APIConstants.KeyManager.PKCE_SUPPORT_PLAIN.equals(entry.getKey()) || APIConstants.KeyManager.BYPASS_CLIENT_CREDENTIALS.equals(entry.getKey())) {
if (!(additionalProperty.equalsIgnoreCase(Boolean.TRUE.toString()) || additionalProperty.equalsIgnoreCase(Boolean.FALSE.toString()))) {
String errMsg = "Application configuration values cannot have negative values.";
throw new APIManagementException(errMsg, ExceptionCodes.from(ExceptionCodes.INVALID_APPLICATION_ADDITIONAL_PROPERTIES, errMsg));
}
} else {
Long longValue = Long.parseLong(additionalProperty);
if (longValue < 0) {
String errMsg = "Application configuration values cannot have negative values.";
throw new APIManagementException(errMsg, ExceptionCodes.from(ExceptionCodes.INVALID_APPLICATION_ADDITIONAL_PROPERTIES, errMsg));
}
}
} catch (NumberFormatException e) {
String errMsg = "Application configuration values cannot have string values.";
throw new APIManagementException(errMsg, ExceptionCodes.from(ExceptionCodes.INVALID_APPLICATION_ADDITIONAL_PROPERTIES, errMsg));
}
}
}
}
}
}
Aggregations