Use an STS token to call the AI Guardrails API

更新时间:
复制 MD 格式

Call the AI Guardrails API using a Security Token Service (STS) token to assume a Resource Access Management (RAM) role. STS tokens are temporary credentials with a configurable expiration time, reducing the risk of credential exposure compared to permanent AccessKey pairs.

When to use an STS token

Use STS tokens instead of permanent AccessKey pairs when:

  • Calling the API from a client-side application (web, iOS, or Android) where embedding a permanent AccessKey pair would expose it to end users.

  • Granting third-party services or components limited, time-bound access to the AI Guardrails API without sharing your primary credentials.

  • Scoping permissions to only the operations required, rather than granting full account access.

Limitations

Only a RAM user or RAM role can call the AssumeRole operation. An Alibaba Cloud account cannot call this operation directly.

Prerequisites

Before you begin, make sure you have:

Step 1: Get an STS token

Call the AssumeRole operation to exchange your RAM user credentials for a temporary STS token. For the full API reference, see AssumeRole.

Reuse the AcsClient instance across requests. Creating a new client for every call adds unnecessary latency.

The following Python example uses the aliyunsdkcore library:

import os
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest

# Initialize the client with your RAM user credentials from environment variables.
client = AcsClient(
    os.environ["ALIBABA_CLOUD_ACCESS_KEY_ID"],
    os.environ["ALIBABA_CLOUD_ACCESS_KEY_SECRET"],
    "cn-shanghai"
)

request = CommonRequest()
request.set_accept_format("json")
request.set_domain("sts.aliyuncs.com")
request.set_method("POST")
request.set_protocol_type("https")
request.set_version("2015-04-01")
request.set_action_name("AssumeRole")
request.add_query_param("RoleArn", "acs:ram::174*************:role/ali**")
request.add_query_param("RoleSessionName", "alink")

response = client.do_action_with_exception(request)
print(str(response, encoding="utf-8"))

A successful response looks like this:

{
    "RequestId": "1*******-1111-5548-1111-6011111111D0",
    "AssumedRoleUser": {
        "Arn": "acs:ram::17****************:role/alink/alink",
        "AssumedRoleId": "3***************3:alink"
    },
    "Credentials": {
        "SecurityToken": "CAIS6Q******************wFnzm6aq/om6e49",
        "AccessKeyId": "STS.NTu***************hh",
        "AccessKeySecret": "FNQXp********************KCaZmpnA8fuyL",
        "Expiration": "2022-12-13T04:43:09Z"
    }
}

The Credentials object contains the three values you pass to the AI Guardrails API in Step 2. The token expires at the UTC time shown in Expiration — it is invalid after that time.

Response fieldUsed as
Credentials.AccessKeyIdFirst parameter of StsTokenCredential
Credentials.AccessKeySecretSecond parameter of StsTokenCredential
Credentials.SecurityTokenThird parameter of StsTokenCredential

Step 2: Call the AI Guardrails API with the STS token

Pass the three credential values from the Credentials object into StsTokenCredential, then use the resulting client to call the API.

Text Moderation 1.0

import uuid
import json
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.profile import region_provider
from aliyunsdkcore.auth.credentials import StsTokenCredential
from aliyunsdkgreen.request.v20180509 import TextScanRequest

# Use the three fields from the Credentials object in Step 1.
sts_token_credential = StsTokenCredential(
    "Credentials_AccessKeyId",      # Credentials.AccessKeyId
    "Credentials_AccessKeySecret",  # Credentials.AccessKeySecret
    "Credentials_SecurityToken"     # Credentials.SecurityToken
)
acs_client = AcsClient(region_id="cn-shanghai", credential=sts_token_credential)

region_provider.modify_point("Green", "cn-shanghai", "green.cn-shanghai.aliyuncs.com")

# Create a new request object for each call — request objects cannot be reused.
request = TextScanRequest.TextScanRequest()
request.set_accept_format("JSON")
task1 = {
    "dataId": str(uuid.uuid1()),
    "content": "textContentToBeModerated",
}
request.set_content(
    bytearray(json.dumps({"tasks": [task1], "scenes": ["antispam"]}), "utf-8")
)

response = acs_client.do_action_with_exception(request)
result = json.loads(response)

if result["code"] == 200:
    for task_result in result["data"]:
        if task_result["code"] == 200:
            for scene_result in task_result["results"]:
                scene = scene_result["scene"]
                suggestion = scene_result["suggestion"]
                # Handle the result based on scene and suggestion values.

Text Moderation 2.0

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.auth.credentials import StsTokenCredential
from aliyunsdkcore.request import CommonRequest

# Use the three fields from the Credentials object in Step 1.
sts_token_credential = StsTokenCredential(
    "Credentials_AccessKeyId",      # Credentials.AccessKeyId
    "Credentials_AccessKeySecret",  # Credentials.AccessKeySecret
    "Credentials_SecurityToken"     # Credentials.SecurityToken
)
client = AcsClient(region_id="cn-shanghai", credential=sts_token_credential)

request = CommonRequest()
request.set_accept_format("json")
request.set_method("POST")
request.set_protocol_type("https")
request.set_domain("green-cip.cn-shanghai.aliyuncs.com")
request.set_version("2022-03-02")
request.set_action_name("TextModeration")

# Supported Service values:
# - nickname_detection: user nicknames
# - chat_detection:     chat messages
# - comment_detection:  comments
request.add_query_param("Service", "nickname_detection")
request.add_query_param("ServiceParameters", {"content": "Test text", "accountId": "user123"})

response = client.do_action_with_exception(request)
print(str(response, encoding="utf-8"))

Troubleshooting

"You are not authorized to do this action. You should be authorized by RAM"

This error means the RAM user or RAM role lacks permission to call AssumeRole. There are two common causes:

No STS policy attached — Attach the AliyunSTSAssumeRoleAccess system policy (or a custom policy with equivalent permissions) to the RAM user or RAM role. See Grant permissions to the RAM user and How do I restrict a specific RAM user from assuming a specific RAM role?.

Requester not listed as a trusted entity — The RAM role's trust policy controls who can assume it. If the requester is not listed, update the trust policy to include them. See Modify a RAM role's trust policy.