Search in sources :

Example 31 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.

the class AMDefaultKeyManagerImpl method updateApplicationOwner.

@Override
public OAuthApplicationInfo updateApplicationOwner(OAuthAppRequest appInfoDTO, String owner) throws APIManagementException {
    OAuthApplicationInfo oAuthApplicationInfo = appInfoDTO.getOAuthApplicationInfo();
    log.debug("Updating Application Owner : " + oAuthApplicationInfo.getClientId());
    ClientInfo updatedClient;
    try {
        updatedClient = dcrClient.updateApplicationOwner(owner, Base64.getUrlEncoder().encodeToString(oAuthApplicationInfo.getClientId().getBytes(StandardCharsets.UTF_8)));
        return buildDTOFromClientInfo(updatedClient, new OAuthApplicationInfo());
    } catch (KeyManagerClientException e) {
        handleException("Error occurred while updating OAuth Client : ", e);
        return null;
    }
}
Also used : KeyManagerClientException(org.wso2.carbon.apimgt.impl.kmclient.KeyManagerClientException) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) ClientInfo(org.wso2.carbon.apimgt.impl.kmclient.model.ClientInfo)

Example 32 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.

the class AMDefaultKeyManagerImpl method createApplication.

@Override
public OAuthApplicationInfo createApplication(OAuthAppRequest oauthAppRequest) throws APIManagementException {
    // OAuthApplications are created by calling to APIKeyMgtSubscriber Service
    OAuthApplicationInfo oAuthApplicationInfo = oauthAppRequest.getOAuthApplicationInfo();
    // Subscriber's name should be passed as a parameter, since it's under the subscriber the OAuth App is created.
    String userId = (String) oAuthApplicationInfo.getParameter(ApplicationConstants.OAUTH_CLIENT_USERNAME);
    if (StringUtils.isEmpty(userId)) {
        throw new APIManagementException("Missing user ID for OAuth application creation.");
    }
    String applicationName = oAuthApplicationInfo.getClientName();
    String oauthClientName = oauthAppRequest.getOAuthApplicationInfo().getApplicationUUID();
    String keyType = (String) oAuthApplicationInfo.getParameter(ApplicationConstants.APP_KEY_TYPE);
    if (StringUtils.isNotEmpty(applicationName) && StringUtils.isNotEmpty(keyType)) {
        String domain = UserCoreUtil.extractDomainFromName(userId);
        if (domain != null && !domain.isEmpty() && !UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equals(domain)) {
            userId = userId.replace(UserCoreConstants.DOMAIN_SEPARATOR, "_");
        }
        oauthClientName = String.format("%s_%s_%s", APIUtil.replaceEmailDomain(MultitenantUtils.getTenantAwareUsername(userId)), oauthClientName, keyType);
    } else {
        throw new APIManagementException("Missing required information for OAuth application creation.");
    }
    if (log.isDebugEnabled()) {
        log.debug("Trying to create OAuth application : " + oauthClientName + " for application: " + applicationName + " and key type: " + keyType);
    }
    String tokenScope = (String) oAuthApplicationInfo.getParameter("tokenScope");
    String[] tokenScopes = new String[1];
    tokenScopes[0] = tokenScope;
    ClientInfo request = createClientInfo(oAuthApplicationInfo, oauthClientName, false);
    ClientInfo createdClient;
    try {
        createdClient = dcrClient.createApplication(request);
        buildDTOFromClientInfo(createdClient, oAuthApplicationInfo);
        oAuthApplicationInfo.addParameter("tokenScope", tokenScopes);
        oAuthApplicationInfo.setIsSaasApplication(false);
        return oAuthApplicationInfo;
    } catch (KeyManagerClientException e) {
        handleException("Can not create OAuth application  : " + oauthClientName + " for application: " + applicationName + " and key type: " + keyType, e);
        return null;
    }
}
Also used : KeyManagerClientException(org.wso2.carbon.apimgt.impl.kmclient.KeyManagerClientException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) ClientInfo(org.wso2.carbon.apimgt.impl.kmclient.model.ClientInfo)

Example 33 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.

the class AMDefaultKeyManagerImpl method mapOAuthApplication.

/**
 * This method will create a new record at CLIENT_INFO table by given OauthAppRequest.
 *
 * @param appInfoRequest oAuth application properties will contain in this object
 * @return OAuthApplicationInfo with created oAuth application details.
 * @throws org.wso2.carbon.apimgt.api.APIManagementException
 */
@Override
public OAuthApplicationInfo mapOAuthApplication(OAuthAppRequest appInfoRequest) throws APIManagementException {
    // initiate OAuthApplicationInfo
    OAuthApplicationInfo oAuthApplicationInfo = appInfoRequest.getOAuthApplicationInfo();
    String consumerKey = oAuthApplicationInfo.getClientId();
    String tokenScope = (String) oAuthApplicationInfo.getParameter("tokenScope");
    String[] tokenScopes = new String[1];
    tokenScopes[0] = tokenScope;
    String clientSecret = (String) oAuthApplicationInfo.getParameter("client_secret");
    // for the first time we set default time period.
    oAuthApplicationInfo.addParameter(ApplicationConstants.VALIDITY_PERIOD, getConfigurationParamValue(APIConstants.IDENTITY_OAUTH2_FIELD_VALIDITY_PERIOD));
    String userId = (String) oAuthApplicationInfo.getParameter(ApplicationConstants.OAUTH_CLIENT_USERNAME);
    // check whether given consumer key and secret match or not. If it does not match throw an exception.
    ClientInfo clientInfo;
    try {
        clientInfo = dcrClient.getApplication(Base64.getUrlEncoder().encodeToString(consumerKey.getBytes(StandardCharsets.UTF_8)));
        buildDTOFromClientInfo(clientInfo, oAuthApplicationInfo);
    } catch (KeyManagerClientException e) {
        handleException("Some thing went wrong while getting OAuth application for given consumer key " + oAuthApplicationInfo.getClientId(), e);
    }
    if (!clientSecret.equals(oAuthApplicationInfo.getClientSecret())) {
        throw new APIManagementException("The secret key is wrong for the given consumer key " + consumerKey);
    }
    oAuthApplicationInfo.addParameter("tokenScope", tokenScopes);
    oAuthApplicationInfo.setIsSaasApplication(false);
    if (log.isDebugEnabled()) {
        log.debug("Creating semi-manual application for consumer id  :  " + oAuthApplicationInfo.getClientId());
    }
    return oAuthApplicationInfo;
}
Also used : KeyManagerClientException(org.wso2.carbon.apimgt.impl.kmclient.KeyManagerClientException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) ClientInfo(org.wso2.carbon.apimgt.impl.kmclient.model.ClientInfo)

Example 34 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.

the class OAuthResponseMediator method mediate.

@Override
public boolean mediate(MessageContext messageContext) {
    if (messageContext != null) {
        TargetResponse targetResponse = (TargetResponse) ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty("pass-through.Target-Response");
        int statusCode = targetResponse.getStatus();
        if (statusCode == 401) {
            Object oauthEndpointObject = messageContext.getProperty(APIMgtGatewayConstants.OAUTH_ENDPOINT_INSTANCE);
            if (oauthEndpointObject instanceof OAuthEndpoint) {
                try {
                    OAuthTokenGenerator.generateToken((OAuthEndpoint) oauthEndpointObject, null);
                    log.error("OAuth 2.0 access token has been rejected by the backend...");
                    handleFailure(APISecurityConstants.OAUTH_TEMPORARY_SERVER_ERROR, messageContext, APISecurityConstants.OAUTH_TEMPORARY_SERVER_ERROR_MESSAGE, "Please try again");
                } catch (APISecurityException e) {
                    log.error("Error when generating oauth 2.0 access token...", e);
                }
            }
        }
    }
    return true;
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) OAuthEndpoint(org.wso2.carbon.apimgt.gateway.mediators.oauth.conf.OAuthEndpoint) TargetResponse(org.apache.synapse.transport.passthru.TargetResponse) OAuthEndpoint(org.wso2.carbon.apimgt.gateway.mediators.oauth.conf.OAuthEndpoint) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 35 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.

the class OAuthMediator method mediate.

@Override
public boolean mediate(MessageContext messageContext) {
    if (log.isDebugEnabled()) {
        log.debug("OAuth Mediator is invoked...");
    }
    CountDownLatch latch = new CountDownLatch(1);
    TokenResponse tokenResponse = null;
    if (oAuthEndpoint != null) {
        try {
            tokenResponse = OAuthTokenGenerator.generateToken(oAuthEndpoint, latch);
            latch.await();
        } catch (InterruptedException | APISecurityException e) {
            log.error("Could not generate access token...", e);
        }
    }
    if (tokenResponse != null) {
        String accessToken = tokenResponse.getAccessToken();
        Map<String, Object> transportHeaders = (Map<String, Object>) ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty("TRANSPORT_HEADERS");
        transportHeaders.put("Authorization", "Bearer " + accessToken);
        if (log.isDebugEnabled()) {
            log.debug("Access token set: " + GatewayUtils.getMaskedToken(accessToken));
        }
    } else {
        log.debug("Token Response is empty...");
    }
    messageContext.setProperty(APIMgtGatewayConstants.OAUTH_ENDPOINT_INSTANCE, oAuthEndpoint);
    return true;
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) TokenResponse(org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse) JSONObject(org.json.simple.JSONObject) CountDownLatch(java.util.concurrent.CountDownLatch) Map(java.util.Map) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)26 HashMap (java.util.HashMap)18 ArrayList (java.util.ArrayList)14 Test (org.junit.Test)14 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)13 Map (java.util.Map)11 JSONObject (org.json.simple.JSONObject)9 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)9 OAuthApplicationInfo (org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo)9 JsonObject (com.google.gson.JsonObject)8 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)8 KeyManagementException (org.wso2.carbon.apimgt.core.exception.KeyManagementException)8 TokenResponse (org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse)8 LinkedHashMap (java.util.LinkedHashMap)6 Test (org.testng.annotations.Test)6 IOException (java.io.IOException)5 ParseException (org.json.simple.parser.ParseException)5 OAuthAppRequest (org.wso2.carbon.apimgt.api.model.OAuthAppRequest)5 MultiEnvironmentOverview (org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview)5 APIMAppConfigurations (org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMAppConfigurations)5