Obtain a token using an SDK
Obtain tokens on a server to keep long-term AccessKey credentials out of mobile applications. The SDK signs requests. The application must store tokens, check their expiration times, and obtain replacements before they expire.
Background
Choose the method that fits the SDK used in the project. Only one of the two SDKs is needed.
|
Method |
When to use |
|
NLS SDK |
Use the token request class if the corresponding SDK is already integrated. |
|
Alibaba Cloud common SDK |
Call |
Configure credentials
An account with Intelligent Speech Interaction activated and an AccessKey pair with the required permissions are needed. For service activation and credential setup, see Start here.
Token requests use an AccessKey pair, not a Model Studio API key. Set the credentials in the environment of the process that runs the example: ALIYUN_AK_ID for the AccessKey ID and ALIYUN_AK_SECRET for the AccessKey secret.
Keep AccessKey credentials in a trusted server environment, not in source code or mobile applications. Before calling a speech service, a mobile application requests a token from the application server. The examples print only the result and expiration time, not the token. Do not log AccessKey credentials, tokens, or complete signed requests.
Obtain a token with an NLS SDK
Java
Add the Maven dependencies. The example uses nls-sdk-common 2.1.6. JAXB API is also required to run the example on JDK 21.
<dependency>
<groupId>com.alibaba.nls</groupId>
<artifactId>nls-sdk-common</artifactId>
<version>2.1.6</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
Call apply() to send the request. Then call getToken() and getExpireTime() to retrieve the token and expiration time. This request class does not automatically refresh tokens on a schedule.
import com.alibaba.nls.client.AccessToken;
public class NlsTokenDemo {
public static void main(String[] args) throws Exception {
AccessToken request = new AccessToken(
System.getenv("ALIYUN_AK_ID"),
System.getenv("ALIYUN_AK_SECRET"),
"nls-meta.cn-shanghai.aliyuncs.com",
"cn-shanghai", "2019-02-28");
request.apply();
String token = request.getToken();
long expireTime = request.getExpireTime();
System.out.println("Token acquired: " + (token != null && !token.isEmpty()));
System.out.println("ExpireTime (Unix seconds): " + expireTime);
}
}
C++
Download the C++ Token SDK and extract the package. It contains headers, examples, and libraries for Linux and Windows. Environment requirements:
Linux: Glibc 2.5 or later and GCC 4 or GCC 5.
Windows: Visual Studio 2013 or Visual Studio 2015. Create a project and configure the library references.
Add the extracted include directory to the header search path and configure the SDK libraries and dependencies for the target platform. Extract the Linux libraries from lib/linux.tar.gz. The Linux example links against alibabacloud-idst-common, jsoncpp, ssl, crypto, curl, and uuid. For example, compile with the following command and replace path/to/NlsCommonSdk with the actual extraction path:
g++ -D_GLIBCXX_USE_CXX11_ABI=0 tokenDemo.cpp \
-I path/to/NlsCommonSdk/include \
-L path/to/NlsCommonSdk/lib/linux \
-lalibabacloud-idst-common -ljsoncpp -lssl -lcrypto -lcurl -luuid \
-o tokenDemo
At runtime, add path/to/NlsCommonSdk/lib/linux to LD_LIBRARY_PATH so that the shared libraries can be loaded.
The code reads AccessKey credentials from environment variables. No credentials are required as command-line arguments.
#include <cstdlib>
#include <iostream>
#include "Token.h"
int main() {
const char* accessKeyId = std::getenv("ALIYUN_AK_ID");
const char* accessKeySecret = std::getenv("ALIYUN_AK_SECRET");
if (!accessKeyId || !accessKeySecret) {
std::cerr << "Set ALIYUN_AK_ID and ALIYUN_AK_SECRET." << std::endl;
return 1;
}
AlibabaNlsCommon::NlsToken request;
request.setAccessKeyId(accessKeyId);
request.setKeySecret(accessKeySecret);
if (request.applyNlsToken() == -1) {
std::cerr << request.getErrorMsg() << std::endl;
return 1;
}
const char* token = request.getToken();
unsigned int expireTime = request.getExpireTime();
std::cout << "Token acquired: " << (token != NULL && token[0] != '\0') << std::endl;
std::cout << "ExpireTime (Unix seconds): " << expireTime << std::endl;
return 0;
}
Obtain a token with an Alibaba Cloud common SDK
RPC requests made with a common SDK use the following parameters. Use the endpoint, region, and API version together as listed; do not change just one of them.
|
Parameter |
Setting |
Description |
|
|
|
Token service endpoint. |
|
|
|
Request region. |
|
|
|
API operation. |
|
|
|
RPC API version. |
Java
Add the Maven dependencies. The example uses aliyun-java-sdk-core 3.7.1 and fastjson 1.2.83. JDK 21 also requires JAXB API 2.3.1.
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>3.7.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
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.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
public class CreateTokenDemo {
public static void main(String[] args) throws Exception {
DefaultProfile profile = DefaultProfile.getProfile(
"cn-shanghai", System.getenv("ALIYUN_AK_ID"),
System.getenv("ALIYUN_AK_SECRET"));
DefaultAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setDomain("nls-meta.cn-shanghai.aliyuncs.com");
request.setVersion("2019-02-28");
request.setAction("CreateToken");
request.setMethod(MethodType.POST);
request.setProtocol(ProtocolType.HTTPS);
CommonResponse response = client.getCommonResponse(request);
JSONObject result = JSON.parseObject(response.getData()).getJSONObject("Token");
String token = result.getString("Id");
long expireTime = result.getLongValue("ExpireTime");
System.out.println("Token acquired: " + (token != null && !token.isEmpty()));
System.out.println("ExpireTime (Unix seconds): " + expireTime);
}
}
Python
Install the dependency. The example uses aliyun-python-sdk-core 2.15.1.
pip install aliyun-python-sdk-core
import json
import os
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
client = AcsClient(
os.environ["ALIYUN_AK_ID"],
os.environ["ALIYUN_AK_SECRET"],
"cn-shanghai",
)
request = CommonRequest()
request.set_method("POST")
request.set_protocol_type("https")
request.set_domain("nls-meta.cn-shanghai.aliyuncs.com")
request.set_version("2019-02-28")
request.set_action_name("CreateToken")
result = json.loads(client.do_action_with_exception(request))
token = result["Token"]["Id"]
expire_time = result["Token"]["ExpireTime"]
print("Token acquired:", bool(token))
print("ExpireTime (Unix seconds):", expire_time)
Go
Install the dependency in a Go module. The example uses alibaba-cloud-sdk-go 1.63.107.
go get github.com/aliyun/alibaba-cloud-sdk-go/sdk
package main
import (
"encoding/json"
"fmt"
"os"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
)
func main() {
credential := credentials.NewAccessKeyCredential(
os.Getenv("ALIYUN_AK_ID"), os.Getenv("ALIYUN_AK_SECRET"))
client, err := sdk.NewClientWithOptions("cn-shanghai", sdk.NewConfig(), credential)
if err != nil {
panic(err)
}
request := requests.NewCommonRequest()
request.Scheme = "HTTPS"
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)
}
var result struct {
Token struct {
Id string
ExpireTime int64
}
}
if err := json.Unmarshal(response.GetHttpContentBytes(), &result); err != nil {
panic(err)
}
token := result.Token.Id
fmt.Println("Token acquired:", token != "")
fmt.Println("ExpireTime (Unix seconds):", result.Token.ExpireTime)
}
PHP
Use PHP 7.2 or later and install the dependency with Composer. The example uses alibabacloud/sdk 1.8.2345 and alibabacloud/client 1.5.32.
composer require alibabacloud/sdk
This example uses the SDK's ROA request wrapper with API version 2018-05-18 and request path /pop/2018-05-18/tokens. This version differs from the RPC API version. Do not mix parameters from the two request styles.
<?php
require __DIR__ . '/vendor/autoload.php';
use AlibabaCloud\Client\AlibabaCloud;
AlibabaCloud::accessKeyClient(
getenv('ALIYUN_AK_ID'), getenv('ALIYUN_AK_SECRET'))
->regionId('cn-shanghai')
->asDefaultClient();
$response = AlibabaCloud::nlsCloudMeta()
->v20180518()
->createToken()
->scheme('https')
->request();
$token = $response['Token']['Id'];
$expireTime = $response['Token']['ExpireTime'];
echo 'Token acquired: ' . (!empty($token) ? 'true' : 'false') . PHP_EOL;
echo 'ExpireTime (Unix seconds): ' . $expireTime . PHP_EOL;
Node.js
Install the dependency. The example uses @alicloud/pop-core 1.8.0.
npm install @alicloud/pop-core
const { RPCClient } = require('@alicloud/pop-core');
const client = new RPCClient({
accessKeyId: process.env.ALIYUN_AK_ID,
accessKeySecret: process.env.ALIYUN_AK_SECRET,
endpoint: 'https://nls-meta.cn-shanghai.aliyuncs.com',
apiVersion: '2019-02-28',
});
async function main() {
const result = await client.request('CreateToken', {}, { method: 'POST' });
const token = result.Token.Id;
const expireTime = result.Token.ExpireTime;
console.log('Token acquired:', Boolean(token));
console.log('ExpireTime (Unix seconds):', expireTime);
}
main().catch((error) => {
console.error('CreateToken failed:', error.code || error.name);
process.exitCode = 1;
});
Response and usage notes
After a common SDK request succeeds, read the following fields from the Token object in the response. The NLS SDK for Java returns these values through the corresponding methods.
|
Field |
Type |
Description |
|
|
String |
The token string for subsequent speech service requests. In the NLS SDK for Java, use |
|
|
Long |
The expiration time as a Unix timestamp in seconds. In the NLS SDK for Java, use |
Cache and reuse a token while it is valid instead of obtaining one before every speech service request. Use the returned
ExpireTimevalue to determine when the token expires. Obtain a replacement and update the cache before expiration. Do not substitute a fixed duration for the returned value.Multiple processes or applications in a trusted environment can use the same token. Obtain tokens from the endpoint configured in these examples. Do not interchange tokens issued by the Shanghai and Singapore endpoints.
Pass the
Idstring to the speech service, not the complete JSON response, AccessKey credentials, or another field. Pass the token in the location required by the speech API's authentication protocol.
FAQ
How do I troubleshoot a failed token request?
Use the error code returned by the SDK to identify the cause. An incorrect AccessKey pair is not the only cause of authentication errors.
|
Error code |
Troubleshooting |
|
|
Check that the AccessKey ID is correct, belongs to the intended identity, and contains no spaces introduced when copying it. |
|
|
Check that the AccessKey ID and AccessKey secret are a matching pair and that signed parameters have not been changed. Use a common SDK to construct requests instead of assembling signatures manually. |
|
|
Check that the requesting system's clock is synchronized with standard time. This error concerns the request timestamp, not the expiration of an issued token. |
|
|
Check the endpoint and API version, and distinguish RPC from ROA requests. The PHP request style must match its API version. |
What if a speech API reports an invalid token?
40000001 indicates an authentication error when calling a speech service. Check that the actual token string and all required authentication parameters are provided, the token has not expired, and its issuing endpoint matches the service configuration. The same error code can have multiple causes; check the full error message.
How do I resolve the "Not supported proxy scheme" error?
Check http_proxy, https_proxy, and any proxies configured in the application. Use a proxy protocol supported by the SDK and check the proxy address, port, and availability. If the network does not require a proxy, remove the proxy settings and retry.
Related topics
To obtain a token from the console for temporary testing, see Obtain a token in the console.
To construct signed requests directly, see Obtain a token using OpenAPI.