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:

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}
1var resultSink: AnyCancellable?
2var progressSink: AnyCancellable?
3
4func uploadData(key: String, data: Data) {
5 let options = StorageUploadDataRequest.Options(accessLevel: .protected)
6 let uploadTask = Amplify.Storage.uploadData(
7 key: key,
8 data: data,
9 options: options
10 )
11 progressSink = uploadTask
12 .inProcessPublisher
13 .sink { progress in
14 print("Progress: \(progress)")
15 }
16
17 resultSink = uploadTask
18 .resultPublisher
19 .sink {
20 if case let .failure(storageError) = $0 {
21 print("Failed: \(storageError.errorDescription). \(storageError.recoverySuggestion)")
22 }
23 }
24 receiveValue: { data in
25 print("Completed: \(data)")
26 }
27}

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.

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}
1var progressSink: AnyCancellable?
2var resultSink: AnyCancellable?
3
4func downloadData(key: String, identityId: String) {
5 let options = StorageDownloadDataRequest.Options(
6 accessLevel: .protected,
7 targetIdentityId: identityId
8 )
9 let downloadTask = Amplify.Storage.downloadData(
10 key: key,
11 options: options
12 )
13 progressSink = downloadTask
14 .inProcessPublisher
15 .sink { progress in
16 print("Progress: \(progress)")
17 }
18
19 resultSink = downloadTask
20 .resultPublisher
21 .sink {
22 if case let .failure(storageError) = $0 {
23 print("Failed: \(storageError.errorDescription). \(storageError.recoverySuggestion)")
24 }
25 }
26 receiveValue: { data in
27 print("Completed: \(data)")
28 }
29}

Private Access

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

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:

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

Customization

Customize Object Key Path

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

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.

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/:

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:

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:

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.

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}