The SDKs handle token acquisition and renewal. This saves you from manually handling complex authentication logic and token lifecycle management. Using an SDK simplifies the development process, improves efficiency, and enhances security. This topic describes how to obtain a token using an SDK.
Background information
Method | Description |
Obtain a token using the Intelligent Speech Interaction SDK | Use this method to obtain a token directly with the Intelligent Speech Interaction SDK. We recommend that you integrate this SDK. |
Obtain a token using the Alibaba Cloud public SDK | Use this method if the Intelligent Speech Interaction service does not offer an SDK in your preferred programming language. |
Prerequisites
Obtain an AccessKey ID and an AccessKey Secret. For more information, see Get started.
Before calling the API, configure environment variables for your access credentials. The environment variables for the AccessKey ID and AccessKey Secret of Intelligent Speech Interaction are ALIYUN_AK_ID and ALIYUN_AK_SECRET.
Obtain a token with the Intelligent Speech Interaction SDK
Example (Java)
Download the latest version of the SDK from the Maven repository, and download the demo source code ZIP package.
<dependency>
<groupId>com.alibaba.nls</groupId>
<artifactId>nls-sdk-common</artifactId>
<version>2.1.6</version>
</dependency>The following example shows how to obtain an access token in Java:
AccessToken accessToken = new AccessToken(System.getenv().get("ALIYUN_AK_ID"), System.getenv().get("ALIYUN_AK_SECRET"));
accessToken.apply();
String token = accessToken.getToken();
long expireTime = accessToken.getExpireTime();The
tokenis allocated by the server. You can use this token until it expires. The token can be used concurrently on different machines, processes, or applications.The
expireTimeis a timestamp that indicates when the token expires, in seconds. For example,1527592757corresponds to 2018-05-29 19:19:17 (UTC+8). The token is valid until this time. After the token expires, you must obtain a new one.
To obtain a token, you must provide your AccessKey ID and AccessKey Secret. For security purposes, we recommend that you do not store your AccessKey ID and AccessKey Secret on the client side, such as in a mobile application. Use your AccessKey ID and AccessKey Secret in a secure environment.
If you are developing a mobile app, consider building a token generator service on your server. Store your AccessKey ID and AccessKey Secret on the server. Before the app calls the speech recognition service, it should first request a token from your server and then use that token to call the Intelligent Speech Interaction service.
Example (C++)
Tool requirements for Linux:
Glibc 2.5 or later
GCC 4 or GCC 5
For Windows: Visual Studio 2013 or VS2015. You must create and configure the project on the Windows platform.
Compile the demo.
Assume that the demo files are extracted to the
path/todirectory. Run the following commands in sequence in a Linux terminal to compile and run the program.If your development environment supports compilation with CMake:
Make sure that CMake 2.4 or later is installed on your system.
Change the directory:
cd path/to/sdk/lib.Extract the file:
tar -zxvpf linux.tar.gz.Change the directory:
cd path/to/sdk.Run the build script:
./build.sh.Change the directory:
cd path/to/sdk/demo.Run the token demo:
./tokenDemo <yourAccessKeySecret> <yourAccessKeyId>.
If your development environment does not support compilation with CMake:
Change the directory:
cd path/to/sdk/lib.Extract the file:
tar -zxvpf linux.tar.gz.Change the directory:
cd path/to/sdk/demo.Compile the demo program by using the g++ command:
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.Specify the library path:
export LD_LIBRARY_PATH=path/to/sdk/lib/linux/.Run the token demo:
./tokenDemo <yourAccessKeySecret> <yourAccessKeyId>.
Call the service.
The following example shows how to obtain an access token in C++:
#include <iostream> #include "Token.h" using std::cout; using std::endl; using namespace AlibabaNlsCommon; // Obtain the access token. int getTokenId(const char* keySecret, const char* keyId) { NlsToken nlsTokenRequest; /* Set the AccessKey Secret of your Alibaba Cloud account. */ nlsTokenRequest.setKeySecret(getenv("ALIYUN_AK_SECRET")); /* Set the AccessKey ID of your Alibaba Cloud account. */ nlsTokenRequest.setAccessKeyId(getenv("ALIYUN_AK_ID")); /* Obtain the token. The method returns 0 on success and -1 on failure. */ if (-1 == nlsTokenRequest.applyNlsToken()) { cout << "Failed: " << nlsTokenRequest.getErrorMsg() << endl; /* Get the error message. */ return -1; } else { cout << "TokenId: " << nlsTokenRequest.getToken() << endl; /* Get the token. */ cout << "TokenId expireTime: " << nlsTokenRequest.getExpireTime() << endl; /* Get the Unix timestamp (in seconds) for the token's expiration. */ return 0; } }
Obtain a token with the Alibaba Cloud public SDK
When using the Alibaba Cloud public SDK to obtain a token, we recommend making API calls in the RPC style. A CommonRequest in the RPC style requires the following parameters:
Parameter | Value | Description |
domain | nls-meta.cn-shanghai.aliyuncs.com | The product's fixed access domain name. |
region_id | cn-shanghai | The service's fixed region ID. |
action | CreateToken | The API's fixed name. |
version | 2019-02-28 | The API's fixed version. |
A successful call returns the following response:
{
"NlsRequestId": "aed8c1af075347819118ff6bf811****",
"RequestId": "0989F63E-5069-4AB0-822B-5BD2D953****",
"Token": {
"ExpireTime": 1527592757,
"Id": "124fc7526f434b8c8198d6196b0a****",
"UserId": "12345678****"
}
}Idis the allocated access token. You can use this token until it expires. The token can be used concurrently on different machines, processes, or applications.ExpireTimeis a Unix timestamp (in seconds) indicating the token's expiration. For example,1527592757corresponds to 2018-05-29 19:19:17 (UTC+8). The token is valid until this time. After the token expires, you must obtain a new one.
Example (Java)
Add Java dependencies.
Add the Alibaba Cloud SDK for Java core library (version 3.7.1) 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.83</version> </dependency>Call the service.
The following example shows 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 { // Region ID private static final String REGIONID = "cn-shanghai"; // Access domain name for the token service private static final String DOMAIN = "nls-meta.cn-shanghai.aliyuncs.com"; // API version private static final String API_VERSION = "2019-02-28"; // API name private static final String REQUEST_ACTION = "CreateToken"; // 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 { String accessKeyId = System.getenv().get("ALIYUN_AK_ID"); String accessKeySecret = System.getenv().get("ALIYUN_AK_SECRET"); // Create and initialize a DefaultAcsClient instance. 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 + ", ExpireTime (in seconds): " + expireTime); // Convert the 10-digit timestamp to UTC+8. String expireDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(expireTime * 1000)); System.out.println("Token expiration time (UTC+8):" + expireDate); } else { System.out.println("Failed to obtain the token!"); } } }
Example (Python)
Use pip to install the SDK.
Run the following command to install the Python SDK (version 2.15.1) by using pip.
pip install aliyun-python-sdk-core==2.15.1 # Install the core library of the Alibaba Cloud SDK.Call the service.
The following code provides an example:
#! /usr/bin/env python # coding=utf-8 import os import time import json from aliyunsdkcore.client import AcsClient from aliyunsdkcore.request import CommonRequest # Create an AcsClient instance. client = AcsClient( os.getenv('ALIYUN_AK_ID'), os.getenv('ALIYUN_AK_SECRET'), "cn-shanghai" ) # Create a 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') try: response = client.do_action_with_exception(request) print(response) jss = json.loads(response) if 'Token' in jss and 'Id' in jss['Token']: token = jss['Token']['Id'] expireTime = jss['Token']['ExpireTime'] print("token = " + token) print("expireTime = " + str(expireTime)) except Exception as e: print(e)
Example (Go)
Before you start, install alibaba-cloud-sdk-go. For more information, see Installation.
The following code provides an example:
package main
import (
"fmt"
"os"
"encoding/json"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/credentials"
)
type TokenResult struct {
ErrMsg string
Token struct {
UserId string
Id string
ExpireTime int64
}
}
func main() {
config := sdk.NewConfig()
credential := credentials.NewAccessKeyCredential(os.Getenv("ALIYUN_AK_ID"), os.Getenv("ALIYUN_AK_SECRET"))
client, err := sdk.NewClientWithOptions("cn-shanghai", config, credential)
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())
var tr TokenResult
err = json.Unmarshal([]byte(response.GetHttpContentString()), &tr)
if err == nil {
fmt.Println(tr.Token.Id)
fmt.Println(tr.Token.ExpireTime)
} else {
fmt.Println(err)
}
}Example (PHP)
Make sure that your environment uses PHP 7.2 or later. For information about how to install the PHP SDK, see Install Alibaba Cloud SDK for PHP .
Create a global client.
Create an API request and set the parameters.
Send the request and process the response or exception.
The following code provides an example of how to obtain an access token in PHP:
<?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 AccessKey Secret of an Alibaba Cloud RAM account for authentication.
*/
AlibabaCloud::accessKeyClient(
getenv('ALIYUN_AK_ID'),
getenv('ALIYUN_AK_SECRET'))
->regionId("cn-shanghai")
->asDefaultClient();
try {
$response = AlibabaCloud::nlsCloudMeta()
->v20180518()
->createToken()
->request();
print $response . "\n";
$token = $response["Token"];
if ($token != NULL) {
print "Token obtained successfully:\n";
print_r($token);
print "The obtained token is: " . $token["Id"] ."\n";
date_default_timezone_set('Asia/Shanghai');
print "The token expires at: " . $token["ExpireTime"] . "\n";
}
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());
}The preceding code provides an example based on the new version of the Alibaba Cloud SDK for PHP. For more information, see Alibaba Cloud SDK for PHP. If you have integrated the earlier version of the Alibaba Cloud SDK for PHP, see aliyun-openapi-php-sdk. You can continue to use it or update to the new SDK.
Example (Node.js)
Install the Node.js SDK.
We recommend that you use npm to install the Node.js dependency modules. All official Alibaba Cloud Node.js SDKs are under @alicloud.
Assume that the Node.js SDK is downloaded to the
/path/to/aliyun-openapi-Node.js-sdkdirectory. When you develop based on the core SDK library, run the following command to install the @alicloud/pop-core module.The
--saveflag saves the module as a dependency in the application's package.json file.npm install @alicloud/pop-core --saveNoteYou can also download the SDK from GitHub. For more information, see Download the SDK from GitHub.
Call the service.
The following code provides an example:
var RPCClient = require('@alicloud/pop-core').RPCClient; var client = new RPCClient({ accessKeyId: process.env.ALIYUN_AK_ID, accessKeySecret: process.env.ALIYUN_AK_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) console.log("token = " + result.Token.Id) console.log("expireTime = " + result.Token.ExpireTime) });
FAQ
You may encounter errors when obtaining a token. Use this procedure for general troubleshooting:
Use the error code and message to find solutions in the official Alibaba Cloud error code table. For example, if you call the service to obtain a token using a non-existent AccessKey ID, the following result may be returned:
{ "RequestId":"F5805076-38C5-5093-B5BD-9176ECD9CBBD", "Message":"Specified access key is not found.", "Recommend":"https://next.api.aliyun.com/troubleshoot?q=InvalidAccessKeyId.NotFound&product=nls-cloud-meta", "HostId":"nls-meta.cn-shanghai.aliyuncs.com", "Code":"InvalidAccessKeyId.NotFound" }Search for keywords from the error message, such as InvalidAccessKeyId.NotFound and Specified access key is not found, in the error code table to find the details of the error code. The HTTP status code for this error is
404. To resolve this issue, check whether a valid AccessKey ID is passed in the call.You can also find a solution by entering the error message on the Alibaba Cloud OpenAPI Diagnostic Center page.
Take
InvalidAccessKeyId.NotFoundas an example. The diagnosis is a credential error. This error occurs because the API rejects the request due to an invalid or disabled client credential. To resolve this issue, check your credential for any spaces. Log on to the AccessKey Management page in the Alibaba Cloud console at https://usercenter.console.aliyun.com/#/manage/ak. Confirm that the AccessKey ID exists and is enabled. If the AccessKey ID is disabled, enable it. If it does not exist, create a new one.
"Not supported proxy scheme" error
If you encounter the "Not supported proxy scheme" error, check your proxy configuration. For example, you can try to modify or delete the http_proxy and https_proxy environment variables and then retry the operation. If you have configured a proxy elsewhere, make sure that the proxy address and port are correct and that the proxy server is available.
Related documentation
You can also obtain a token using the following methods: