use of com.amplifyframework.api.aws.sigv4.DefaultCognitoUserPoolsAuthProvider 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;
}
}
use of com.amplifyframework.api.aws.sigv4.DefaultCognitoUserPoolsAuthProvider in project amplify-android by aws-amplify.
the class MultiAuthSyncEngineInstrumentationTest method configure.
/**
* Method used to configure each scenario.
* @param modelType The model type.
* @param signInToCognito Does the test scenario require the user to be logged in with user pools.
* @param signInWithOidc Does the test scenario require the user to be logged in with an OIDC provider.
* @param expectedAuthType The auth type that should succeed for the test.
* @throws AmplifyException No expected.
* @throws IOException Not expected.
*/
private void configure(Class<? extends Model> modelType, boolean signInToCognito, boolean signInWithOidc, AuthorizationType expectedAuthType) throws AmplifyException, IOException {
Amplify.addPlugin(new AndroidLoggingPlugin(LogLevel.VERBOSE));
String tag = modelType.getSimpleName();
MultiAuthTestModelProvider modelProvider = MultiAuthTestModelProvider.getInstance(Collections.singletonList(modelType));
SchemaRegistry schemaRegistry = SchemaRegistry.instance();
ModelSchema modelSchema = ModelSchema.fromModelClass(modelType);
schemaRegistry.register(modelType.getSimpleName(), modelSchema);
StrictMode.enable();
Context context = getApplicationContext();
@RawRes int configResourceId = Resources.getRawResourceId(context, "amplifyconfiguration");
AmplifyConfiguration amplifyConfiguration = AmplifyConfiguration.fromConfigFile(context, configResourceId);
readCredsFromConfig(context);
// Setup an auth plugin
CategoryConfiguration authCategoryConfiguration = amplifyConfiguration.forCategoryType(CategoryType.AUTH);
// Turn off persistence so the mobile client's state for one test does not interfere with the others.
try {
authCategoryConfiguration.getPluginConfig("awsCognitoAuthPlugin").getJSONObject("Auth").getJSONObject("Default").put("Persistence", false);
} catch (JSONException exception) {
exception.printStackTrace();
fail();
return;
}
AuthCategory authCategory = new AuthCategory();
AWSCognitoAuthPlugin authPlugin = new AWSCognitoAuthPlugin();
authCategory.addPlugin(authPlugin);
authCategory.configure(authCategoryConfiguration, context);
auth = SynchronousAuth.delegatingTo(authCategory);
if (signInToCognito) {
Log.v(tag, "Test requires signIn.");
AuthSignInResult authSignInResult = auth.signIn(cognitoUser, cognitoPassword);
if (!authSignInResult.isSignInComplete()) {
fail("Unable to complete initial sign-in");
}
}
if (signInWithOidc) {
oidcLogin();
if (token.get() == null) {
fail("Unable to autenticate with OIDC provider");
}
}
// Setup an API
DefaultCognitoUserPoolsAuthProvider cognitoProvider = new DefaultCognitoUserPoolsAuthProvider(authPlugin.getEscapeHatch());
CategoryConfiguration apiCategoryConfiguration = amplifyConfiguration.forCategoryType(CategoryType.API);
ApiAuthProviders apiAuthProviders = ApiAuthProviders.builder().cognitoUserPoolsAuthProvider(cognitoProvider).awsCredentialsProvider(authPlugin.getEscapeHatch()).oidcAuthProvider(token::get).build();
ApiCategory apiCategory = new ApiCategory();
requestInterceptor = new HttpRequestInterceptor(expectedAuthType);
apiCategory.addPlugin(AWSApiPlugin.builder().configureClient("DataStoreIntegTestsApi", okHttpClientBuilder -> okHttpClientBuilder.addInterceptor(requestInterceptor)).apiAuthProviders(apiAuthProviders).build());
apiCategory.configure(apiCategoryConfiguration, context);
api = SynchronousApi.delegatingTo(apiCategory);
// Setup DataStore
DataStoreConfiguration dsConfig = DataStoreConfiguration.builder().errorHandler(exception -> Log.e(tag, "DataStore error handler received an error.", exception)).syncExpression(modelSchema.getName(), () -> Where.id("FAKE_ID").getQueryPredicate()).build();
CategoryConfiguration dataStoreCategoryConfiguration = AmplifyConfiguration.fromConfigFile(context, configResourceId).forCategoryType(CategoryType.DATASTORE);
String databaseName = "IntegTest" + modelType.getSimpleName() + ".db";
SQLiteStorageAdapter sqLiteStorageAdapter = TestStorageAdapter.create(schemaRegistry, modelProvider, databaseName);
AWSDataStorePlugin awsDataStorePlugin = AWSDataStorePlugin.builder().storageAdapter(sqLiteStorageAdapter).modelProvider(modelProvider).apiCategory(apiCategory).authModeStrategy(AuthModeStrategyType.MULTIAUTH).schemaRegistry(schemaRegistry).dataStoreConfiguration(dsConfig).build();
DataStoreCategory dataStoreCategory = new DataStoreCategory();
dataStoreCategory.addPlugin(awsDataStorePlugin);
dataStoreCategory.configure(dataStoreCategoryConfiguration, context);
dataStoreCategory.initialize(context);
dataStore = SynchronousDataStore.delegatingTo(dataStoreCategory);
}
use of com.amplifyframework.api.aws.sigv4.DefaultCognitoUserPoolsAuthProvider in project amplify-android by aws-amplify.
the class TestApiCategory method fromConfiguration.
/**
* Creates an instance of {@link ApiCategory}, using the provided configuration
* file, referred to by its android resource ID.
* @return A configured and initialized ApiCategory instance
*/
@NonNull
static ApiCategory fromConfiguration(@RawRes int resourceId) throws AmplifyException {
CognitoUserPoolsAuthProvider cognitoUserPoolsAuthProvider = new DefaultCognitoUserPoolsAuthProvider(AWSMobileClient.getInstance());
ApiAuthProviders providers = ApiAuthProviders.builder().awsCredentialsProvider(AWSMobileClient.getInstance()).cognitoUserPoolsAuthProvider(cognitoUserPoolsAuthProvider).build();
AWSApiPlugin plugin = AWSApiPlugin.builder().apiAuthProviders(providers).build();
ApiCategory apiCategory = new ApiCategory();
apiCategory.addPlugin(plugin);
CategoryConfiguration apiConfiguration = AmplifyConfiguration.fromConfigFile(getApplicationContext(), resourceId).forCategoryType(CategoryType.API);
apiCategory.configure(apiConfiguration, getApplicationContext());
// apiCategory.initialize(...); Doesn't currently contain any logic, so, skip it.
return apiCategory;
}
Aggregations