Search in sources :

Example 11 with OAuthApplicationInfo

use of org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo in project carbon-apimgt by wso2.

the class AuthenticatorService method getConsumerKeySecret.

/**
 * This method returns the consumer key & secret of a DCR application.
 *
 * @param appName Name of the DCR application
 * @return Map with consumer key & secret
 * @throws APIManagementException When creating DCR application fails
 */
private Map<String, String> getConsumerKeySecret(String appName) throws APIManagementException {
    HashMap<String, String> consumerKeySecretMap;
    if (!AuthUtil.getConsumerKeySecretMap().containsKey(appName)) {
        consumerKeySecretMap = new HashMap<>();
        List<String> grantTypes = new ArrayList<>();
        grantTypes.add(KeyManagerConstants.PASSWORD_GRANT_TYPE);
        grantTypes.add(KeyManagerConstants.REFRESH_GRANT_TYPE);
        OAuthApplicationInfo oAuthApplicationInfo;
        oAuthApplicationInfo = createDCRApplication(appName, "http://temporary.callback/url", grantTypes);
        consumerKeySecretMap.put(AuthenticatorConstants.CONSUMER_KEY, oAuthApplicationInfo.getClientId());
        consumerKeySecretMap.put(AuthenticatorConstants.CONSUMER_SECRET, oAuthApplicationInfo.getClientSecret());
        AuthUtil.getConsumerKeySecretMap().put(appName, consumerKeySecretMap);
        return consumerKeySecretMap;
    } else {
        return AuthUtil.getConsumerKeySecretMap().get(appName);
    }
}
Also used : OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) ArrayList(java.util.ArrayList)

Example 12 with OAuthApplicationInfo

use of org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo in project carbon-apimgt by wso2.

the class AuthenticatorService method createDCRApplication.

/**
 * This method creates a DCR application.
 *
 * @param clientName  Name of the application to be created
 * @param callBackURL Call back URL of the application
 * @param grantTypes  List of grant types of the application
 * @return OAUthApplicationInfo - An object with DCR Application information
 * @throws APIManagementException When creating DCR application fails
 */
private OAuthApplicationInfo createDCRApplication(String clientName, String callBackURL, List<String> grantTypes) throws APIManagementException {
    OAuthApplicationInfo oAuthApplicationInfo;
    try {
        // Here the keyType:"Application" will be passed as a default value
        // for the oAuthAppRequest constructor argument.
        // This value is not related to DCR application creation.
        OAuthAppRequest oAuthAppRequest = new OAuthAppRequest(clientName, callBackURL, AuthenticatorConstants.APPLICATION_KEY_TYPE, grantTypes);
        if (systemApplicationDao.isConsumerKeyExistForApplication(clientName)) {
            String consumerKey = systemApplicationDao.getConsumerKeyForApplication(clientName);
            oAuthApplicationInfo = getKeyManager().retrieveApplication(consumerKey);
        } else {
            oAuthApplicationInfo = getKeyManager().createApplication(oAuthAppRequest);
            if (oAuthApplicationInfo != null) {
                systemApplicationDao.addApplicationKey(clientName, oAuthApplicationInfo.getClientId());
            }
        }
    } catch (KeyManagementException | APIMgtDAOException e) {
        String errorMsg = "Error while creating the keys for OAuth application : " + clientName;
        log.error(errorMsg, e, ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
    }
    return oAuthApplicationInfo;
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) OAuthAppRequest(org.wso2.carbon.apimgt.core.models.OAuthAppRequest) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException)

Example 13 with OAuthApplicationInfo

use of org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo in project carbon-apimgt by wso2.

the class AuthenticatorServiceTestCase method testGetAuthenticationConfigurations.

@Test
public void testGetAuthenticationConfigurations() throws Exception {
    // Happy Path - 200
    // // Mocked response object from DCR api
    SystemApplicationDao systemApplicationDao = Mockito.mock(SystemApplicationDao.class);
    Mockito.when(systemApplicationDao.isConsumerKeyExistForApplication("store")).thenReturn(false);
    APIMConfigurationService apimConfigurationService = Mockito.mock(APIMConfigurationService.class);
    EnvironmentConfigurations environmentConfigurations = new EnvironmentConfigurations();
    Mockito.when(apimConfigurationService.getEnvironmentConfigurations()).thenReturn(environmentConfigurations);
    APIMAppConfigurationService apimAppConfigurationService = Mockito.mock(APIMAppConfigurationService.class);
    APIMAppConfigurations apimAppConfigurations = new APIMAppConfigurations();
    Mockito.when(apimAppConfigurationService.getApimAppConfigurations()).thenReturn(apimAppConfigurations);
    OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
    oAuthApplicationInfo.setClientId("xxx-client-id-xxx");
    oAuthApplicationInfo.setCallBackURL("https://localhost/9292/login/callback/store");
    // // Expected data object to be passed to the front-end
    JsonObject oAuthData = new JsonObject();
    String scopes = "apim:self-signup apim:dedicated_gateway apim:subscribe openid";
    oAuthData.addProperty(KeyManagerConstants.OAUTH_CLIENT_ID, oAuthApplicationInfo.getClientId());
    oAuthData.addProperty(KeyManagerConstants.OAUTH_CALLBACK_URIS, oAuthApplicationInfo.getCallBackURL());
    oAuthData.addProperty(KeyManagerConstants.TOKEN_SCOPES, scopes);
    oAuthData.addProperty(KeyManagerConstants.AUTHORIZATION_ENDPOINT, "https://localhost:9080/oauth2/authorize");
    oAuthData.addProperty(AuthenticatorConstants.SSO_ENABLED, ServiceReferenceHolder.getInstance().getAPIMAppConfiguration().isSsoEnabled());
    oAuthData.addProperty(AuthenticatorConstants.MULTI_ENVIRONMENT_OVERVIEW_ENABLED, APIMConfigurationService.getInstance().getEnvironmentConfigurations().getMultiEnvironmentOverview().isEnabled());
    MultiEnvironmentOverview multiEnvironmentOverview = new MultiEnvironmentOverview();
    environmentConfigurations.setMultiEnvironmentOverview(multiEnvironmentOverview);
    KeyManager keyManager = Mockito.mock(KeyManager.class);
    AuthenticatorService authenticatorService = new AuthenticatorService(keyManager, systemApplicationDao, apimConfigurationService, apimAppConfigurationService);
    // // Get data object to be passed to the front-end
    Mockito.when(keyManager.createApplication(Mockito.any())).thenReturn(oAuthApplicationInfo);
    JsonObject responseOAuthDataObj = authenticatorService.getAuthenticationConfigurations("store");
    Assert.assertEquals(responseOAuthDataObj, oAuthData);
    // Error Path - 500 - When OAuthApplicationInfo is null
    JsonObject emptyOAuthDataObj = new JsonObject();
    Mockito.when(keyManager.createApplication(Mockito.any())).thenReturn(null);
    JsonObject responseEmptyOAuthDataObj = authenticatorService.getAuthenticationConfigurations("store");
    Assert.assertEquals(responseEmptyOAuthDataObj, emptyOAuthDataObj);
    // Error Path - When DCR application creation fails and throws an APIManagementException
    Mockito.when(keyManager.createApplication(Mockito.any())).thenThrow(KeyManagementException.class);
    try {
        authenticatorService.getAuthenticationConfigurations("store");
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "Error while creating the keys for OAuth application : store");
    }
}
Also used : EnvironmentConfigurations(org.wso2.carbon.apimgt.core.configuration.models.EnvironmentConfigurations) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) APIMAppConfigurations(org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMAppConfigurations) SystemApplicationDao(org.wso2.carbon.apimgt.core.dao.SystemApplicationDao) JsonObject(com.google.gson.JsonObject) APIMAppConfigurationService(org.wso2.carbon.apimgt.rest.api.authenticator.configuration.APIMAppConfigurationService) MultiEnvironmentOverview(org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview) KeyManager(org.wso2.carbon.apimgt.core.api.KeyManager) APIMConfigurationService(org.wso2.carbon.apimgt.core.configuration.APIMConfigurationService) Test(org.junit.Test)

Example 14 with OAuthApplicationInfo

use of org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo in project carbon-apimgt by wso2.

the class APIStoreImpl method mapApplicationKeys.

@Override
public OAuthApplicationInfo mapApplicationKeys(String applicationId, String keyType, String clientId, String clientSecret) throws APIManagementException {
    if (log.isDebugEnabled()) {
        log.debug("Semi-manual client registering for App: " + applicationId + " and Client ID: " + clientId);
    }
    if (StringUtils.isEmpty(applicationId) || StringUtils.isEmpty(clientId) || StringUtils.isEmpty(clientSecret)) {
        String msg = "One of input values is null or empty. Application Id: " + applicationId + " Client Id: " + clientId + (StringUtils.isEmpty(clientSecret) ? " Client Secret: " + clientSecret : "");
        log.error(msg);
        throw new APIManagementException(msg, ExceptionCodes.OAUTH2_APP_MAP_FAILED);
    }
    // Checking whether given consumer key and secret match with an existing OAuth app.
    // If they does not match, throw an exception.
    OAuthApplicationInfo oAuthApp = getKeyManager().retrieveApplication(clientId);
    if (oAuthApp == null || !clientSecret.equals(oAuthApp.getClientSecret())) {
        String msg = "Unable to find OAuth app. The provided Client Id is invalid. Client Id: " + clientId;
        throw new APIManagementException(msg, ExceptionCodes.OAUTH2_APP_MAP_FAILED);
    }
    try {
        getApplicationDAO().addApplicationKeys(applicationId, keyType, clientId);
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while saving key data.";
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    }
    log.debug("Application keys are successfully saved in the database");
    List<SubscriptionValidationData> subscriptionValidationData = getApiSubscriptionDAO().getAPISubscriptionsOfAppForValidation(applicationId, keyType);
    if (subscriptionValidationData != null && !subscriptionValidationData.isEmpty()) {
        getApiGateway().addAPISubscription(subscriptionValidationData);
    }
    if (log.isDebugEnabled()) {
        log.debug("Semi-manual client registration was successful for application: " + applicationId + " and Client ID: " + clientId);
    }
    return oAuthApp;
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) SubscriptionValidationData(org.wso2.carbon.apimgt.core.models.SubscriptionValidationData)

Example 15 with OAuthApplicationInfo

use of org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo in project carbon-apimgt by wso2.

the class DefaultKeyManagerImpl method createApplication.

@Override
public OAuthApplicationInfo createApplication(OAuthAppRequest oauthAppRequest) throws KeyManagementException {
    log.debug("Creating OAuth2 application:{}", oauthAppRequest.toString());
    String applicationName = oauthAppRequest.getClientName();
    String keyType = oauthAppRequest.getKeyType();
    if (keyType != null) {
        // Derive oauth2 app name based on key type and user input for app name
        applicationName = applicationName + '_' + keyType;
    }
    DCRClientInfo dcrClientInfo = new DCRClientInfo();
    dcrClientInfo.setClientName(applicationName);
    dcrClientInfo.setGrantTypes(oauthAppRequest.getGrantTypes());
    if (StringUtils.isNotEmpty(oauthAppRequest.getCallBackURL())) {
        dcrClientInfo.addCallbackUrl(oauthAppRequest.getCallBackURL());
    }
    Response response = dcrmServiceStub.registerApplication(dcrClientInfo);
    if (response == null) {
        throw new KeyManagementException("Error occurred while DCR application creation. Response is null", ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
    }
    if (response.status() == APIMgtConstants.HTTPStatusCodes.SC_201_CREATED) {
        // 201 - Success
        try {
            OAuthApplicationInfo oAuthApplicationInfoResponse = getOAuthApplicationInfo(response);
            // setting original parameter list
            oAuthApplicationInfoResponse.setParameters(oauthAppRequest.getParameters());
            log.debug("OAuth2 application created: {}", oAuthApplicationInfoResponse.toString());
            return oAuthApplicationInfoResponse;
        } catch (IOException e) {
            throw new KeyManagementException("Error occurred while parsing the DCR application creation response " + "message.", e, ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
        }
    } else if (response.status() == APIMgtConstants.HTTPStatusCodes.SC_400_BAD_REQUEST) {
        // 400 - Known Error
        try {
            DCRError error = (DCRError) new GsonDecoder().decode(response, DCRError.class);
            throw new KeyManagementException("Error occurred while DCR application creation. Error: " + error.getError() + ". Error Description: " + error.getErrorDescription() + ". Status Code: " + response.status(), ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
        } catch (IOException e) {
            throw new KeyManagementException("Error occurred while parsing the DCR error message.", e, ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
        }
    } else {
        // Unknown Error
        throw new KeyManagementException("Error occurred while DCR application creation. Error: " + response.body().toString() + " Status Code: " + response.status(), ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
    }
}
Also used : OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) Response(feign.Response) DCRError(org.wso2.carbon.apimgt.core.auth.dto.DCRError) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) GsonDecoder(feign.gson.GsonDecoder) IOException(java.io.IOException) DCRClientInfo(org.wso2.carbon.apimgt.core.auth.dto.DCRClientInfo) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException)

Aggregations

OAuthApplicationInfo (org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo)30 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)15 ArrayList (java.util.ArrayList)12 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)10 Test (org.junit.Test)9 ApplicationKeysDTO (org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationKeysDTO)9 KeyManagementException (org.wso2.carbon.apimgt.core.exception.KeyManagementException)8 HashMap (java.util.HashMap)7 DCRClientInfo (org.wso2.carbon.apimgt.core.auth.dto.DCRClientInfo)6 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)6 Response (feign.Response)5 Map (java.util.Map)5 Response (javax.ws.rs.core.Response)5 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)5 WorkflowResponse (org.wso2.carbon.apimgt.core.api.WorkflowResponse)5 OAuth2IntrospectionResponse (org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse)5 ApplicationCreationResponse (org.wso2.carbon.apimgt.core.workflow.ApplicationCreationResponse)5 GeneralWorkflowResponse (org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse)5 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)5 Request (org.wso2.msf4j.Request)5