use of org.wso2.carbon.apimgt.api.model.OAuthAppRequest in project carbon-apimgt by wso2.
the class APIMgtDAOTest method testCreateApplicationRegistrationEntry.
@Test
public void testCreateApplicationRegistrationEntry() throws Exception {
Subscriber subscriber = new Subscriber("testCreateApplicationRegistrationEntry");
subscriber.setTenantId(-1234);
subscriber.setEmail("abc@wso2.com");
subscriber.setSubscribedDate(new Date(System.currentTimeMillis()));
apiMgtDAO.addSubscriber(subscriber, null);
Policy applicationPolicy = getApplicationPolicy("testCreateApplicationRegistrationEntry");
applicationPolicy.setTenantId(-1234);
apiMgtDAO.addApplicationPolicy((ApplicationPolicy) applicationPolicy);
Application application = new Application("testCreateApplicationRegistrationEntry", subscriber);
application.setTier("testCreateApplicationRegistrationEntry");
application.setId(apiMgtDAO.addApplication(application, "testCreateApplicationRegistrationEntry", "testOrg"));
ApplicationRegistrationWorkflowDTO applicationRegistrationWorkflowDTO = new ApplicationRegistrationWorkflowDTO();
applicationRegistrationWorkflowDTO.setApplication(application);
applicationRegistrationWorkflowDTO.setKeyType("PRODUCTION");
applicationRegistrationWorkflowDTO.setDomainList("*");
applicationRegistrationWorkflowDTO.setWorkflowReference(UUID.randomUUID().toString());
applicationRegistrationWorkflowDTO.setValidityTime(100L);
applicationRegistrationWorkflowDTO.setExternalWorkflowReference(UUID.randomUUID().toString());
applicationRegistrationWorkflowDTO.setStatus(WorkflowStatus.CREATED);
applicationRegistrationWorkflowDTO.setKeyManager("Default");
apiMgtDAO.addWorkflowEntry(applicationRegistrationWorkflowDTO);
OAuthAppRequest oAuthAppRequest = new OAuthAppRequest();
OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
oAuthApplicationInfo.setJsonString("");
oAuthApplicationInfo.addParameter("tokenScope", "deafault");
oAuthAppRequest.setOAuthApplicationInfo(oAuthApplicationInfo);
applicationRegistrationWorkflowDTO.setAppInfoDTO(oAuthAppRequest);
APIIdentifier apiId = new APIIdentifier("testCreateApplicationRegistrationEntry", "testCreateApplicationRegistrationEntry", "1.0.0");
API api = new API(apiId);
api.setContext("/testCreateApplicationRegistrationEntry");
api.setContextTemplate("/testCreateApplicationRegistrationEntry/{version}");
api.setUUID(UUID.randomUUID().toString());
api.setVersionTimestamp(String.valueOf(System.currentTimeMillis()));
int internalAPIID2 = apiMgtDAO.addAPI(api, -1234, "org1");
api.getId().setId(internalAPIID2);
api.setOrganization("org1");
APIIdentifier apiId1 = new APIIdentifier("testCreateApplicationRegistrationEntry1", "testCreateApplicationRegistrationEntry1", "1.0.0");
API api1 = new API(apiId1);
api1.setContext("/testCreateApplicationRegistrationEntry1");
api1.setContextTemplate("/testCreateApplicationRegistrationEntry1/{version}");
api1.setUUID(UUID.randomUUID().toString());
int apiInternalId = apiMgtDAO.addAPI(api1, -1234, "org2");
api1.getId().setId(apiInternalId);
api1.setOrganization("org2");
apiMgtDAO.createApplicationRegistrationEntry(applicationRegistrationWorkflowDTO, false);
ApplicationRegistrationWorkflowDTO retrievedApplicationRegistrationWorkflowDTO = new ApplicationRegistrationWorkflowDTO();
retrievedApplicationRegistrationWorkflowDTO.setExternalWorkflowReference(applicationRegistrationWorkflowDTO.getExternalWorkflowReference());
apiMgtDAO.populateAppRegistrationWorkflowDTO(retrievedApplicationRegistrationWorkflowDTO);
ApiTypeWrapper apiTypeWrapper = new ApiTypeWrapper(api);
ApiTypeWrapper apiTypeWrapper1 = new ApiTypeWrapper(api1);
apiMgtDAO.addSubscription(apiTypeWrapper, application, APIConstants.SubscriptionStatus.ON_HOLD, subscriber.getName());
int subsId = apiMgtDAO.addSubscription(apiTypeWrapper1, application, APIConstants.SubscriptionStatus.ON_HOLD, subscriber.getName());
assertTrue(apiMgtDAO.isContextExist(api.getContext()));
assertTrue(api.getContext().equals(apiMgtDAO.getAPIContext(api.getUuid())));
apiMgtDAO.removeSubscription(apiId, application.getId());
apiMgtDAO.removeSubscriptionById(subsId);
apiMgtDAO.deleteAPI(api.getUuid());
apiMgtDAO.deleteAPI(api1.getUuid());
assertNotNull(apiMgtDAO.getWorkflowReference(application.getName(), subscriber.getName()));
applicationRegistrationWorkflowDTO.setStatus(WorkflowStatus.APPROVED);
apiMgtDAO.updateWorkflowStatus(applicationRegistrationWorkflowDTO);
assertNotNull(apiMgtDAO.retrieveWorkflow(applicationRegistrationWorkflowDTO.getExternalWorkflowReference()));
assertNotNull(apiMgtDAO.retrieveWorkflowFromInternalReference(applicationRegistrationWorkflowDTO.getWorkflowReference(), applicationRegistrationWorkflowDTO.getWorkflowType()));
apiMgtDAO.removeWorkflowEntry(applicationRegistrationWorkflowDTO.getExternalWorkflowReference(), applicationRegistrationWorkflowDTO.getWorkflowType());
apiMgtDAO.deleteApplicationKeyMappingByApplicationIdAndType(application.getId(), "PRODUCTION");
apiMgtDAO.deleteApplicationRegistration(application.getId(), "PRODUCTION", APIConstants.KeyManager.DEFAULT_KEY_MANAGER);
apiMgtDAO.deleteApplication(application);
apiMgtDAO.removeThrottlePolicy(PolicyConstants.POLICY_LEVEL_APP, "testCreateApplicationRegistrationEntry", -1234);
deleteSubscriber(subscriber.getId());
}
use of org.wso2.carbon.apimgt.api.model.OAuthAppRequest in project carbon-apimgt by wso2.
the class ApplicationRegistrationSimpleWorkflowExecutorTest method init.
@Before
public void init() throws APIManagementException {
PowerMockito.mockStatic(ApiMgtDAO.class);
PowerMockito.mockStatic(KeyManagerHolder.class);
apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
keyManager = Mockito.mock(KeyManager.class);
application = new Application("test", new Subscriber("testUser"));
oAuthAppRequest = new OAuthAppRequest();
oAuthApplicationInfo = new OAuthApplicationInfo();
oAuthAppRequest.setOAuthApplicationInfo(oAuthApplicationInfo);
workflowDTO = new ApplicationRegistrationWorkflowDTO();
workflowDTO.setWorkflowReference("1");
workflowDTO.setApplication(application);
workflowDTO.setAppInfoDTO(oAuthAppRequest);
workflowDTO.setKeyManager("default");
KeyManagerConfigurationDTO kmConfigDTO = new KeyManagerConfigurationDTO();
kmConfigDTO.setOrganization("carbon.super");
kmConfigDTO.setName("default");
PowerMockito.when(apiMgtDAO.getKeyManagerConfigurationByUUID("default")).thenReturn(kmConfigDTO);
PowerMockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
PowerMockito.when(KeyManagerHolder.getKeyManagerInstance("carbon.super", "default")).thenReturn(keyManager);
KeyManagerConfiguration keyManagerConfiguration = new KeyManagerConfiguration();
Mockito.when(keyManager.getKeyManagerConfiguration()).thenReturn(keyManagerConfiguration);
applicationRegistrationSimpleWorkflowExecutor = new ApplicationRegistrationSimpleWorkflowExecutor();
}
use of org.wso2.carbon.apimgt.api.model.OAuthAppRequest in project carbon-apimgt by wso2.
the class RestApiUtil method registerOAuthApplication.
public static OAuthApplicationInfo registerOAuthApplication(OAuthAppRequest appRequest) {
// Create Oauth Application - Dynamic client registration service
AMDefaultKeyManagerImpl impl = new AMDefaultKeyManagerImpl();
OAuthApplicationInfo returnedAPP = null;
try {
returnedAPP = impl.createApplication(appRequest);
} catch (APIManagementException e) {
log.error("Cannot create OAuth application from provided information, for APP name: " + appRequest.getOAuthApplicationInfo().getClientName(), e);
}
return returnedAPP;
}
use of org.wso2.carbon.apimgt.api.model.OAuthAppRequest in project carbon-apimgt by wso2.
the class RegistrationServiceImpl method createApplication.
/**
* Create a new client application
*
* @param appRequest OAuthAppRequest object with client's payload content
* @return created Application
* @throws APIKeyMgtException if failed to create the a new application
*/
private OAuthApplicationInfo createApplication(String applicationName, OAuthAppRequest appRequest, String grantType) throws APIManagementException {
String userName;
OAuthApplicationInfo applicationInfo = appRequest.getOAuthApplicationInfo();
String appName = applicationInfo.getClientName();
String userId = (String) applicationInfo.getParameter(OAUTH_CLIENT_USERNAME);
boolean isTenantFlowStarted = false;
if (userId == null || userId.isEmpty()) {
return null;
}
userName = MultitenantUtils.getTenantAwareUsername(userId);
String tenantDomain = MultitenantUtils.getTenantDomain(userId);
try {
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
isTenantFlowStarted = true;
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userName);
}
// Creating the service provider
ServiceProvider serviceProvider = new ServiceProvider();
serviceProvider.setApplicationName(applicationName);
serviceProvider.setDescription("Service Provider for application " + appName);
serviceProvider.setSaasApp(applicationInfo.getIsSaasApplication());
ServiceProviderProperty[] serviceProviderProperties = new ServiceProviderProperty[4];
ServiceProviderProperty serviceProviderProperty = new ServiceProviderProperty();
serviceProviderProperty.setName(APP_DISPLAY_NAME);
serviceProviderProperty.setValue(applicationName);
serviceProviderProperties[0] = serviceProviderProperty;
ServiceProviderProperty tokenTypeProviderProperty = new ServiceProviderProperty();
tokenTypeProviderProperty.setName(APIConstants.APP_TOKEN_TYPE);
tokenTypeProviderProperty.setValue(applicationInfo.getTokenType());
serviceProviderProperties[1] = tokenTypeProviderProperty;
ServiceProviderProperty consentProperty = new ServiceProviderProperty();
consentProperty.setDisplayName(APIConstants.APP_SKIP_CONSENT_DISPLAY);
consentProperty.setName(APIConstants.APP_SKIP_CONSENT_NAME);
consentProperty.setValue(APIConstants.APP_SKIP_CONSENT_VALUE);
serviceProviderProperties[2] = consentProperty;
ServiceProviderProperty logoutConsentProperty = new ServiceProviderProperty();
logoutConsentProperty.setDisplayName(APIConstants.APP_SKIP_LOGOUT_CONSENT_DISPLAY);
logoutConsentProperty.setName(APIConstants.APP_SKIP_LOGOUT_CONSENT_NAME);
logoutConsentProperty.setValue(APIConstants.APP_SKIP_LOGOUT_CONSENT_VALUE);
serviceProviderProperties[3] = logoutConsentProperty;
serviceProvider.setSpProperties(serviceProviderProperties);
ApplicationManagementService appMgtService = ApplicationManagementService.getInstance();
appMgtService.createApplication(serviceProvider, tenantDomain, userName);
// Retrieving the created service provider
ServiceProvider createdServiceProvider = appMgtService.getApplicationExcludingFileBasedSPs(applicationName, tenantDomain);
if (createdServiceProvider == null) {
throw new APIManagementException("Error occurred while creating Service Provider " + "Application" + appName);
}
// creating the OAuth app
OAuthConsumerAppDTO createdOauthApp = this.createOAuthApp(applicationName, applicationInfo, grantType, userName);
// Set the OAuthApp in InboundAuthenticationConfig
InboundAuthenticationConfig inboundAuthenticationConfig = new InboundAuthenticationConfig();
InboundAuthenticationRequestConfig[] inboundAuthenticationRequestConfigs = new InboundAuthenticationRequestConfig[1];
InboundAuthenticationRequestConfig inboundAuthenticationRequestConfig = new InboundAuthenticationRequestConfig();
String oAuthType = APIConstants.SWAGGER_12_OAUTH2;
inboundAuthenticationRequestConfig.setInboundAuthType(oAuthType);
inboundAuthenticationRequestConfig.setInboundAuthKey(createdOauthApp.getOauthConsumerKey());
String oauthConsumerSecret = createdOauthApp.getOauthConsumerSecret();
if (oauthConsumerSecret != null && !oauthConsumerSecret.isEmpty()) {
Property property = new Property();
property.setName(ApplicationConstants.INBOUNT_AUTH_CONSUMER_SECRET);
property.setValue(oauthConsumerSecret);
Property[] properties = { property };
inboundAuthenticationRequestConfig.setProperties(properties);
}
inboundAuthenticationRequestConfigs[0] = inboundAuthenticationRequestConfig;
inboundAuthenticationConfig.setInboundAuthenticationRequestConfigs(inboundAuthenticationRequestConfigs);
createdServiceProvider.setInboundAuthenticationConfig(inboundAuthenticationConfig);
// Setting the SaasApplication attribute to created service provider
createdServiceProvider.setSaasApp(applicationInfo.getIsSaasApplication());
createdServiceProvider.setSpProperties(serviceProviderProperties);
// Updating the service provider with Inbound Authentication Configs and SaasApplication
appMgtService.updateApplication(createdServiceProvider, tenantDomain, userName);
Map<String, String> valueMap = new HashMap<String, String>();
valueMap.put(OAUTH_REDIRECT_URIS, createdOauthApp.getCallbackUrl());
valueMap.put(OAUTH_CLIENT_NAME, createdOauthApp.getApplicationName());
valueMap.put(OAUTH_CLIENT_GRANT, createdOauthApp.getGrantTypes());
return this.fromAppDTOToApplicationInfo(createdOauthApp.getOauthConsumerKey(), applicationName, createdOauthApp.getCallbackUrl(), createdOauthApp.getOauthConsumerSecret(), createdServiceProvider.isSaasApp(), userId, valueMap);
} catch (IdentityApplicationManagementException e) {
log.error("Error occurred while creating the client application " + appName, e);
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.getThreadLocalCarbonContext().endTenantFlow();
}
}
return null;
}
use of org.wso2.carbon.apimgt.api.model.OAuthAppRequest in project carbon-apimgt by wso2.
the class RegistrationServiceImpl method register.
@POST
@Override
public Response register(RegistrationProfile profile) {
/**
* sample message to this method
* {
* "callbackUrl": "www.google.lk",
* "clientName": "mdm",
* "tokenScope": "Production",
* "owner": "admin",
* "grantType": "password refresh_token",
* "saasApp": true
*}
*/
Response response;
String applicationName = null;
ErrorDTO errorDTO;
try {
OAuthAppRequest appRequest = new OAuthAppRequest();
OAuthApplicationInfo oauthApplicationInfo = new OAuthApplicationInfo();
OAuthApplicationInfo returnedAPP;
String loggedInUserTenantDomain;
String owner = profile.getOwner();
String authUserName = RestApiCommonUtil.getLoggedInUsername();
// correct domain
if (owner != null && authUserName != null) {
int index = authUserName.indexOf(UserCoreConstants.DOMAIN_SEPARATOR);
int ownerIndex = owner.indexOf(UserCoreConstants.DOMAIN_SEPARATOR);
if (index > 0 && ownerIndex < 0) {
if (!UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equalsIgnoreCase(authUserName.substring(0, index)) && owner.equals(authUserName.substring(index + 1))) {
if (log.isDebugEnabled()) {
log.debug("Update profile user name :" + owner + " with " + authUserName);
}
owner = authUserName;
profile.setOwner(owner);
}
}
}
// Validates if the application owner and logged in username is same.
if (authUserName != null && ((authUserName.equals(owner)) || isUserSuperAdmin(authUserName))) {
if (!isUserAccessAllowed(authUserName)) {
String errorMsg = "You do not have enough privileges to create an OAuth app";
log.error("User " + authUserName + " does not have any of subscribe/create/publish privileges " + "to create an OAuth app");
errorDTO = RestApiUtil.getErrorDTO(RestApiConstants.STATUS_FORBIDDEN_MESSAGE_DEFAULT, 403L, errorMsg);
response = Response.status(Response.Status.FORBIDDEN).entity(errorDTO).build();
return response;
}
// Getting client credentials from the profile
String grantTypes = profile.getGrantType();
oauthApplicationInfo.setClientName(profile.getClientName());
if (StringUtils.isNotBlank(profile.getCallbackUrl())) {
oauthApplicationInfo.setCallBackURL(profile.getCallbackUrl());
} else {
String[] grantTypeArr = grantTypes.split(" ");
for (String grantType : grantTypeArr) {
if ((grantType.equalsIgnoreCase(ApplicationConstants.AUTHORIZATION_CODE)) || (grantType.equalsIgnoreCase(ApplicationConstants.IMPLICIT_CONST))) {
grantTypes = grantTypes.replace(grantType, "");
}
}
}
String tokenType = APIConstants.DEFAULT_TOKEN_TYPE;
String profileTokenType = profile.getTokenType();
if (StringUtils.isNotEmpty(profileTokenType)) {
tokenType = profileTokenType;
}
oauthApplicationInfo.addParameter(OAUTH_CLIENT_USERNAME, owner);
oauthApplicationInfo.setClientId("");
oauthApplicationInfo.setClientSecret("");
oauthApplicationInfo.setIsSaasApplication(profile.isSaasApp());
oauthApplicationInfo.setTokenType(tokenType);
appRequest.setOAuthApplicationInfo(oauthApplicationInfo);
if (!authUserName.equals(owner)) {
loggedInUserTenantDomain = MultitenantUtils.getTenantDomain(owner);
} else {
loggedInUserTenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
}
String userId = (String) oauthApplicationInfo.getParameter(OAUTH_CLIENT_USERNAME);
String userNameForSP = MultitenantUtils.getTenantAwareUsername(userId);
// Replace domain separator by "_" if user is coming from a secondary userstore.
String domain = UserCoreUtil.extractDomainFromName(userNameForSP);
if (domain != null && !domain.isEmpty() && !UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equals(domain)) {
userNameForSP = userNameForSP.replace(UserCoreConstants.DOMAIN_SEPARATOR, "_");
}
applicationName = profile.getClientName();
ApplicationManagementService applicationManagementService = ApplicationManagementService.getInstance();
// Check if the application is already exists
ServiceProvider appServiceProvider = null;
try {
appServiceProvider = applicationManagementService.getApplicationExcludingFileBasedSPs(applicationName, loggedInUserTenantDomain);
} catch (IdentityApplicationManagementException e) {
log.error("Error occurred while checking the existence of the application " + applicationName, e);
}
// Retrieving the existing application
if (appServiceProvider != null) {
returnedAPP = this.getExistingApp(applicationName, appServiceProvider.isSaasApp());
} else {
// create a new application if the application doesn't exists.
returnedAPP = this.createApplication(applicationName, appRequest, grantTypes);
}
// ReturnedAPP is null
if (returnedAPP == null) {
String errorMsg = "OAuth app '" + profile.getClientName() + "' creation or updating failed." + " Dynamic Client Registration Service not available.";
log.error(errorMsg);
errorDTO = RestApiUtil.getErrorDTO(RestApiConstants.STATUS_BAD_REQUEST_MESSAGE_DEFAULT, 500L, errorMsg);
response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorDTO).build();
} else {
if (log.isDebugEnabled()) {
log.debug("OAuth app " + profile.getClientName() + " creation successful.");
}
response = Response.status(Response.Status.OK).entity(returnedAPP).build();
}
} else {
String errorMsg = "Logged in user '" + authUserName + "' and application owner '" + owner + "' should be same.";
errorDTO = RestApiUtil.getErrorDTO(RestApiConstants.STATUS_BAD_REQUEST_MESSAGE_DEFAULT, 400L, errorMsg);
response = Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
}
} catch (APIManagementException e) {
String errorMsg = "Error occurred while trying to create the client application " + applicationName;
log.error(errorMsg, e);
errorDTO = RestApiUtil.getErrorDTO(RestApiConstants.STATUS_BAD_REQUEST_MESSAGE_DEFAULT, 500L, errorMsg);
response = Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
}
return response;
}
Aggregations