Todos los productos
Search
Centro de documentos

Object Storage Service:Authorize access (iOS SDK)

Última actualización: Sep 03, 2026

El SDK de Object Storage Service (OSS) para iOS ofrece el modo de autenticación mediante Security Token Service (STS), el modo autofirmado y URL prefirmadas para garantizar la seguridad de los datos en dispositivos móviles.

Notas

Cuando utilice el modo de autenticación STS o el modo autofirmado, asegúrese de que la función de callback que emplee pueda devolver el token de seguridad y la firma. Si necesita obtener el token y la firma del servidor de aplicaciones mediante una solicitud dentro de la función de callback, se recomienda llamar a las operaciones síncronas de la API incluidas en la biblioteca de red. La función de callback se ejecuta en el hilo secundario de la solicitud generada por el SDK y no bloquea el hilo principal.

Modo de autenticación STS

Para acceder a OSS con credenciales de acceso temporal proporcionadas por STS, realice las siguientes operaciones:

  1. Obtenga credenciales de acceso temporal.

    Las credenciales de acceso temporal contienen un token de seguridad y un par de AccessKey temporal. Un par de AccessKey consta de un AccessKey ID y un AccessKey secret. El periodo de validez mínimo de las credenciales de acceso temporal es de 900 segundos. El periodo de validez máximo corresponde a la duración máxima de sesión especificada para el rol actual. Para obtener más información, consulte Specify the maximum session duration for a RAM role.

    Puede utilizar uno de los siguientes métodos para obtener credenciales de acceso temporal:

  2. Utilice las credenciales de acceso temporal para inicializar el SDK de OSS para iOS.

    id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:@"<StsToken.AccessKeyId>" secretKeyId:@"<StsToken.SecretKeyId>" securityToken:@"<StsToken.SecurityToken>"];
    client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
    Nota

    Puede usar OSSAuthCredentialProvider para inicializar el SDK de OSS para iOS. Para obtener más información, consulte Initialization.

    Al inicializar el SDK con credenciales de acceso temporal, tenga en cuenta el periodo de validez del token STS. El siguiente código de ejemplo muestra cómo determinar dicho periodo de validez:

    NSDateFormatter * fm = [NSDateFormatter new];
    fm.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    [fm setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
    NSDate *expirationDate = [fm dateFromString:@"<StsToken.Expiration>"];
    NSTimeInterval interval = [expirationDate timeIntervalSinceDate:[NSDate date]];
    // The STS token is about to expire within less than five minutes. 
    if (interval < 5 * 60) {
        id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:@"<StsToken.AccessKeyId>" secretKeyId:@"<StsToken.SecretKeyId>" securityToken:@"<StsToken.SecurityToken>"];
        client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
    }
    • Actualice manualmente el token STS

      Cuando el token STS esté próximo a caducar, puede crear una nueva instancia de OSSClient o actualizar CredentialProvider mediante el siguiente método:

      id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:@"<StsToken.AccessKeyId>" secretKeyId:@"<StsToken.SecretKeyId>" securityToken:@"<StsToken.SecurityToken>"];
      client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
    • Actualice automáticamente el token STS

      Si desea que el SDK actualice automáticamente el token STS, debe implementar un callback en su aplicación. Este callback obtiene un token de federación (token STS) y lo devuelve al SDK, el cual lo utiliza para generar firmas. Cuando sea necesario renovar el token STS, el SDK invocará el callback para obtener uno nuevo.

      id<OSSCredentialProvider> credential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {
          // Implement a function that obtains a federation token and returns it as an OSSFederationToken object. 
          // If the federation token is not obtained, nil is returned. 
            OSSFederationToken * token;
          // Obtain a federation token from your server. 
          ...
          return token;
      }];
      client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
      Nota

      Si obtiene todos los campos necesarios para generar un token STS por otros medios, puede devolver el token directamente en el callback. En este caso, deberá actualizar manualmente el token y luego reconfigurar OSSCredentialProvider de la instancia OSSClient.

      Si la URL del servidor desde el que solicita un token es http://localhost:8080/distribute-token.json, se devolverá la siguiente respuesta de ejemplo:

      {
          "StatusCode": 200,
          "AccessKeyId":"STS.iA645eTOXEqP3cg3****",
          "AccessKeySecret":"rV3VQrpFQ4BsyHSAvi5NVLpPIVffDJv4LojU****",
          "Expiration":"2015-11-03T09:52:59Z",
          "SecurityToken":"CAES7QIIARKAAZPlqaN9ILiQZPS+JDkS/GSZN45RLx4YS/p3OgaUC+oJl3XSlbJ7StKpQ****"
      }                           

      El siguiente código de ejemplo muestra cómo implementar OSSFederationCredentialProvider:

      id<OSSCredentialProvider> credential2 = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {
          // Create a request to access your application server. 
          NSURL * url = [NSURL URLWithString:@"http://localhost:8080/distribute-token.json"];
          // Use a request to set the parameters required by your server. 
          NSURLRequest * request = [NSURLRequest requestWithURL:url];
          OSSTaskCompletionSource * tcs = [OSSTaskCompletionSource taskCompletionSource];
          NSURLSession * session = [NSURLSession sharedSession];
          // Send the request. 
          NSURLSessionTask * sessionTask = [session dataTaskWithRequest:request
                                                      completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                          if (error) {
                                                              [tcs setError:error];
                                                              return;
                                                          }
                                                          [tcs setResult:data];
                                                      }];
          [sessionTask resume];
          // Wait until the response to the request is returned. 
          [tcs.task waitUntilFinished];
          // Parse the returned results. 
          if (tcs.task.error) {
              NSLog(@"get token error: %@", tcs.task.error);
              return nil;
          } else {
              // The returned data is in the JSON format. Parse the data to obtain the values of the fields of the token. 
              NSDictionary * object = [NSJSONSerialization JSONObjectWithData:tcs.task.result
                                                                      options:kNilOptions
                                                                        error:nil];
              OSSFederationToken * token = [OSSFederationToken new];
              token.tAccessKey = [object objectForKey:@"AccessKeyId"];
              token.tSecretKey = [object objectForKey:@"AccessKeySecret"];
              token.tToken = [object objectForKey:@"SecurityToken"];
              token.expirationTimeInGMTFormat = [object objectForKey:@"Expiration"];
              NSLog(@"get token: %@", token);
              return token;
          }
      }];

URL prefirmadas

Notas de uso

  • Cuando utiliza un SDK de OSS para generar una URL prefirmada, este calcula una firma mediante un algoritmo específico basado en la información de clave almacenada localmente y la agrega a la URL para garantizar su validez y seguridad. Las operaciones de cálculo y construcción de la URL se completan en el cliente, por lo que no es necesario enviar solicitudes al servidor a través de la red. De esta manera, no tiene que otorgar permisos específicos al llamante al generar la URL prefirmada. Sin embargo, para permitir que usuarios externos realicen operaciones sobre los recursos autorizados por dicha URL, debe asegurarse de que la entidad principal que llama a las operaciones de la API para generarla cuente con los permisos correspondientes.

    Por ejemplo, si una entidad principal desea cargar un objeto mediante una URL prefirmada, debe otorgarle el permiso oss:PutObject. Si desea descargar o previsualizar un objeto mediante una URL prefirmada, debe otorgarle el permiso oss:GetObject.

  • La URL prefirmada generada con el siguiente código de ejemplo podría contener un signo más (+). En ese caso, reemplace el signo más (+) en la URL por %2B. De lo contrario, es posible que la URL prefirmada no permita acceder al objeto correctamente.

Usar una URL prefirmada para cargar un objeto

  1. Genere una URL prefirmada.

    // Specify the name of the bucket. 
    NSString *bucketName = @"examplebucket";
    // Specify the name of the object. 
    NSString *objectKey = @"exampleobject.txt";
    NSURL *file = [NSURL fileURLWithPath:@"<filePath>"];
    NSString *contentType = [OSSUtil detemineMimeTypeForFilePath:file.absoluteString uploadName:objectKey];
    __block NSString *urlString;
    // Generate a presigned URL with a validity period for uploading the object. In this example, the validity period of the URL is 30 minutes. 
    OSSTask *task = [client presignConstrainURLWithBucketName:bucketName
                                                withObjectKey:objectKey
                                                   httpMethod:@"PUT"
                                       withExpirationInterval:30 * 60
                                               withParameters:@{}
                                                  contentType:contentType
                                                   contentMd5:nil];
    [task continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {
        if (task.error) {
            NSLog(@"presign error: %@", task.error);
        } else {
            urlString = task.result;
            NSLog(@"url: %@", urlString);
        }
        return nil;
    }];
  2. Utilice la URL prefirmada para cargar el objeto.

    // Upload the object using the presigned URL. 
    NSURL * url = [NSURL URLWithString:urlString];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"PUT";
    request.allHTTPHeaderFields = @{OSSHttpHeaderContentType: contentType};
    NSURLSession * session = [NSURLSession sharedSession];
    NSURLSessionTask * sessionTask = [session uploadTaskWithRequest:request
                                                           fromFile:file
                                                  completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"upload error: %@", error);
            return;
        } else if (((NSHTTPURLResponse*)response).statusCode == 203 ||
                   ((NSHTTPURLResponse*)response).statusCode >= 300) {
            NSString *body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"upload error: %@", body);
            return;
        }
        NSLog(@"upload success");
    }];
    [sessionTask resume];

Usar una URL prefirmada para descargar un objeto

  1. Genere una URL prefirmada.

    // Specify the name of the bucket. 
    NSString *bucketName = @"examplebucket";
    // Specify the name of the object. 
    NSString *objectKey = @"exampleobject.txt";
    __block NSString *urlString;
    // Generate a presigned URL with a validity period for downloading the object. In this example, the validity period of the URL is 30 minutes. 
    OSSTask *task = [client presignConstrainURLWithBucketName:bucketName
                                                withObjectKey:objectKey
                                                   httpMethod:@"GET"
                                       withExpirationInterval:30 * 60
                                               withParameters:@{}];
    [task continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {
        if (task.error) {
            NSLog(@"presign error: %@", task.error);
        } else {
            urlString = task.result;
            NSLog(@"url: %@", urlString);
        }
        return nil;
    }];
  2. Utilice la URL prefirmada para descargar el objeto

    // Use the presigned URL to download the object. 
    NSURL * url = [NSURL URLWithString:urlString];
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    NSURLSession * session = [NSURLSession sharedSession];
    NSURLSessionTask * sessionTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"download error: %@", error);
            return;
        } else if (((NSHTTPURLResponse*)response).statusCode == 203 ||
                   ((NSHTTPURLResponse*)response).statusCode >= 300) {
            NSString *body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"download error: %@", body);
            return;
        }
        NSLog(@"download success");
    }];
    [sessionTask resume];