Name:
interface
Value:
Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.

Page updated Apr 29, 2024

File access levels

Amplify iOS v1 is deprecated as of June 1st, 2024. No new features or bug fixes will be added. Dependencies may become outdated and potentially introduce compatibility issues.

Please use the latest version (v2) of Amplify Library for Swift to get started. Refer to the upgrade guide for instructions on upgrading your application to the latest version.

Amplify libraries should be used for all new cloud connected applications. If you are currently using the AWS Mobile SDK for iOS, you can access the documentation here.

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, but only writable 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) {
let options = StorageUploadDataRequest.Options(accessLevel: .protected)
Amplify.Storage.uploadData(key: key, data: data, options: options) { progress in
print("Progress: \(progress)")
} resultListener: { event in
switch event {
case .success(let data):
print("Completed: \(data)")
case .failure(let storageError):
print("Failed: \(storageError.errorDescription). \(storageError.recoverySuggestion)")
}
}
}
var progressSink: AnyCancellable?
var resultSink: AnyCancellable?
func uploadData(key: String, data: Data) {
let options = StorageUploadDataRequest.Options(accessLevel: .protected)
let storageOperation = Amplify.Storage.uploadData(key: key, data: data, options: options)
progressSink = storageOperation.progressPublisher.sink { progress in print("Progress: \(progress)") }
resultSink = storageOperation.resultPublisher.sink {
if case let .failure(storageError) = $0 {
print("Failed: \(storageError.errorDescription). \(storageError.recoverySuggestion)")
}
}
receiveValue: { data in
print("Completed: \(data)")
}
}

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) {
let options = StorageDownloadDataRequest.Options(accessLevel: .protected, targetIdentityId: identityId)
Amplify.Storage.downloadData(
key: key,
options: options,
progressListener: { progress in
print("Progress: \(progress)")
}, resultListener: { (event) in
switch event {
case let .success(data):
print("Completed: \(data)")
case let .failure(storageError):
print("Failed: \(storageError.errorDescription). \(storageError.recoverySuggestion)")
}
})
}
var progressSink: AnyCancellable?
var resultSink: AnyCancellable?
func downloadData(key: String, identityId: String) {
let options = StorageDownloadDataRequest.Options(accessLevel: .protected,
targetIdentityId: identityId)
let storageOperation = Amplify.Storage.downloadData(key: key, options: options)
progressSink = storageOperation.progressPublisher.sink { progress in print("Progress: \(progress)") }
resultSink = storageOperation.resultPublisher.sink {
if case let .failure(storageError) = $0 {
print("Failed: \(storageError.errorDescription). \(storageError.recoverySuggestion)")
}
}
receiveValue: { data in
print("Completed: \(data)")
}
}

Private Access

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

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

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

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

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

Customization

Customize Object Key Path

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

import Amplify
import AmplifyPlugins
// 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?,
completion: @escaping (Result<String, StorageError>) -> Void
) {
// Use "myPublicPrefix" for guest access levels
if accessLevel == .guest {
completion(.success("myPublicPrefix/"))
return
}
// Use "myProtectedPrefix/{targetIdentityId}" and "myPrivatePrefix/{targetIdentityId}" respectively
// `targetIdentityId` is the value passed into the Storage request object,
if let identityId = targetIdentityId {
if accessLevel == .protected {
completion(.success("myProtectedPrefix/" + identityId + "/"))
} else if accessLevel == .private {
completion(.success("myPrivatePrefix/" + identityId + "/"))
}
return
}
// Use "myProtectedPrefix/{identityId}" and "myPrivatePrefix/{identityId}" respectively
// `identityId` is the identity id of the current user
getIdentityId { result in
switch result {
case .failure(let error):
completion(.failure(error))
case .success(let identityId):
if accessLevel == .protected {
completion(.success("myProtectedPrefix/" + identityId + "/"))
} else if accessLevel == .private {
completion(.success("myPrivatePrefix/" + identityId + "/"))
}
}
}
}
public func getIdentityId(completion: @escaping (Result<String, StorageError>) -> Void) {
Amplify.Auth.fetchAuthSession { result in
do {
let session = try result.get()
if let identityProvider = session as? AuthCognitoIdentityProvider {
let identityId = try identityProvider.getIdentityId().get()
completion(.success(identityId))
}
} catch {
completion(.failure(StorageError.authError("Failed to retrieve auth session", "", error)))
}
}
}
}

Then configure the storage plugin with the resolver.

let storagePlugin = AWSS3StoragePlugin(configuration: .prefixResolver(MyDeveloperDefinedPrefixResolver()))
Amplify.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/*",
]
}
]

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}/*"
]
}
]

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:

public func resolvePrefix(
for accessLevel: StorageAccessLevel,
targetIdentityId: String?
) -> Result<String, StorageError> {
return .success("")
}

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 {
public func resolvePrefix(
for accessLevel: StorageAccessLevel,
targetIdentityId: String?,
completion: @escaping (Result<String, StorageError>) -> Void
) {
guard Amplify.Auth.getCurrentUser() != nil else {
completion(.failure(.authError("User is not signed in", "", nil)))
return
}
// Continue to resolve the prefix for the request
// ...
}
}