All Products
Search
Document Center

Obtain a token

Last Updated: May 22, 2020

Overview

An access token is a credential for you to call an Intelligent Speech Interaction service. You can use the Alibaba Cloud public SDK to send a request for an access token. When you send this request, you must provide the AccessKey ID and AccessKey secret of your Alibaba Cloud account. In addition, you can also send an HTTP or HTTPS request for an access token from the client as needed. For more information, see Use HTTP or HTTPS to obtain a token.

Before using an access token, you need to check the ExpireTime parameter to obtain the timestamp that indicates the validity period of the access token. If the access token expires, you need to obtain a valid one.

You can obtain an access token used for testing from the Intelligent Speech Interaction console as follows: Click All Projects in the left-side navigation pane. On the My Projects page, click Obtain AccessToken. Based on this access token, you can use the SDK to call and test an Intelligent Speech Interaction service.

Sample response:

  1. {
  2. "NlsRequestId": "aed8c1af075347819118ff6bf8111168",
  3. "RequestId": "0989F63E-5069-4AB0-822B-5BD2D95356DF",
  4. "Token": {
  5. "ExpireTime": 1527592757,
  6. "Id": "124fc7526f434b8c8198d6196b0a1c8e",
  7. "UserId": "123456789012"
  8. }
  9. }

The parameters in the Token object are described as follows:

  • Id: the access token that is assigned.
  • ExpireTime: the timestamp that indicates the validity period of the access token. Unit: seconds. For example, a value of 1527592757 indicates that the access token is valid before 19:19:17 on May 29, 2018, UTC+8.

Common error troubleshooting

If an error occurs when you use the SDK to obtain an access token, you can resolve the error according to the error code. For more information, see Error code table.

Obtain an access token on a mobile client

We recommend that you integrate the SDK on the server to obtain an access token.

The procedure in a typical scenario is as follows:

  • Integrate the Java SDK on the server. Then, the server can send an HTTP GET request to call the */gettoken method to obtain an access token.
  • The client calls the */gettoken method to obtain access token A and its validity period from the server.
  • The client uses access token A to call an Intelligent Speech Interaction service. The client can request an access token from the server each time before calling an Intelligent Speech Interaction service.
  • The client stores access token A in the local cache. If it calls a service next time within the validity period of access token A, it can directly use the locally cached token. If access token A expires, the client can obtain an access token from the server to update the locally cached token.

Use the CommonRequest method to obtain an access token

If you use the Alibaba Cloud public SDK to obtain an access token, we recommend that you use APIs in a remote procedure call (RPC) style. To initiate a common API request in an RPC style, you need to provide some parameters, as described in the following table.

Parameter Value Description
domain nlsmeta.ap-southeast-1.aliyuncs.com The universal endpoint of Intelligent Speech Interaction. The value is fixed.
region_id ap-southeast-1 The region ID of the requested Intelligent Speech Interaction service. The value is fixed.
action CreateToken The operation that you want to perform. The value is fixed.
version 2019-07-17 The version of the API. The value is fixed.

Call example for Java

  1. Add Java dependencies.

You only need to add dependencies on the core library (V3.7.1) of the Alibaba Cloud SDK for Java and the fastjson library.

  1. <dependency>
  2. <groupId>com.aliyun</groupId>
  3. <artifactId>aliyun-java-sdk-core</artifactId>
  4. <version>3.7.1</version>
  5. </dependency>
  6. <!-- http://mvnrepository.com/artifact/com.alibaba/fastjson -->
  7. <dependency>
  8. <groupId>com.alibaba</groupId>
  9. <artifactId>fastjson</artifactId>
  10. <version>1.2.49</version>
  11. </dependency>
  1. Obtain an access token.

Use the following sample code:

  1. import com.alibaba.fastjson.JSON;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.aliyuncs.CommonRequest;
  4. import com.aliyuncs.CommonResponse;
  5. import com.aliyuncs.DefaultAcsClient;
  6. import com.aliyuncs.IAcsClient;
  7. import com.aliyuncs.exceptions.ClientException;
  8. import com.aliyuncs.http.MethodType;
  9. import com.aliyuncs.http.ProtocolType;
  10. import com.aliyuncs.profile.DefaultProfile;
  11. import java.text.SimpleDateFormat;
  12. import java.util.Date;
  13. public class CreateTokenDemo {
  14. // The region ID of the requested Intelligent Speech Interaction service.
  15. private static final String REGIONID = "ap-southeast-1";
  16. // The endpoint of the requested Intelligent Speech Interaction service.
  17. private static final String DOMAIN = "nlsmeta.ap-southeast-1.aliyuncs.com";
  18. // The version of the API.
  19. private static final String API_VERSION = "2019-07-17";
  20. // The operation that you want to perform.
  21. private static final String REQUEST_ACTION = "CreateToken";
  22. // The response parameters.
  23. private static final String KEY_TOKEN = "Token";
  24. private static final String KEY_ID = "Id";
  25. private static final String KEY_EXPIRETIME = "ExpireTime";
  26. public static void main(String args[]) throws ClientException {
  27. if (args.length < 2) {
  28. System.err.println("CreateTokenDemo need params: <AccessKey Id> <AccessKey Secret>");
  29. System.exit(-1);
  30. }
  31. String accessKeyId = args[0];
  32. String accessKeySecret = args[1];
  33. // Create a DefaultAcsClient instance and initialize it.
  34. DefaultProfile profile = DefaultProfile.getProfile(
  35. REGIONID,
  36. accessKeyId,
  37. accessKeySecret);
  38. IAcsClient client = new DefaultAcsClient(profile);
  39. CommonRequest request = new CommonRequest();
  40. request.setDomain(DOMAIN);
  41. request.setVersion(API_VERSION);
  42. request.setAction(REQUEST_ACTION);
  43. request.setMethod(MethodType.POST);
  44. request.setProtocol(ProtocolType.HTTPS);
  45. CommonResponse response = client.getCommonResponse(request);
  46. System.out.println(response.getData());
  47. if (response.getHttpStatus() == 200) {
  48. JSONObject result = JSON.parseObject(response.getData());
  49. String token = result.getJSONObject(KEY_TOKEN).getString(KEY_ID);
  50. long expireTime = result.getJSONObject(KEY_TOKEN).getLongValue(KEY_EXPIRETIME);
  51. System.out.println("Obtained token: " + token + ", Timestamp of the validity period (Unit: seconds): " + expireTime);
  52. // Convert the 10-digit timestamp to a time in UTC+8.
  53. String expireDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(expireTime * 1000));
  54. System.out.println("Validity period of the token in UTC+8: " + expireDate);
  55. }
  56. else {
  57. System.out.println("Failed to obtain the token.") ;
  58. }
  59. }
  60. }

Call example for Python

  1. Run a pip command to install the SDK.

Run the following pip command to install the Python SDK V2.13.3:

  1. pip install aliyun-python-sdk-core==2.13.3 # Install the core library of the Alibaba Cloud SDK for Python.

Note: In this topic, the latest SDK version that you can use to obtain an access token may be subject to change from time to time. You can continue to use the SDK version that you have installed.

  1. Run the sample code.
  1. # -*- coding: utf8 -*-
  2. from aliyunsdkcore.client import AcsClient
  3. from aliyunsdkcore.request import CommonRequest
  4. # Create an AcsClient instance.
  5. client = AcsClient(
  6. "<Your AccessKey Id>",
  7. "<Your AccessKey Secret>",
  8. "ap-southeast-1"
  9. );
  10. # Create a request and set parameters.
  11. request = CommonRequest()
  12. request.set_method('POST')
  13. request.set_domain('nlsmeta.ap-southeast-1.aliyuncs.com')
  14. request.set_version('2019-07-17')
  15. request.set_action_name('CreateToken')
  16. response = client.do_action_with_exception(request)
  17. print(response)

Call example for Go

Use the following sample code:

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/aliyun/alibaba-cloud-sdk-go/sdk"
  5. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
  6. )
  7. func main() {
  8. client, err := sdk.NewClientWithAccessKey("ap-southeast-1", "<Your AccessKey Id>", "<Your AccessKey Secret>")
  9. if err != nil {
  10. panic(err)
  11. }
  12. request := requests.NewCommonRequest()
  13. request.Method = "POST"
  14. request.Domain = "nlsmeta.ap-southeast-1.aliyuncs.com"
  15. request.ApiName = "CreateToken"
  16. request.Version = "2019-07-17"
  17. response, err := client.ProcessCommonRequest(request)
  18. if err != nil {
  19. panic(err)
  20. }
  21. fmt.Print(response.GetHttpStatus())
  22. fmt.Print(response.GetHttpContentString())
  23. }

Call example for Node.js

  1. Install the Node.js SDK.

We recommend that you use npm to install dependent modules for Node.js. All official Node.js SDKs of Alibaba Cloud are stored in the @alicloud directory.

Assume that the Node.js SDK is downloaded and installed in the /path/to/aliyun-openapi-Node.js-sdk directory.If you develop an application based on the SDK core library, run the following command to install the @alicloud/pop-core module.

The —save option in the following command adds the module to the package.json file of your application as a dependent module.

  1. $ npm install @alicloud/pop-core --save

In addition, you can also download SDK packages from GitHub.

  1. Run the sample code.
  1. var RPCClient = require('@alicloud/pop-core').RPCClient;
  2. var client = new RPCClient({
  3. accessKeyId: '<Your AccessKey Id>',
  4. accessKeySecret: '<Your AccessKey Secret>',
  5. endpoint: 'https://nlsmeta.ap-southeast-1.aliyuncs.com',
  6. apiVersion: '2019-07-17'
  7. });
  8. // => returns Promise
  9. // => request(Action, params, options)
  10. client.request('CreateToken').then((result) => {
  11. console.log(result.Token);
  12. });

Call example for .NET

  1. Install the .NET SDK.

The .NET demo for obtaining an access token uses the CommonRequest method of the Alibaba Cloud SDK for .NET to send pctowap open platform (POP) API requests in an RPC style. For more information about the Alibaba Cloud SDK for .NET, see Use .NET SDK in .NET SDK Developer Guide. For more information about how to use the CommonRequest method of the .NET SDK, see Use CommonRequest in .NET SDK Developer Guide.

You only need to install the core library of the Alibaba Cloud SDK for .NET. To install the .NET SDK, you can add the reference to a DLL file or a project. For more information, see Use .NET SDK in .NET SDK Developer Guide.

  1. Run the sample code.
  1. using System;
  2. using Aliyun.Acs.Core;
  3. using Aliyun.Acs.Core.Exceptions;
  4. using Aliyun.Acs.Core.Profile;
  5. class Sample
  6. {
  7. static void Main(string[] args)
  8. {
  9. // Create a client to initiate requests.
  10. IClientProfile profile = DefaultProfile.GetProfile(
  11. "ap-southeast-1",
  12. "<Your AccessKey Id>",
  13. "<Your AccessKey Secret>");
  14. DefaultAcsClient client = new DefaultAcsClient(profile);
  15. try
  16. {
  17. // Create a request.
  18. CommonRequest request = new CommonRequest();
  19. request.Domain = "nlsmeta.ap-southeast-1.aliyuncs.com";
  20. request.Version = "2019-07-17";
  21. // Set the Action parameter to the RPC API operation that you want to perform.
  22. request.Action = "CreateToken";
  23. // Send the request and obtain a response.
  24. CommonResponse response = client.GetCommonResponse(request);
  25. System.Console.WriteLine(response.Data);
  26. }
  27. catch (ServerException ex)
  28. {
  29. System.Console.WriteLine(ex.ToString());
  30. }
  31. catch (ClientException ex)
  32. {
  33. System.Console.WriteLine(ex.ToString());
  34. }
  35. }
  36. }