use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.
the class APIConsumerImpl method mapExistingOAuthClient.
/**
* @param jsonString this string will contain oAuth app details
* @param userName user name of logged in user.
* @param clientId this is the consumer key of oAuthApplication
* @param applicationName this is the APIM appication name.
* @param keyType
* @param tokenType this is theApplication Token Type. This can be either default or jwt.
* @param keyManagerName key Manager name
* @return
* @throws APIManagementException
*/
@Override
public Map<String, Object> mapExistingOAuthClient(String jsonString, String userName, String clientId, String applicationName, String keyType, String tokenType, String keyManagerName, String tenantDomain) throws APIManagementException {
String callBackURL = null;
if (StringUtils.isEmpty(tenantDomain)) {
tenantDomain = MultitenantUtils.getTenantDomain(userName);
}
String keyManagerId = null;
KeyManagerConfigurationDTO keyManagerConfiguration = null;
if (keyManagerName != null) {
keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByName(tenantDomain, keyManagerName);
if (keyManagerConfiguration == null) {
keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByUUID(keyManagerName);
if (keyManagerConfiguration != null) {
keyManagerId = keyManagerName;
keyManagerName = keyManagerConfiguration.getName();
}
} else {
keyManagerId = keyManagerConfiguration.getUuid();
}
} else {
keyManagerName = APIConstants.KeyManager.DEFAULT_KEY_MANAGER;
keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByName(tenantDomain, keyManagerName);
keyManagerId = keyManagerConfiguration.getUuid();
}
if (keyManagerConfiguration == null || !keyManagerConfiguration.isEnabled()) {
throw new APIManagementException("Key Manager " + keyManagerName + " doesn't exist in Tenant " + tenantDomain, ExceptionCodes.KEY_MANAGER_NOT_REGISTERED);
}
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_SUPPORT_OAUTH_APP_CREATION);
}
OAuthAppRequest oauthAppRequest = ApplicationUtils.createOauthAppRequest(applicationName, clientId, callBackURL, "default", jsonString, tokenType, tenantDomain, keyManagerName);
// if clientId is null in the argument `ApplicationUtils#createOauthAppRequest` will set it using
// the props in `jsonString`. Hence we are taking the updated `clientId` here
clientId = oauthAppRequest.getOAuthApplicationInfo().getClientId();
KeyManager keyManager = KeyManagerHolder.getKeyManagerInstance(tenantDomain, keyManagerName);
if (keyManager == null) {
throw new APIManagementException("Key Manager " + keyManagerName + "Couldn't initialized in tenant " + tenantDomain + ".", ExceptionCodes.KEY_MANAGER_NOT_REGISTERED);
}
// Get application ID
int applicationId = apiMgtDAO.getApplicationId(applicationName, userName);
// Checking if clientId is mapped with another application.
if (apiMgtDAO.isKeyMappingExistsForConsumerKeyOrApplication(applicationId, keyManagerName, keyManagerId, keyType, clientId)) {
throw new APIManagementException("Key Mappings already exists for application " + applicationName + " or consumer key " + clientId, ExceptionCodes.KEY_MAPPING_ALREADY_EXIST);
}
if (log.isDebugEnabled()) {
log.debug("Client ID " + clientId + " not mapped previously with another application. No existing " + "key mappings available for application " + applicationName);
}
// createApplication on oAuthorization server.
OAuthApplicationInfo oAuthApplication = isOauthAppValidation() ? keyManager.mapOAuthApplication(oauthAppRequest) : oauthAppRequest.getOAuthApplicationInfo();
// Do application mapping with consumerKey.
String keyMappingId = UUID.randomUUID().toString();
apiMgtDAO.createApplicationKeyTypeMappingForManualClients(keyType, applicationId, clientId, keyManagerId, keyMappingId);
Object enableTokenGeneration = keyManager.getKeyManagerConfiguration().getParameter(APIConstants.KeyManager.ENABLE_TOKEN_GENERATION);
AccessTokenInfo tokenInfo;
if (enableTokenGeneration != null && (Boolean) enableTokenGeneration && oAuthApplication.getJsonString().contains(APIConstants.GRANT_TYPE_CLIENT_CREDENTIALS)) {
AccessTokenRequest tokenRequest = ApplicationUtils.createAccessTokenRequest(keyManager, oAuthApplication, null);
tokenInfo = keyManager.getNewApplicationAccessToken(tokenRequest);
} else {
tokenInfo = new AccessTokenInfo();
tokenInfo.setAccessToken("");
tokenInfo.setValidityPeriod(0L);
String[] noScopes = new String[] { "N/A" };
tokenInfo.setScope(noScopes);
oAuthApplication.addParameter("tokenScope", Arrays.toString(noScopes));
}
Map<String, Object> keyDetails = new HashMap<String, Object>();
if (tokenInfo != null) {
keyDetails.put("validityTime", tokenInfo.getValidityPeriod());
keyDetails.put("accessToken", tokenInfo.getAccessToken());
keyDetails.put("tokenDetails", tokenInfo.getJSONString());
}
keyDetails.put(APIConstants.FrontEndParameterNames.CONSUMER_KEY, oAuthApplication.getClientId());
keyDetails.put(APIConstants.FrontEndParameterNames.CONSUMER_SECRET, oAuthApplication.getParameter("client_secret"));
keyDetails.put(APIConstants.FrontEndParameterNames.CLIENT_DETAILS, oAuthApplication.getJsonString());
keyDetails.put(APIConstants.FrontEndParameterNames.KEY_MAPPING_ID, keyMappingId);
keyDetails.put(APIConstants.FrontEndParameterNames.MODE, APIConstants.OAuthAppMode.MAPPED.name());
return keyDetails;
}
use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.
the class APIConsumerImpl method renewAccessToken.
/**
* Re-generates the access token.
*
* @param oldAccessToken Token to be revoked
* @param clientId Consumer Key for the Application
* @param clientSecret Consumer Secret for the Application
* @param validityTime Desired Validity time for the token
* @param requestedScopes Requested Scopes
* @param jsonInput Additional parameters if Authorization server needs any.
* @param keyManagerName Configured Key Manager
* @param grantType Grant Type
* @return
* @throws APIManagementException
*/
@Override
public AccessTokenInfo renewAccessToken(String oldAccessToken, String clientId, String clientSecret, String validityTime, String[] requestedScopes, String jsonInput, String keyManagerName, String grantType) throws APIManagementException {
// Create Token Request with parameters provided from UI.
AccessTokenRequest tokenRequest = new AccessTokenRequest();
tokenRequest.setClientId(clientId);
tokenRequest.setClientSecret(clientSecret);
tokenRequest.setValidityPeriod(Long.parseLong(validityTime));
tokenRequest.setTokenToRevoke(oldAccessToken);
tokenRequest.setScope(requestedScopes);
tokenRequest.setGrantType(grantType);
try {
// Populating additional parameters.
KeyManagerConfigurationDTO keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByUUID(keyManagerName);
String keyManagerTenant = tenantDomain;
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, keyManagerName);
if (keyManagerConfiguration == null) {
throw new APIManagementException("Key Manager " + keyManagerName + " couldn't found.", ExceptionCodes.KEY_MANAGER_NOT_REGISTERED);
}
}
if (keyManagerConfiguration.isEnabled()) {
Object enableTokenGeneration = keyManagerConfiguration.getProperty(APIConstants.KeyManager.ENABLE_TOKEN_GENERATION);
if (enableTokenGeneration != null && !(Boolean) enableTokenGeneration) {
throw new APIManagementException("Key Manager didn't support to generate token Generation From portal", ExceptionCodes.KEY_MANAGER_NOT_SUPPORTED_TOKEN_GENERATION);
}
KeyManager keyManager = KeyManagerHolder.getKeyManagerInstance(keyManagerTenant, keyManagerName);
if (keyManager == null) {
throw new APIManagementException("Key Manager " + keyManagerName + " not initialized", ExceptionCodes.KEY_MANAGER_INITIALIZATION_FAILED);
}
tokenRequest = ApplicationUtils.populateTokenRequest(keyManager, jsonInput, tokenRequest);
JSONObject appLogObject = new JSONObject();
appLogObject.put("Re-Generated Keys for application with client Id", clientId);
APIUtil.logAuditMessage(APIConstants.AuditLogConstants.APPLICATION, appLogObject.toString(), APIConstants.AuditLogConstants.UPDATED, this.username);
return keyManager.getNewApplicationAccessToken(tokenRequest);
} else {
throw new APIManagementException("Key Manager " + keyManagerName + " not enabled", ExceptionCodes.KEY_MANAGER_NOT_ENABLED);
}
} catch (APIManagementException e) {
log.error("Error while re-generating AccessToken", e);
throw e;
}
}
use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.
the class APIConsumerImpl method updateApplicationOwner.
public boolean updateApplicationOwner(String userId, String organization, Application application) throws APIManagementException {
boolean isAppUpdated;
String consumerKey;
String oldUserName = application.getSubscriber().getName();
String oldTenantDomain = MultitenantUtils.getTenantDomain(oldUserName);
String newTenantDomain = MultitenantUtils.getTenantDomain(userId);
if (oldTenantDomain.equals(newTenantDomain)) {
if (!isSubscriberValid(userId)) {
RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
try {
int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(newTenantDomain);
UserStoreManager userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
if (userStoreManager.isExistingUser(userId)) {
if (apiMgtDAO.getSubscriber(userId) == null) {
addSubscriber(userId, "");
}
} else {
throw new APIManagementException("User " + userId + " doesn't exist in user store");
}
} catch (UserStoreException e) {
throw new APIManagementException("Error while adding user " + userId + " as a subscriber");
}
}
String applicationName = application.getName();
if (!APIUtil.isApplicationOwnedBySubscriber(userId, applicationName, organization)) {
for (APIKey apiKey : application.getKeys()) {
KeyManager keyManager = KeyManagerHolder.getKeyManagerInstance(tenantDomain, apiKey.getKeyManager());
/* retrieving OAuth application information for specific consumer key */
consumerKey = apiKey.getConsumerKey();
OAuthApplicationInfo oAuthApplicationInfo = keyManager.retrieveApplication(consumerKey);
if (oAuthApplicationInfo.getParameter(ApplicationConstants.OAUTH_CLIENT_NAME) != null) {
OAuthAppRequest oauthAppRequest = ApplicationUtils.createOauthAppRequest(oAuthApplicationInfo.getParameter(ApplicationConstants.OAUTH_CLIENT_NAME).toString(), null, oAuthApplicationInfo.getCallBackURL(), null, null, application.getTokenType(), this.tenantDomain, apiKey.getKeyManager());
oauthAppRequest.getOAuthApplicationInfo().setAppOwner(userId);
oauthAppRequest.getOAuthApplicationInfo().setClientId(consumerKey);
/* updating the owner of the OAuth application with userId */
OAuthApplicationInfo updatedAppInfo = keyManager.updateApplicationOwner(oauthAppRequest, userId);
isAppUpdated = true;
audit.info("Successfully updated the owner of application " + application.getName() + " from " + oldUserName + " to " + userId + ".");
} else {
throw new APIManagementException("Unable to retrieve OAuth application information.");
}
}
} else {
throw new APIManagementException("Unable to update application owner to " + userId + " as this user has an application with the same name. Update owner to another user.");
}
} else {
throw new APIManagementException("Unable to update application owner to " + userId + " as this user does not belong to " + oldTenantDomain + " domain.");
}
isAppUpdated = apiMgtDAO.updateApplicationOwner(userId, application);
return isAppUpdated;
}
use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.
the class APIConsumerImpl method getApplicationKeyByAppIDAndKeyMapping.
@Override
public APIKey getApplicationKeyByAppIDAndKeyMapping(int applicationId, String keyMappingId) throws APIManagementException {
APIKey apiKey = apiMgtDAO.getKeyMappingFromApplicationIdAndKeyMappingId(applicationId, keyMappingId);
String keyManagerId = apiKey.getKeyManager();
String consumerKey = apiKey.getConsumerKey();
KeyManagerConfigurationDTO keyManagerConfigurationDTO = apiMgtDAO.getKeyManagerConfigurationByUUID(keyManagerId);
if (keyManagerConfigurationDTO != null) {
String keyManagerName = keyManagerConfigurationDTO.getName();
KeyManager keyManager = KeyManagerHolder.getKeyManagerInstance(this.tenantDomain, keyManagerName);
if (keyManager != null) {
OAuthApplicationInfo oAuthApplicationInfo = keyManager.retrieveApplication(consumerKey);
if (oAuthApplicationInfo != null) {
apiKey.setConsumerSecret(oAuthApplicationInfo.getClientSecret());
apiKey.setGrantTypes((String) oAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES));
apiKey.setCallbackUrl(oAuthApplicationInfo.getCallBackURL());
apiKey.setAdditionalProperties(oAuthApplicationInfo.getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES));
}
}
}
return apiKey;
}
use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.
the class ApplicationUtils method createOauthAppRequest.
/**
* This method will parse json String and set properties in OAuthApplicationInfo object.
* Further it will initiate new OauthAppRequest object and set applicationInfo object as its own property.
* @param clientName client Name.
* @param clientId The ID of the client
* @param callbackURL This is the call back URL of the application
* @param tokenScope The token scope
* @param clientDetails The client details
* @param tenantDomain
* @param keyManagerName
* @return appRequest object of OauthAppRequest.
* @throws APIManagementException
*/
public static OAuthAppRequest createOauthAppRequest(String clientName, String clientId, String callbackURL, String tokenScope, String clientDetails, String tokenType, String tenantDomain, String keyManagerName) throws APIManagementException {
// initiate OauthAppRequest object.
OAuthAppRequest appRequest = new OAuthAppRequest();
OAuthApplicationInfo authApplicationInfo = new OAuthApplicationInfo();
authApplicationInfo.setClientName(clientName);
authApplicationInfo.setCallBackURL(callbackURL);
authApplicationInfo.addParameter("tokenScope", tokenScope);
authApplicationInfo.setClientId(clientId);
authApplicationInfo.setTokenType(tokenType);
if (clientDetails != null) {
// parse json string and set applicationInfo parameters.
KeyManager keyManagerInstance = KeyManagerHolder.getKeyManagerInstance(tenantDomain, keyManagerName);
if (keyManagerInstance != null) {
authApplicationInfo = keyManagerInstance.buildFromJSON(authApplicationInfo, clientDetails);
}
if (log.isDebugEnabled()) {
log.debug("Additional json parameters when building OauthAppRequest = " + clientDetails);
}
} else {
if (log.isDebugEnabled()) {
log.debug("No additional json parameters when building OauthAppRequest");
}
}
// set applicationInfo object
appRequest.setOAuthApplicationInfo(authApplicationInfo);
return appRequest;
}
Aggregations