All Products
Search
Document Center

Obtain an access token

Last Updated: Jun 21, 2021

An access token is a credential for you to call Intelligent Speech Interaction services. This topic describes how to obtain an access token.

Prerequisites

The AccessKey ID and the AccessKey secret are obtained. For more information, see Activate Intelligent Speech Interaction.

You can use Alibaba Cloud SDK to request an access token from the cloud. When you send this request, you must provide the AccessKey ID and the AccessKey secret of your Alibaba Cloud account. You can also send an HTTP or HTTPS request from a client to obtain an access token based on your needs. For more information, see Use HTTP or HTTPS to obtain an access token.

Note

Before you use an access token, you must check the ExpireTime parameter to obtain the timestamp that indicates the validity period of the access token. If the access token expires, you must obtain a new access token.

Procedure

  1. Log on to the Intelligent Speech Interaction console.

  2. On the Overview page that appears, click Obtain AccessToken in the upper-right corner.

    You can use the SDK to call and test Intelligent Speech Interaction services based on the access token. This access token is for testing purposes only.

    The following code provides a response sample:

    {
        "NlsRequestId": "aed8c1af075347819118ff6bf811****",
        "RequestId": "0989F63E-5069-4AB0-822B-5BD2D953****",
        "Token": {
            "ExpireTime": 1527592757,
            "Id": "124fc7526f434b8c8198d6196b0a****",
            "UserId": "12345678****"
        }
    }

    where:

    • Id indicates the access token that is assigned to the request.

    • ExpireTime is the timestamp that represents 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 (UTC+8) on May 29, 2018.

Common error troubleshooting

If an error occurs when you call the SDK to obtain an access token, troubleshoot the error. For more information, see Error code table.

Note
  1. You are most likely to encounter the following error: Request was denied due to user flow control. This error indicates that the API request is rejected by Alibaba Cloud API Gateway because the API access frequency exceeds the threshold. To avoid this error, do not make frequent requests to obtain access tokens.

  2. After you obtain an access token, you can use it multiple times within the validity period across threads, processes, or servers.

Obtain an access token on a mobile client

We recommend that you integrate Alibaba Cloud SDK for Java on your server to obtain an access token.

  1. Integrate Alibaba Cloud SDK for Java on the server. Then, the server sends an HTTP GET request to call the */gettoken method to obtain an access token.

  2. The client calls the */gettoken method to obtain the access token and the validity period from the server.

  3. The client uses the access token to access Intelligent Speech Interaction services. Before the client calls an Intelligent Speech Interaction service, it sends a request to obtain an access token.

  4. The client stores the access token in the local cache. Before the access token expires, the client can continue to use the cached access token to access Intelligent Speech Interaction services. If the cached access token expires, the client obtains a new access token from the server and updates the local cache.

Use the SDK to obtain an access token

Call example for Java

Download the latest version of Alibaba Cloud SDK for Java from the maven server. Download the ZIP package of the demo source code.

<dependency>
    <groupId>com.alibaba.nls</groupId>
    <artifactId>nls-sdk-common</artifactId>
    <version>2.1.6</version>
</dependency>
AccessToken token = new AccessToken("your akID", "your akSecret");
token.apply();
String accessToken = token.getToken();
long expireTime = token.getExpireTime();
Note

The preceding java code is used on the server. An Android user must run code on the server or a PC client to obtain an access token. To ensure data security, we recommend that you build a server and use the client to request an access token from the server.

Call example for C++

Note

  • Install the following tools on Linux:

    • Glibc 2.5 or later

    • Ccc4 or Ccc5

  • Install the following tool on Windows: Visual Studio 2013 or Visual Studio 2015.

    Create a project on the Windows platform.

  1. Download Alibaba Cloud SDK for C++.

  2. Compile the sample file.

    Assume that the sample file is decompressed to the path/to directory. Run the following commands on the Linux terminal to compile and run the program.

    If the operating system supports CMake:

    1. Make sure that CMake 2.4 or later is installed in the local operating system.

    2. cd path/to/sdk/lib.

    3. tar -zxvpf linux.tar.gz.

    4. cd path/to/sdk.

    5. ./build.sh.

    6. cd path/to/sdk/demo.

    7. ./tokenDemo <yourAccessKeySecret> <yourAccessKeyId>.

    If the operating system does not support CMake:

    1. cd path/to/sdk/lib.

    2. tar -zxvpf linux.tar.gz.

    3. cd path/to/sdk/demo.

    4. g++ -o tokenDemo tokenDemo.cpp -I path/to/sdk/include/ -L path/to/sdk/lib/linux -ljsoncpp -lssl -lcrypto -lcurl -luuid -lnlsCommonSdk -D_GLIBCXX_USE_CXX11_ABI=0.

    5. export LD_LIBRARY_PATH=path/to/sdk/lib/linux/.

    6. ./tokenDemo <yourAccessKeySecret> <yourAccessKeyId>.

  3. Obtain an access token.

    The following sample code provides an example to show how to obtain an access token:

    #include <iostream>
    #include "Token.h"
    
    using std::cout;
    using std::endl;
    using namespace AlibabaNlsCommon;
    
    // Obtain the ID of the access token.
    int getTokenId(const char* keySecret, const char* keyId) {
        NlsToken nlsTokenRequest;
    
        / *Set the AccessKey secret of your Alibaba Cloud account.* /
        nlsTokenRequest.setKeySecret(keySecret);
        / *Set the AccessKey ID of your Alibaba Cloud account.* /
        nlsTokenRequest.setAccessKeyId(keyId);
    
        / *Obtain the access token. If the request is successful, 0 is returned. If the request has failed, -1 is returned.* /
        if (-1 == nlsTokenRequest.applyNlsToken()) {
            cout << "Failed: " << nlsTokenRequest.getErrorMsg() << endl; / *The cause of the request failure.* /
    
            return -1;
        } else {
            cout << "TokenId: " << nlsTokenRequest.getToken() << endl; / *The ID of the access token.* /
            cout << "TokenId expireTime: " << nlsTokenRequest.getExpireTime() << endl; / *The timestamp that indicates the validity period of the access token in seconds.* /
    
            return 0;
        }
    }

Call example for PHP

Note

The latest version of Alibaba Cloud SDK for PHP is used in this example. For more information, see Alibaba Cloud SDK for PHP. You can continue to use an earlier version of Alibaba Cloud SDK for PHP. However, we recommend that you update to the latest version. For more information about earlier versions, see aliyun-openapi-php-sdk.

Before you install Alibaba Cloud SDK for PHP, make sure that the environment uses PHP V5.5 or a later version. For more information, see Install Alibaba Cloud SDK for PHP.

To call Alibaba Cloud SDK for PHP, perform the following steps:

  1. Create a global client.

  2. Create an API request and set the parameters.

  3. Initiate the API request and process the response or exception.

<? php
require __DIR__ . '/vendor/autoload.php';
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
/**
 * Step 1: Set a global client.
 * Use the AccessKey ID and the AccessKey secret of your Alibaba Cloud RAM account to perform authentication.
 */
AlibabaCloud::accessKeyClient(
            "<your-access-key-id>",
            "<your-access-key-secret>")
            ->regionId("cn-shanghai")
            ->asDefaultClient();
try {
    $response = AlibabaCloud::nlsCloudMeta()
                            ->v20180518()
                            ->createToken()
                            ->request();
    print $response . "\n";
    $token = $response["Token"];
    if ($token ! = NULL) {
        print "Token obtained:\n";
        print_r($token);
    }
    else {
        print "Failed to obtain the token\n";
    }
} catch (ClientException $exception) {
    // Obtain the error message.
    print_r($exception->getErrorMessage());
} catch (ServerException $exception) {
    // Obtain the error message.
    print_r($exception->getErrorMessage());
}

Use the CommonRequest method to obtain an access token

If you use Alibaba Cloud SDK to obtain an access token, we recommend that you call API operations in a remote procedure call (RPC) style. To initiate a common API request in an RPC style, you must specify the following parameters.

Parameter

Value

Description

domain

nls-meta.cn-shanghai.aliyuncs.com

The general endpoint of Intelligent Speech Interaction. The value is fixed.

region_id

cn-shanghai

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-02-28

The version number of the API. The value is fixed.

Call example for Java

  1. Add Java dependencies.

    Add dependencies on the core library (V3.7.1) of Alibaba Cloud SDK for Java and the fastjson library.

    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-core</artifactId>
        <version>3.7.1</version>
    </dependency>
    
    <! -- http://mvnrepository.com/artifact/com.alibaba/fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.49</version>
    </dependency>

  2. Obtain an access token.

    The following sample code provides an example to show how to obtain an access token:

    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import com.aliyuncs.CommonRequest;
    import com.aliyuncs.CommonResponse;
    import com.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.IAcsClient;
    import com.aliyuncs.exceptions.ClientException;
    import com.aliyuncs.http.MethodType;
    import com.aliyuncs.http.ProtocolType;
    import com.aliyuncs.profile.DefaultProfile;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class CreateTokenDemo {
    
        // The region ID of the requested Intelligent Speech Interaction service.
        private static final String REGIONID = "cn-shanghai";
        // The endpoint of the requested Intelligent Speech Interaction service.
        private static final String DOMAIN = "nls-meta.cn-shanghai.aliyuncs.com";
        // The version number of the API.
        private static final String API_VERSION = "2019-02-28";
        // The operation that you want to perform.
        private static final String REQUEST_ACTION = "CreateToken";
    
        // The response parameters.
        private static final String KEY_TOKEN = "Token";
        private static final String KEY_ID = "Id";
        private static final String KEY_EXPIRETIME = "ExpireTime";
    
    
        public static void main(String args[]) throws ClientException {
            if (args.length < 2) {
                System.err.println("CreateTokenDemo need params: <AccessKey Id> <AccessKey Secret>");
                System.exit(-1);
            }
    
            String accessKeyId = args[0];
            String accessKeySecret = args[1];
    
            // Create a DefaultAcsClient instance and initialize it.
            DefaultProfile profile = DefaultProfile.getProfile(
                    REGIONID,
                    accessKeyId,
                    accessKeySecret);
    
            IAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            request.setDomain(DOMAIN);
            request.setVersion(API_VERSION);
            request.setAction(REQUEST_ACTION);
            request.setMethod(MethodType.POST);
            request.setProtocol(ProtocolType.HTTPS);
    
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            if (response.getHttpStatus() == 200) {
                JSONObject result = JSON.parseObject(response.getData());
                String token = result.getJSONObject(KEY_TOKEN).getString(KEY_ID);
                long expireTime = result.getJSONObject(KEY_TOKEN).getLongValue(KEY_EXPIRETIME);
                System.out.println("Obtained token: " + token + ", Timestamp of the validity period (unit: seconds): " + expireTime);
                // Convert the 10-digit timestamp to a time in UTC+8.
                String expireDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(expireTime * 1000));
                System.out.println("Validity period of the access token in UTC+8: " + expireDate);
            }
            else {
                System.out.println("Failed to obtain the token.") ;
            }
        }
    }
    
    

Call example for Python

  1. Run a pip command to install the SDK.

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

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

  2. Obtain an access token.

    The following sample code provides an example to show how to obtain an access token:

    # -*- coding: utf8 -*-
    
    from aliyunsdkcore.client import AcsClient
    from aliyunsdkcore.request import CommonRequest
    
    # Create an AcsClient instance.
    client = AcsClient(
       "<Your AccessKey ID>",
       "<Your AccessKey secret>",
       "cn-shanghai"
    );
    
    # Create an API request and set the parameters.
    request = CommonRequest()
    request.set_method('POST')
    request.set_domain('nls-meta.cn-shanghai.aliyuncs.com')
    request.set_version('2019-02-28')
    request.set_action_name('CreateToken')
    response = client.do_action_with_exception(request)
    
    print(response)

Call example for GO

The following sample code provides an example to show how to obtain an access token:

package main
import (
    "fmt"
    "github.com/aliyun/alibaba-cloud-sdk-go/sdk"
    "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
)
func main() {
    client, err := sdk.NewClientWithAccessKey("cn-shanghai", "<Your AccessKey ID>", "<Your AccessKey secret>")
    if err ! = nil {
        panic(err)
    }
    request := requests.NewCommonRequest()
    request.Method = "POST"
    request.Domain = "nls-meta.cn-shanghai.aliyuncs.com"
    request.ApiName = "CreateToken"
    request.Version = "2019-02-28"
    response, err := client.ProcessCommonRequest(request)
    if err ! = nil {
        panic(err)
    }
    fmt.Print(response.GetHttpStatus())
    fmt.Print(response.GetHttpContentString())
}

Call example for Node.js

  1. Install Alibaba Cloud SDK for Node.js.

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

    Assume that Alibaba Cloud SDK for Node.js is downloaded to the /path/to/aliyun-openapi-Node.js-sdk directory. When 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 writes the module to the package.json file of the application as a dependent module:

    $ npm install @alicloud/pop-core --save
    Note

    You can also download the SDK from GitHub. For more information, see Download the SDK on GitHub.

  2. Obtain an access token.

    The following sample code provides an example to show how to obtain an access token:

    var RPCClient = require('@alicloud/pop-core').RPCClient;
    
    var client = new RPCClient({
      accessKeyId: '<Your AccessKey ID>',
      accessKeySecret: '<Your AccessKey secret>',
      endpoint: 'http://nls-meta.cn-shanghai.aliyuncs.com',
      apiVersion: '2019-02-28'
    });
    
    // => returns Promise
    // => request(Action, params, options)
    client.request('CreateToken').then((result) => {
        console.log(result.Token);
    });
    

Call example for .NET

  1. Install Alibaba Cloud SDK for .NET.

    In the .NET demo that is used to obtain an access token, the CommonRequest method of the Alibaba Cloud SDK for. NET is used to send pctowap open platform (POP) API requests in an RPC style. For more information about Alibaba Cloud SDK for .NET, see Use .NET SDK.

    For more information about how to use the CommonRequest method of Alibaba Cloud SDK for .NET, see Use CommonRequest.

    You need only to install the core library of Alibaba Cloud SDK for .NET. If you want to install Alibaba Cloud SDK for .NET, you can add the reference to a Dynamic Link Library (DLL) file or a project. For more information, see Use .NET SDK.

  2. Obtain an access token.

    The following sample code provides an example to show how to obtain an access token:

    using System;
    using Aliyun.Acs.Core;
    using Aliyun.Acs.Core.Exceptions;
    using Aliyun.Acs.Core.Profile;
    class Sample
    {
        static void Main(string[] args)
        {
            // Create a client instance to initiate a request.
            IClientProfile profile = DefaultProfile.GetProfile(
                "cn-shanghai",
                "<Your AccessKey ID>",
                "<Your AccessKey secret>");
            DefaultAcsClient client = new DefaultAcsClient(profile);
    
            try
            {
                // Create an API request.
                CommonRequest request = new CommonRequest();
                request.Domain = "nls-meta.cn-shanghai.aliyuncs.com";
                request.Version = "2019-02-28";
    
                // This API request is in an RPC style. Set the Action parameter to the RPC API operation that you want to perform.
                request.Action = "CreateToken";
    
                // Initiate the API request and obtain a response.
                CommonResponse response = client.GetCommonResponse(request);
                System.Console.WriteLine(response.Data);
            }
            catch (ServerException ex)
            {
                System.Console.WriteLine(ex.ToString());
            }
            catch (ClientException ex)
            {
                System.Console.WriteLine(ex.ToString());
            }
        }
    }