Page updated Nov 14, 2023

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:

func uploadData(key: String, data: Data) async throws { let options = StorageUploadDataRequest.Options(accessLevel: .protected) let uploadTask = Amplify.Storage.uploadData( key: key, data: data, options: options ) Task { for await progress in await uploadTask.progress { print("Progress: \(progress)") } } let data = try await uploadTask.value print("Completed: \(data)") }
1func uploadData(key: String, data: Data) async throws {
2 let options = StorageUploadDataRequest.Options(accessLevel: .protected)
3 let uploadTask = Amplify.Storage.uploadData(
4 key: key,
5 data: data,
6 options: options
7 )
8 Task {
9 for await progress in await uploadTask.progress {
10 print("Progress: \(progress)")
11 }
12 }
13 let data = try await uploadTask.value
14 print("Completed: \(data)")
15}

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.

func downloadData(key: String, identityId: String) async throws { let options = StorageDownloadDataRequest.Options( accessLevel: .protected, targetIdentityId: identityId ) let downloadTask = Amplify.Storage.downloadData( key: key, options: options ) Task { for await progress in await downloadTask.progress { print("Progress: \(progress)") } } let data = try await downloadTask.value print("Completed: \(data)") }
1func downloadData(key: String, identityId: String) async throws {
2 let options = StorageDownloadDataRequest.Options(
3 accessLevel: .protected,
4 targetIdentityId: identityId
5 )
6
7 let downloadTask = Amplify.Storage.downloadData(
8 key: key,
9 options: options
10 )
11
12 Task {
13 for await progress in await downloadTask.progress {
14 print("Progress: \(progress)")
15 }
16 }
17 let data = try await downloadTask.value
18 print("Completed: \(data)")
19}

Private Access

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

let options = StorageUploadDataRequest.Options(accessLevel: .private)
1let options = StorageUploadDataRequest.Options(accessLevel: .private)

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:

let options = StorageDownloadDataRequest.Options(accessLevel: .private)
1let options = StorageDownloadDataRequest.Options(accessLevel: .private)

Customization

Customize Object Key Path

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

import Amplify import AWSPluginsCore import AWSS3StoragePlugin // Define your own prefix resolver, that conforms to `AWSS3StoragePluginPrefixResolver` struct MyDeveloperDefinedPrefixResolver: AWSS3PluginPrefixResolver { // This function is called on every Storage API to modify the prefix of the request. func resolvePrefix( for accessLevel: StorageAccessLevel, targetIdentityId: String? ) async throws -> String { // Use "myPublicPrefix" for guest access levels if accessLevel == .guest { return "myPublicPrefix/" } // Use "myProtectedPrefix/{identityId}" and "myPrivatePrefix/{identityId}" respectively let accessLevelPrefix: String if accessLevel == .protected { accessLevelPrefix = "myProtectedPrefix/" } else { accessLevelPrefix = "myPrivatePrefix/" } // `targetIdentityId` is the value passed into the Storage request object if let identityId = targetIdentityId { return accessLevelPrefix + identityId + "/" } // `identityId` is the identity id of the current user let identityId = try await getIdentityId() return accessLevelPrefix + identityId + "/" } func getIdentityId() async throws -> String { let session = try await Amplify.Auth.fetchAuthSession() if let identityProvider = session as? AuthCognitoIdentityProvider { return try identityProvider.getIdentityId().get() } else { throw StorageError.authError("Unable to retrieve identity id", "", nil) } } }
1import Amplify
2import AWSPluginsCore
3import AWSS3StoragePlugin
4
5// Define your own prefix resolver, that conforms to `AWSS3StoragePluginPrefixResolver`
6struct MyDeveloperDefinedPrefixResolver: AWSS3PluginPrefixResolver {
7
8 // This function is called on every Storage API to modify the prefix of the request.
9 func resolvePrefix(
10 for accessLevel: StorageAccessLevel,
11 targetIdentityId: String?
12 ) async throws -> String {
13 // Use "myPublicPrefix" for guest access levels
14 if accessLevel == .guest {
15 return "myPublicPrefix/"
16 }
17
18 // Use "myProtectedPrefix/{identityId}" and "myPrivatePrefix/{identityId}" respectively
19 let accessLevelPrefix: String
20 if accessLevel == .protected {
21 accessLevelPrefix = "myProtectedPrefix/"
22 } else {
23 accessLevelPrefix = "myPrivatePrefix/"
24 }
25
26 // `targetIdentityId` is the value passed into the Storage request object
27 if let identityId = targetIdentityId {
28 return accessLevelPrefix + identityId + "/"
29 }
30
31 // `identityId` is the identity id of the current user
32 let identityId = try await getIdentityId()
33 return accessLevelPrefix + identityId + "/"
34 }
35
36 func getIdentityId() async throws -> String {
37 let session = try await Amplify.Auth.fetchAuthSession()
38 if let identityProvider = session as? AuthCognitoIdentityProvider {
39 return try identityProvider.getIdentityId().get()
40 } else {
41 throw StorageError.authError("Unable to retrieve identity id", "", nil)
42 }
43 }
44}

Then configure the storage plugin with the resolver.

let storagePlugin = AWSS3StoragePlugin(configuration: .prefixResolver(MyDeveloperDefinedPrefixResolver())) Amplify.add(storagePlugin)
1let storagePlugin = AWSS3StoragePlugin(configuration: .prefixResolver(MyDeveloperDefinedPrefixResolver()))
2Amplify.add(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/:

"Statement": [ { "Effect": "Allow", "Action": [ "s3:GetObject", "s3:PutObject", "s3:DeleteObject" ], "Resource": [ "arn:aws:s3:::your-s3-bucket/myPublicPrefix/*", ] } ]
1"Statement": [
2 {
3 "Effect": "Allow",
4 "Action": [
5 "s3:GetObject",
6 "s3:PutObject",
7 "s3:DeleteObject"
8 ],
9 "Resource": [
10 "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:

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

This ensures only the authenticated users has the access to the objects under the path.

Passthrough PrefixResolver

If you would like no prefix resolution logic, such as performing S3 requests at the root of the bucket, create a prefix resolver that returns an empty string:

func resolvePrefix( for accessLevel: StorageAccessLevel, targetIdentityId: String? ) async throws -> String { return "" }
1func resolvePrefix(
2 for accessLevel: StorageAccessLevel,
3 targetIdentityId: String?
4) async throws -> String {
5 return ""
6}

Client validation

You can also perform validation based on the access controls you have defined. For example, if you have defined Guests with no access then you can fail the request early by checking if the user is not signed in:

This will only stop your app from making a call with an unauthenticated user. You must also set up your IAM policies to protect your resources. See CLI Storage for more details.

struct MyDeveloperDefinedPrefixResolver: AWSS3PluginPrefixResolver { func resolvePrefix( for accessLevel: StorageAccessLevel, targetIdentityId: String? ) async throws -> String { guard await Amplify.Auth.getCurrentUser() != nil else { throw StorageError.authError("User is not signed in", "", nil) } // Continue to resolve the prefix for the request // ... } }
1struct MyDeveloperDefinedPrefixResolver: AWSS3PluginPrefixResolver {
2 func resolvePrefix(
3 for accessLevel: StorageAccessLevel,
4 targetIdentityId: String?
5 ) async throws -> String {
6 guard await Amplify.Auth.getCurrentUser() != nil else {
7 throw StorageError.authError("User is not signed in", "", nil)
8 }
9
10 // Continue to resolve the prefix for the request
11 // ...
12 }
13}