OSS SDK for iOS provides two authentication modes to ensure the data security of mobile devices: Security Token Service (STS) authentication mode and self-signed mode.

Background information

When you use either the STS authentication mode or self-signed mode, ensure that the callback function that you implement returns results. If you must obtain the token and signature from the app server by sending a request in the callback function, we recommend that you call the synchronous API operations included in the network library. The callback function is run in the child thread of the request generated by the SDK and does not block the main thread.

STS authentication mode

Note To use the STS authentication mode, you must first activate Alibaba Cloud RAM.

You can use STS to authorize temporary access to OSS. STS is a web service that provides temporary access tokens for cloud computing users. You can use STS to grant an access credential with a custom validity period and custom permissions for a third-party application or a RAM user managed by you. For more information about STS, see What is STS?

STS has the following benefits:

  • You need only to generate an access token and send the access token to a third-party application, instead of exposing your AccessKey pair to the third-party application. You can customize the access permissions and validity period of this token.
  • The access token automatically expires after the validity period. Therefore, you do not need to manually revoke the permissions of an access token.

For more information about how to access OSS by using STS, see Use a temporary credential provided by STS to access OSS in OSS Developer Guide.

  • Configure an STS token

    You can obtain an STSToken in the app by a certain method, such as sending a request to the app server, and use the STSToken to initialize the SDK. If you use this method, you must pay attention to the expiration time of the STSToken. When the STSToken is about to expire, you must update the new STSToken for the SDK.

    The following code provides an example on how to use an obtained STS token to initialize OSS SDK for iOS:
    Note To use OSSAuthCredentialProvider to initialize OSS SDK for iOS, see Initialization.
    id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:@"<StsToken.AccessKeyId>" secretKeyId:@"<StsToken.SecretKeyId>" securityToken:@"<StsToken.SecurityToken>"];
    client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];

    When the STSToken is about to expire, you can create a new OSSClient or update OSSStsTokenCredentialProvider by using the following method:

    id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:@"<StsToken.AccessKeyId>" secretKeyId:@"<StsToken.SecretKeyId>" securityToken:@"<StsToken.SecurityToken>"];
    client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
  • Obtain an STS token by implementing callback

    If you want the SDK to automatically update the STSToken, you must implement callback in your app. The app uses the callback to obtain a FederationToken (STSToken) and returns it to the SDK. The SDK uses the STSToken for signing. When the STSToken needs to be updated, the SDK calls the callback to obtain a new token.

    id<OSSCredentialProvider> credential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {
        // Implement a method to obtain a FederationToken and return it as an OSSFederationToken object. 
        // If the FederationToken is not obtained, nil is returned. 
          OSSFederationToken * token;
        // Obtain a FederationToken from your server. 
        ...
        return token;
    }];
    client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
    Note Additionally, if you have obtained all fields required to generate a token in other methods, you can also return these fields by using the callback. In this case, you must manually update the token, and then reconfigure OSSCredentialProvider of the OSSClient instance.

    Examples:

    The URL of the server from which you obtain the token is http://localhost:8080/distribute-token.json. If you access this URL, the following similar data is returned:

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

    The following code provides an example on how to implement OSSFederationCredentialProvider:

    id<OSSCredentialProvider> credential2 = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {
        // Create a request to access your service server. 
        NSURL * url = [NSURL URLWithString:@"http://localhost:8080/distribute-token.json"];
        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;
        }
    }];

Self-signed mode

You can perform the following operations to save the AccessKey ID and AccessKey secret on your own server and then use them to sign the client information.
  1. Obtain the string to sign from the client and send the string to your own server.
    1. Use the signContent method of OSSCustomSignerCredentialProvider provided by OSS SDK for iOS to obtain the string to sign when you create the request.
    2. Send the string to sign to your own server.
  2. Sign the string on your own server and return the signed string to the client.
    1. Use the specified signature algorithm to sign the string. For more information about the signature algorithm, see Add signatures to headers.

      The signature is in the following format: signature = "OSS " + AccessKeyId + ":" + base64(hmac-sha1(AccessKeySecret, content)), in which content is the string that is concatenated based on the request parameters. The following code provides an example on how to use the specified signature algorithm to sign a string:

      id<OSSCredentialProvider> credential = [[OSSCustomSignerCredentialProvider alloc] initWithImplementedSigner:^NSString *(NSString *contentToSign, NSError *__autoreleasing *error) {
          // Use the specified signature algorithm to sign a string, concatenate your AccessKey ID to the signed string, and then return the final string. 
          // Send the signed string to your own server and return the signature. 
          // If the string fails to be signed, the server returns nil with an error message. 
      NSString *signature = [OSSUtil calBase64Sha1WithData:contentToSign withSecret:@"<your accessKeySecret>"]; // In this example, the string is signed on the client by using the tool provided by OSS SDK for iOS. We recommend that you sign the string on your business server. 
          if (signature != nil) {
              *error = nil;
          } else {
              *error = [NSError errorWithDomain:@"<your domain>" code:-1001 userInfo:@"<your error info>"];
              return nil;
          }
          return [NSString stringWithFormat:@"OSS %@:%@", @"<your accessKeyId>", signature];
      }];
      
      client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
                  
    2. Return the signed string to the client.
  3. Send the signed string from the client to the OSS server for authentication.