use of org.wso2.carbon.identity.application.mgt.ApplicationManagementService 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.identity.application.mgt.ApplicationManagementService 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