Search in sources :

Example 1 with AppSyncV4Signer

use of com.amplifyframework.api.aws.sigv4.AppSyncV4Signer in project aws-mobile-appsync-sdk-android by awslabs.

the class SubscriptionAuthorizer method getAuthorizationDetailsForIAM.

private JSONObject getAuthorizationDetailsForIAM(boolean connectionFlag, Subscription subscription) throws JSONException {
    DefaultRequest canonicalRequest = new DefaultRequest("appsync");
    URI apiUrl;
    try {
        final String baseUrl = mServerUrl;
        final String connectionUrl = connectionFlag ? baseUrl + "/connect" : baseUrl;
        apiUrl = new URI(connectionUrl);
    } catch (URISyntaxException e) {
        throw new RuntimeException("Error constructing canonical URI for IAM request signature", e);
    }
    canonicalRequest.setEndpoint(apiUrl);
    canonicalRequest.addHeader("accept", "application/json, text/javascript");
    canonicalRequest.addHeader("content-encoding", "amz-1.0");
    canonicalRequest.addHeader("content-type", "application/json; charset=UTF-8");
    canonicalRequest.setHttpMethod(HttpMethodName.valueOf("POST"));
    if (connectionFlag) {
        canonicalRequest.setContent(new ByteArrayInputStream("{}".getBytes()));
    } else {
        canonicalRequest.setContent(new ByteArrayInputStream(getDataJson(subscription).getBytes()));
    }
    String apiRegion = apiUrl.getAuthority().split("\\.")[2];
    DomainType domainType = DomainType.from(mServerUrl);
    if (DomainType.CUSTOM == domainType) {
        apiRegion = getApiRegion();
    }
    if (connectionFlag) {
        new AppSyncV4Signer(apiRegion, AppSyncV4Signer.ResourcePath.IAM_CONNECTION_RESOURCE_PATH).sign(canonicalRequest, getCredentialsProvider().getCredentials());
    } else {
        new AppSyncV4Signer(apiRegion).sign(canonicalRequest, getCredentialsProvider().getCredentials());
    }
    JSONObject authorizationMessage = new JSONObject();
    Map<String, String> signedHeaders = canonicalRequest.getHeaders();
    try {
        for (Map.Entry headerEntry : signedHeaders.entrySet()) {
            if (!headerEntry.getKey().equals("host")) {
                authorizationMessage.put((String) headerEntry.getKey(), headerEntry.getValue());
            } else {
                authorizationMessage.put("host", getHost(mServerUrl));
            }
        }
    } catch (JSONException | MalformedURLException e) {
        throw new RuntimeException("Error constructing authorization message json", e);
    }
    return authorizationMessage;
}
Also used : MalformedURLException(java.net.MalformedURLException) DefaultRequest(com.amazonaws.DefaultRequest) JSONException(org.json.JSONException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) AppSyncV4Signer(com.amazonaws.mobileconnectors.appsync.sigv4.AppSyncV4Signer) JSONObject(org.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) Map(java.util.Map)

Example 2 with AppSyncV4Signer

use of com.amplifyframework.api.aws.sigv4.AppSyncV4Signer in project amplify-android by aws-amplify.

the class ApiRequestDecoratorFactory method forAuthType.

/**
 * Given a authorization type, it returns the appropriate request decorator.
 * @param authorizationType the authorization type to be used for the request.
 * @return the appropriate request decorator for the given authorization type.
 * @throws ApiAuthException if unable to get a request decorator.
 */
public RequestDecorator forAuthType(@NonNull AuthorizationType authorizationType) throws ApiAuthException {
    switch(authorizationType) {
        case AMAZON_COGNITO_USER_POOLS:
            // Note that if there was no user-provided cognito provider passed in to initialize
            // the API plugin, we will try to default to using the DefaultCognitoUserPoolsAuthProvider.
            // If that fails, we then have no choice but to bubble up the error.
            CognitoUserPoolsAuthProvider cognitoUserPoolsAuthProvider = apiAuthProviders.getCognitoUserPoolsAuthProvider() != null ? apiAuthProviders.getCognitoUserPoolsAuthProvider() : new DefaultCognitoUserPoolsAuthProvider();
            // By calling getLatestAuthToken() here instead of inside the lambda block, makes the exception
            // handling a little bit cleaner. If getLatestAuthToken() is called from inside the lambda expression
            // below, we'd have to surround it with a try catch. By doing it this way, if there's a problem,
            // the ApiException will just be bubbled up. Same for OPENID_CONNECT.
            final String token;
            try {
                token = cognitoUserPoolsAuthProvider.getLatestAuthToken();
            } catch (ApiException exception) {
                throw new ApiAuthException("Failed to retrieve auth token from Cognito provider.", exception, "Check the application logs for details.");
            }
            return new TokenRequestDecorator(() -> token);
        case OPENID_CONNECT:
            if (apiAuthProviders.getOidcAuthProvider() == null) {
                throw new ApiAuthException("Attempting to use OPENID_CONNECT authorization " + "without an OIDC provider.", "Configure an OidcAuthProvider when initializing " + "the API plugin.");
            }
            final String oidcToken;
            try {
                oidcToken = apiAuthProviders.getOidcAuthProvider().getLatestAuthToken();
            } catch (ApiException exception) {
                throw new ApiAuthException("Failed to retrieve auth token from OIDC provider.", exception, "Check the application logs for details.");
            }
            return new TokenRequestDecorator(() -> oidcToken);
        case AWS_LAMBDA:
            if (apiAuthProviders.getFunctionAuthProvider() == null) {
                throw new ApiAuthException("Attempting to use AWS_LAMBDA authorization " + "without a provider implemented.", "Configure a FunctionAuthProvider when initializing the API plugin.");
            }
            final String functionToken;
            try {
                functionToken = apiAuthProviders.getFunctionAuthProvider().getLatestAuthToken();
            } catch (ApiException exception) {
                throw new ApiAuthException("Failed to retrieve auth token from function auth provider.", exception, "Check the application logs for details.");
            }
            return new TokenRequestDecorator(() -> functionToken);
        case API_KEY:
            if (apiAuthProviders.getApiKeyAuthProvider() != null) {
                return new ApiKeyRequestDecorator(apiAuthProviders.getApiKeyAuthProvider());
            } else if (apiKey != null) {
                return new ApiKeyRequestDecorator(() -> apiKey);
            } else {
                throw new ApiAuthException("Attempting to use API_KEY authorization without " + "an API key provider or an API key in the config file", "Verify that an API key is in the config file or an " + "ApiKeyAuthProvider is setup during the API " + "plugin initialization.");
            }
        case AWS_IAM:
            AWSCredentialsProvider credentialsProvider = apiAuthProviders.getAWSCredentialsProvider() != null ? apiAuthProviders.getAWSCredentialsProvider() : getDefaultCredentialsProvider();
            final AWS4Signer signer;
            final String serviceName;
            if (endpointType == EndpointType.GRAPHQL) {
                signer = new AppSyncV4Signer(region);
                serviceName = APP_SYNC_SERVICE_NAME;
            } else {
                signer = new ApiGatewayIamSigner(region);
                serviceName = API_GATEWAY_SERVICE_NAME;
            }
            return new IamRequestDecorator(signer, credentialsProvider, serviceName);
        case NONE:
        default:
            return NO_OP_REQUEST_DECORATOR;
    }
}
Also used : ApiAuthException(com.amplifyframework.api.ApiException.ApiAuthException) DefaultCognitoUserPoolsAuthProvider(com.amplifyframework.api.aws.sigv4.DefaultCognitoUserPoolsAuthProvider) AWS4Signer(com.amazonaws.auth.AWS4Signer) ApiGatewayIamSigner(com.amplifyframework.api.aws.sigv4.ApiGatewayIamSigner) DefaultCognitoUserPoolsAuthProvider(com.amplifyframework.api.aws.sigv4.DefaultCognitoUserPoolsAuthProvider) CognitoUserPoolsAuthProvider(com.amplifyframework.api.aws.sigv4.CognitoUserPoolsAuthProvider) AWSCredentialsProvider(com.amazonaws.auth.AWSCredentialsProvider) ApiException(com.amplifyframework.api.ApiException) AppSyncV4Signer(com.amplifyframework.api.aws.sigv4.AppSyncV4Signer)

Example 3 with AppSyncV4Signer

use of com.amplifyframework.api.aws.sigv4.AppSyncV4Signer in project amplify-android by aws-amplify.

the class SubscriptionAuthorizer method forIam.

private JSONObject forIam(AWSCredentialsProvider credentialsProvider, GraphQLRequest<?> request, boolean connectionFlag) throws ApiException {
    final URI apiUrl = getRequestEndpoint(connectionFlag);
    final String apiRegion = configuration.getRegion();
    final String requestContent = request != null ? request.getContent() : "{}";
    // Construct a request to be signed
    DefaultRequest<?> canonicalRequest = new DefaultRequest<>("appsync");
    canonicalRequest.setEndpoint(apiUrl);
    canonicalRequest.addHeader("accept", "application/json, text/javascript");
    canonicalRequest.addHeader("content-encoding", "amz-1.0");
    canonicalRequest.addHeader("content-type", "application/json; charset=UTF-8");
    canonicalRequest.setHttpMethod(HttpMethodName.valueOf("POST"));
    canonicalRequest.setContent(new ByteArrayInputStream(requestContent.getBytes()));
    // Sign with AppSync's SigV4 signer that also considers connection resource path
    new AppSyncV4Signer(apiRegion, connectionFlag).sign(canonicalRequest, credentialsProvider.getCredentials());
    // Extract header from signed request and return
    Map<String, String> signedHeaders = canonicalRequest.getHeaders();
    return new JSONObject(signedHeaders);
}
Also used : DefaultRequest(com.amazonaws.DefaultRequest) JSONObject(org.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) URI(java.net.URI) AppSyncV4Signer(com.amplifyframework.api.aws.sigv4.AppSyncV4Signer)

Aggregations

DefaultRequest (com.amazonaws.DefaultRequest)2 AppSyncV4Signer (com.amplifyframework.api.aws.sigv4.AppSyncV4Signer)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 URI (java.net.URI)2 JSONObject (org.json.JSONObject)2 AWS4Signer (com.amazonaws.auth.AWS4Signer)1 AWSCredentialsProvider (com.amazonaws.auth.AWSCredentialsProvider)1 AppSyncV4Signer (com.amazonaws.mobileconnectors.appsync.sigv4.AppSyncV4Signer)1 ApiException (com.amplifyframework.api.ApiException)1 ApiAuthException (com.amplifyframework.api.ApiException.ApiAuthException)1 ApiGatewayIamSigner (com.amplifyframework.api.aws.sigv4.ApiGatewayIamSigner)1 CognitoUserPoolsAuthProvider (com.amplifyframework.api.aws.sigv4.CognitoUserPoolsAuthProvider)1 DefaultCognitoUserPoolsAuthProvider (com.amplifyframework.api.aws.sigv4.DefaultCognitoUserPoolsAuthProvider)1 MalformedURLException (java.net.MalformedURLException)1 URISyntaxException (java.net.URISyntaxException)1 Map (java.util.Map)1 JSONException (org.json.JSONException)1