edit-icon download-icon

Access control

Last Updated: Jan 07, 2019

A mobile device is an untrusted environment. Therefore, the SDK provides two authentication modes: STS authentication mode and self-signed mode.

STS authentication mode


OSS can temporarily grant authorization for access using the Alibaba Cloud STS service. Alibaba Cloud STS (Security Token Service) is a web service providing temporary access tokens for cloud computing users. With the STS, you can assign a third-party application or federated user (you can manage the user ID) an access credential with a custom validity period and permissions. The access credential in the application is called FederationToken. Third-party applications or federated users can use these access credentials to directly call the Alibaba Cloud APIs or use the SDKs provided by Alibaba Cloud to access the APIs of cloud products.

Advantages of STS

  • You do not need to disclose your long-term key (AccessKey) to a third-party application. You only need to generate an access token and send it to the third-party application. You can customize the access permissions and the validity of this token.

  • You do not need to revoke permissions. The access token becomes invalid automatically when it expires.

For example, the interaction process in an application is shown in the following figure:

How to use STS

  1. Log on to the application.

    You can manage your application ID. You can customize the ID management system or use an external web account or OpenID. For each valid app user, the AppServer can precisely define the minimum access permission.

  2. The AppServer requests a security token (SecurityToken) from the STS.

    1. Before the STS is called, the AppServer needs to determine the minimum access permission (in the policy syntax) of the application user and the expiration time of the authorization.

    2. You can obtain the security token by calling the STS AssumeRole API. For more information about the roles and usage, see Role Management in the RAM User Guide.

  3. The STS returns a valid access credential to the AppServer. The access credential contains a SecurityToken, a temporary pair of access keys (an AccessKeyID and an AccessKeySecret), and the expiration time.

  4. The AppServer returns the access credential to the ClientApp.

    The ClientApp can cache this credential. When the credential becomes invalid, the ClientApp needs to request a new valid access credential from the AppServer. For example, if the access credential is valid for one hour, the ClientApp can request the AppServer to update the access credential every 30 minutes.

  5. The ClientApp uses the locally cached access credential to request Alibaba Cloud service APIs. The cloud service detects the STS access credential, verifies the credential with the STS service, and responds to the user requests accordingly.

Note: To use this authentication mode, you must first activate Alibaba Cloud RAM service

Set the STSToken directly

You can get a pair of STSToken in an app or other mobile devices by a certain method (such as network requests from your business server) and then use it to initialize the SDK. If this method is adopted, you must follow the expiration time of the STSToken. When the STSToken is about to expire, you must take the initiative to update the new STSToken for the SDK.

The initialization code is:

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

When you notice that the token is about to expire, you can rebuild a new OSSClient or update the CredentialProvider by the following method:

  1. client.credentialProvider = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:@"<StsToken.AccessKeyId>" secretKeyId:@"<StsToken.SecretKeyId>" securityToken:@"<StsToken.SecurityToken>"];

Implement the callback to get the STSToken

If you want the SDK to automatically help you manage Token updates, you must configure the SDK to get the token. In the application of the SDK, you must implement a callback, which gets a FederationToken (STSToken) and returns the token. The SDK uses the token for signing. When the token needs to be updated, the SDK calls the callback to get the token, as shown in the following figure:

  1. id<OSSCredentialProvider> credential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {
  2. // Here you must implement a method to get a FederationToken and construct it into the OSSFederationToken object to return it
  3. // If the token is not obtained, "nil" is returned
  4. OSSFederationToken * token;
  5. // The following are some codes that can be used to obtain the token, for example from your server
  6. ...
  7. return token;
  8. }];
  9. client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];

Additionally, if you have obtained all the fields required by the token by other means, you can use the callback to directly return the token. In this case, you must manually update the token and then reset the OSSCredentialProvider of the OSSClient instance.


Suppose the URL of the server you set up is http://localhost:8080/distribute-token.json. If you access the URL, the returned data is shown as follows:

  1. {
  2. "StatusCode": 200,
  3. "AccessKeyId":"STS.iA645eTOXEqP3cg3VeHf",
  4. "AccessKeySecret":"rV3VQrpFQ4BsyHSAvi5NVLpPIVffDJv4LojUBZCf",
  5. "Expiration":"2015-11-03T09:52:59Z",
  6. "SecurityToken":"CAES7QIIARKAAZPlqaN9ILiQZPS+JDkS/GSZN45RLx4YS/p3OgaUC+oJl3XSlbJ7StKpQ...."}

You can use the following codes to implement the OSSFederationCredentialProvider instance:

  1. id<OSSCredentialProvider> credential2 = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {
  2. // Construct a request to access your business server
  3. NSURL * url = [NSURL URLWithString:@"http://localhost:8080/distribute-token.json"];
  4. NSURLRequest * request = [NSURLRequest requestWithURL:url];
  5. OSSTaskCompletionSource * tcs = [OSSTaskCompletionSource taskCompletionSource];
  6. NSURLSession * session = [NSURLSession sharedSession];
  7. // Send the request
  8. NSURLSessionTask * sessionTask = [session dataTaskWithRequest:request
  9. completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  10. if (error) {
  11. [tcs setError:error];
  12. return;
  13. }
  14. [tcs setResult:data];
  15. }];
  16. [sessionTask resume];
  17. // Use a blocking call to wait until the task is returned
  18. [tcs.task waitUntilFinished];
  19. // Parse the result
  20. if (tcs.task.error) {
  21. NSLog(@"get token error: %@", tcs.task.error);
  22. return nil;
  23. } else {
  24. // The returned data is in JSON format and you must parse it to obtain all fields of the token
  25. NSDictionary * object = [NSJSONSerialization JSONObjectWithData:tcs.task.result
  26. options:kNilOptions
  27. error:nil];
  28. OSSFederationToken * token = [OSSFederationToken new];
  29. token.tAccessKey = [object objectForKey:@"AccessKeyId"];
  30. token.tSecretKey = [object objectForKey:@"AccessKeySecret"];
  31. token.tToken = [object objectForKey:@"SecurityToken"];
  32. token.expirationTimeInGMTFormat = [object objectForKey:@"Expiration"];
  33. NSLog(@"get token: %@", token);
  34. return token;
  35. }
  36. }];

Self-signed mode

  1. id<OSSCredentialProvider> credential = [[OSSCustomSignerCredentialProvider alloc] initWithImplementedSigner:^NSString *(NSString *contentToSign, NSError *__autoreleasing *error) {
  2. // Here you must sign a string using the OSS-specified signature algorithm, merge the AccessKeyID with the signed string, and return the string
  3. // Generally, post the string to your business server and then return the signature
  4. // If the signing fails, "nil" is returned after the error is described
  5. NSString *signature = [OSSUtil calBase64Sha1WithData:contentToSign withSecret:@"<your accessKeySecret>"]; // The local signature is completed by using the utility function in the SDK. We recommend that you use the service server to obtain the remote signature
  6. if (signature != nil) {
  7. *error = nil;
  8. } else {
  9. *error = [NSError errorWithDomain:@"<your domain>" code:-1001 userInfo:@"<your error info>"];
  10. return nil;
  11. }
  12. return [NSString stringWithFormat:@"OSS %@:%@", @"<your accessKeyId>", signature];
  13. }];
  14. client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];

Note: For the STS authentication mode and self-signed mode, make sure that results are returned when you call the implemented callback function. Therefore, if you must obtain the token and signature from the business server with a network request, we recommend that you call the synchronous APIs of the network library or perform the conversion from asynchronization to synchronization. The callback is run in the subthread of the request from the SDKs, which does not block the main thread.

Thank you! We've received your feedback.