Use an STS token to call the AI Guardrails API

更新时间:
复制 MD 格式

Using a Security Token Service (STS) token is more secure than using an AccessKey pair because the STS token expires automatically, which limits the exposure window if a credential is compromised. This guide shows you how to get an STS token by calling AssumeRole and how to use that token to call the AI Guardrails API.

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

Prerequisites

Before you begin, ensure that you have:

Step 1: Get an STS token

Call the AssumeRole operation to get temporary credentials. For the full API reference, see AssumeRole.

The following example uses the Alibaba Cloud Python SDK to call AssumeRole:

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

# Reuse the client instance across requests to improve performance
# and avoid repeated connection overhead.
client = AcsClient(
    os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_ID"),      # RAM user AccessKey ID
    os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),  # RAM user AccessKey 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:

{
    "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 need in the next step: AccessKeyId, AccessKeySecret, and SecurityToken.

The Expiration field is the UTC timestamp when the token expires. You must use the token before it expires.

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

Pass the three values from CredentialsAccessKeyId, AccessKeySecret, and SecurityToken — to StsTokenCredential, then use that credential to create your API client.

The following examples show this pattern for Text Moderation 1.0 and Text Moderation 2.0.

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 Credentials values from the AssumeRole response
sts_token_credential = StsTokenCredential(
    "Credentials_AccessKeyId",
    "Credentials_AccessKeySecret",
    "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 request — 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)
print(response)

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 Credentials values from the AssumeRole response
sts_token_credential = StsTokenCredential(
    "Credentials_AccessKeyId",
    "Credentials_AccessKeySecret",
    "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 types for the Service parameter:
# nickname_detection: user nicknames
# chat_detection:     chat messages
# comment_detection:  comments and reviews
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"))

FAQ

Why does the call fail with "You are not authorized to do this action. You should be authorized by RAM"?

This error means the RAM user or RAM role making the AssumeRole call lacks the required STS permissions. There are two common causes: