使用STS Token调用API

内容检测API支持通过扮演RAM角色的临时身份凭证(STS Token)的方式进行调用。使用STS Token调用内容检测API之前,您需要先调用AssumeRole接口,获取扮演RAM角色的STS Token。本文介绍如何获取STS Token和如何通过Token调用内容安全API

说明

STS Token方式调用可以保护账号AccessKey信息,相比AccessKey方式更具有隐私性。

使用限制

只支持使用RAM用户(子账号)或RAM角色调用,不支持使用阿里云账号(主账号)调用。

前提条件

已为RAM用户或RAM角色授予STS的管理权限(AliyunSTSAssumeRoleAccess)。具体操作,请参见为RAM用户授权为RAM角色授权

步骤一:获取STS Token

关于如何获取STS Token,请参见AssumeRole - 获取扮演角色的临时身份凭证

获取STS Token代码示例

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


# 注意:此处实例化的client尽可能重复使用,提升检测性能。避免重复建立连接。
# 常见获取环境变量方式:
# 获取RAM用户AccessKey ID:os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
# 获取RAM用户AccessKey Secret:os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
client = AcsClient("建议从环境变量中获取RAM用户AccessKey ID", "建议从环境变量中获取RAM用户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')  # https | http
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'))

正常返回示例

{
    "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"
    }
}
说明

上面返回示例中Credentials字段包含了调用内容安全API所需的参数,其中Expiration为Token到期失效时间(UTC时间),需要在有效期内使用。

步骤二:通过STS Token调用内容安全API

以下以文本审核1.0版、增强版为例,为您展示通过STS Token调用内容安全API的代码示例。

文本审核1.0版接口示例

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.profile import region_provider
from aliyunsdkcore.auth.credentials import StsTokenCredential// 该方法的入参为STS Token获取的参数。
from aliyunsdkgreen.request.v20180509 import TextScanRequest
import uuid
import json


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')
# 每次请求时需要新建request,请勿复用request对象。
request = TextScanRequest.TextScanRequest()
request.set_accept_format('JSON')
task1 = {"dataId": str(uuid.uuid1()),
         "content": "textContentToBeModerated",
         }
# 文本反垃圾检测场景的场景参数是antispam。
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 200 == result["code"]:
    taskResults = result["data"]
    for taskResult in taskResults:
        if (200 == taskResult["code"]):
            sceneResults = taskResult["results"]
            for sceneResult in sceneResults:
                scene = sceneResult["scene"]
                suggestion = sceneResult["suggestion"]
                # 根据scene和suggestion设置后续操作。

文本审核增强版接口示例

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


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')  # https | http
request.set_domain('green-cip.cn-shanghai.aliyuncs.com')
request.set_version('2022-03-02')
request.set_action_name('TextModeration')

# 审核服务类型,包括:
# nickname_detection:用户昵称
# chat_detection:聊天互动
# comment_detection:动态评论
request.add_query_param("Service", "nickname_detection")
request.add_query_param("ServiceParameters", {'content': '测试文本', 'accountId': "user123"})

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

如何解决报错:You are not authorized to do this action. You should be authorized by RAM?

未对RAM用户或RAM角色授予STS的管理权限,会显示该错误信息。造成该问题的原因和解决方法如下: