Page updated Mar 6, 2024

File access levels

When adding the Storage category, you configure the level of access users have to your S3 bucket. You can configure separate rules for authenticated vs. guest users. When using the Storage category to upload files, you can also specify an access level for each individual file: guest, protected, or private.

  • Guest Accessible by all users of your application
  • Protected Readable by all users (you need to specify the identityID of the user who uploaded the file). Writable only by the creating user
  • Private Readable and writable only by the creating user

Guest access does not mean that your files are totally public. A "guest" is a user of your application who has not yet signed in. To enable access at this level, you will still be required to configured Authentication in your app. The user must be able to assume an unauthenticated role from your Cognito Identity Pool.

For protected and private access, the [IDENTITY_ID] below corresponds to the unique ID of the user. Once the user has signed in, the [IDENTITY_ID] can be retrieved from the session by accessing the identity id. See Accessing credentials to retrieve the identity id, and use this as the unique ID of the authenticated user.

The default access level for the Storage category is guest. Unless you specify otherwise, all uploaded files will be available to all users of your application. This means that a user who is using your application but has not signed in will have access. Anyone else who is not using your application will not be able to access your files.

Protected access

After the user has signed in, create an options object specifying the protected access level to allow other users to read the object:

1import 'package:amplify_flutter/amplify_flutter.dart';
2
3Future<void> uploadProtectedFile({
4 required String filePath,
5 required String key,
6}) async {
7 final awsFile = AWSFile.fromPath(filePath);
8 const options = StorageUploadFileOptions(
9 accessLevel: StorageAccessLevel.protected,
10 );
11
12 try {
13 final uploadResult = await Amplify.Storage.uploadFile(
14 localFile: awsFile,
15 key: key,
16 options: options,
17 ).result;
18 safePrint('Uploaded file: ${uploadResult.uploadedItem.key}');
19 } on StorageException catch (e) {
20 safePrint('Something went wrong uploading file: ${e.message}');
21 rethrow;
22 }
23}

This will upload with the prefix /protected/[IDENTITY_ID]/ followed by the key.

For other users to read the file, you must specify the access level as protected and the identity ID of the user who uploaded it in the options.

1import 'package:amplify_flutter/amplify_flutter.dart';
2import 'package:amplify_storage_s3/amplify_storage_s3.dart';
3
4Future<void> downloadProtectedFile({
5 required String key,
6 required String targetIdentityId,
7 required String downloadPath,
8}) async {
9 final awsFile = AWSFile.fromPath(downloadPath);
10 final options = StorageDownloadFileOptions(
11 // specify that the file has a protected access level
12 accessLevel: StorageAccessLevel.protected,
13 // specify the identity ID of the user who uploaded this file
14 pluginOptions: S3DownloadFilePluginOptions.forIdentity(
15 targetIdentityId,
16 ),
17 );
18
19 try {
20 final result = await Amplify.Storage.downloadFile(
21 key: key,
22 localFile: awsFile,
23 options: options,
24 ).result;
25
26 safePrint('Downloaded file is located at: ${result.localFile.path}');
27 } on StorageException catch (e) {
28 safePrint('Something went wrong downloading the file: ${e.message}');
29 rethrow;
30 }
31}

Private Access

Create an options object specifying the private access level to only allow an object to be accessed by the uploading user

1import 'package:amplify_flutter/amplify_flutter.dart';
2
3Future<void> uploadPrivateFile({
4 required String filePath,
5 required String key,
6}) async {
7 final awsFile = AWSFile.fromPath(filePath);
8 const options = StorageUploadFileOptions(
9 accessLevel: StorageAccessLevel.private,
10 );
11
12 try {
13 final uploadResult = await Amplify.Storage.uploadFile(
14 localFile: awsFile,
15 key: key,
16 options: options,
17 ).result;
18
19 safePrint('Uploaded file: ${uploadResult.uploadedItem.key}');
20 } on StorageException catch (e) {
21 safePrint('Something went wrong uploading file: ${e.message}');
22 rethrow;
23 }
24}

This will upload with the prefix /private/[IDENTITY_ID]/, followed by the key.

For the uploading user to read the file, specify the same access level (private) and key you used to upload:

1import 'package:amplify_flutter/amplify_flutter.dart';
2
3Future<void> downloadPrivateFile({
4 required String key,
5 required String downloadPath,
6}) async {
7 final awsFile = AWSFile.fromPath(downloadPath);
8 const options = StorageDownloadFileOptions(
9 accessLevel: StorageAccessLevel.private,
10 );
11
12 try {
13 final result = await Amplify.Storage.downloadFile(
14 key: key,
15 localFile: awsFile,
16 options: options,
17 ).result;
18
19 safePrint('Downloaded file is located at: ${result.localFile.path}');
20 } on StorageException catch (e) {
21 safePrint('Something went wrong downloading the file: ${e.message}');
22 rethrow;
23 }
24}

Customization

Customize Object Key Path

You can customize your key path by defining a prefix resolver:

1import 'package:amplify_auth_cognito/amplify_auth_cognito.dart';
2import 'package:amplify_flutter/amplify_flutter.dart';
3import 'package:amplify_storage_s3/amplify_storage_s3.dart';
4
5// Define your own prefix resolver, which implements the `S3PrefixResolver`.
6class MyPrefixResolver implements S3PrefixResolver {
7 const MyPrefixResolver();
8
9
10 Future<String> resolvePrefix({
11 required StorageAccessLevel accessLevel,
12 String? identityId,
13 }) async {
14 if (accessLevel == StorageAccessLevel.guest) {
15 return 'myPublicPrefix/';
16 }
17
18 final String accessLevelPrefix;
19
20 if (accessLevel == StorageAccessLevel.protected) {
21 accessLevelPrefix = 'myProtectedPrefix/';
22 } else {
23 accessLevelPrefix = 'myPrivatePrefix/';
24 }
25
26 final targetIdentityId = identityId ?? await getCurrentUserIdentityId();
27
28 return '$accessLevelPrefix$targetIdentityId/';
29 }
30
31 Future<String> getCurrentUserIdentityId() async {
32 final authPlugin = Amplify.Auth.getPlugin(AmplifyAuthCognito.pluginKey);
33 final authSession = await authPlugin.fetchAuthSession();
34 return authSession.identityIdResult.value;
35 }
36}

Then configure the storage plugin with the resolver.

1final storagePlugin = AmplifyStorageS3(
2 prefixResolver: const MyPrefixResolver(),
3);
4...
5await Amplify.addPlugin(storagePlugin);

Add the IAM policy that corresponds with the prefixes defined above to enable read, write and delete operation for all the objects under path myPublicPrefix/:

1{
2 "Statement": [
3 {
4 "Effect": "Allow",
5 "Action": [
6 "s3:GetObject",
7 "s3:PutObject",
8 "s3:DeleteObject"
9 ],
10 "Resource": ["arn:aws:s3:::your-s3-bucket/myPublicPrefix/*"]
11 }
12 ]
13}

If you want to have custom private path prefix like myPrivatePrefix/, you need to add it into your IAM policy:

1{
2 "Statement": [
3 {
4 "Effect": "Allow",
5 "Action": [
6 "s3:GetObject",
7 "s3:PutObject",
8 "s3:DeleteObject"
9 ],
10 "Resource": [
11 "arn:aws:s3:::your-s3-bucket/myPrivatePrefix/${cognito-identity.amazonaws.com:sub}/*"
12 ]
13 }
14 ]
15}

Passthrough PrefixResolver

If you would like no prefix resolution logic, such as performing S3 requests at the root of the bucket, you can use the PassThroughPrefixResolver provided by the amplify_storage_s3 package.

1import 'package:amplify_storage_s3/amplify_storage_s3.dart';
2
3final storagePlugin = AmplifyStorageS3(
4 prefixResolver: const PassThroughPrefixResolver(),
5);
6
7await Amplify.addPlugin(storagePlugin);