Search in sources :

Example 26 with AccessTokenRequest

use of org.wso2.carbon.apimgt.api.model.AccessTokenRequest 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;
}
Also used : KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OAuthAppRequest(org.wso2.carbon.apimgt.api.model.OAuthAppRequest) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) JSONObject(org.json.simple.JSONObject) AccessTokenRequest(org.wso2.carbon.apimgt.api.model.AccessTokenRequest) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager)

Example 27 with AccessTokenRequest

use of org.wso2.carbon.apimgt.api.model.AccessTokenRequest 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;
    }
}
Also used : KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) JSONObject(org.json.simple.JSONObject) AccessTokenRequest(org.wso2.carbon.apimgt.api.model.AccessTokenRequest) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager)

Aggregations

AccessTokenRequest (org.wso2.carbon.apimgt.api.model.AccessTokenRequest)13 AccessTokenRequest (org.wso2.carbon.apimgt.core.models.AccessTokenRequest)11 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)9 KeyManagementException (org.wso2.carbon.apimgt.core.exception.KeyManagementException)9 AccessTokenInfo (org.wso2.carbon.apimgt.core.models.AccessTokenInfo)8 Response (feign.Response)7 Test (org.junit.Test)7 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)7 OAuth2IntrospectionResponse (org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse)7 OAuth2TokenInfo (org.wso2.carbon.apimgt.core.auth.dto.OAuth2TokenInfo)7 Test (org.testng.annotations.Test)6 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)6 DCRMServiceStub (org.wso2.carbon.apimgt.core.auth.DCRMServiceStub)6 OAuth2ServiceStubs (org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs)6 ScopeRegistration (org.wso2.carbon.apimgt.core.auth.ScopeRegistration)6 Gson (com.google.gson.Gson)5 KeyManagerConfigurationDTO (org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO)5 AccessTokenInfo (org.wso2.carbon.apimgt.api.model.AccessTokenInfo)4 KeyManager (org.wso2.carbon.apimgt.api.model.KeyManager)4 JSONObject (org.json.simple.JSONObject)3