语音交互服务 SIS-认证鉴权:Token认证

时间:2024-09-25 09:15:51

Token认证

Token的有效期为24小时,需要使用同一个Token鉴权时,可以缓存起来,避免频繁调用。

Token在计算机系统中代表令牌(临时)的意思,拥有Token就代表拥有某种权限。Token认证就是在调用API的时候将Token加到请求消息头,从而通过身份认证,获得操作API的权限。

代码中加粗的斜体字段需要根据实际值填写usernamedomainname、project name可登录控制台“我的凭证”页面获取。password为用户密码。

  • 伪码
    POST https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens
    Content-Type: application/json 
     
    { 
        "auth": { 
            "identity": { 
                "methods": [ 
                    "password" 
                ], 
                "password": { 
                    "user": { 
                        "name": "username", 
                        "password": "********", 
                        "domain": { 
                            "name": "domainname" 
                        } 
                    } 
                } 
            }, 
            "scope": { 
                "project": { 
                    "name": "cn-north-4" 
                } 
            } 
        } 
    }
  • Python
    import requests
    import json
    
    url = "https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens"
    payload = json.dumps({
      "auth": {
        "identity": {
          "methods": [
            "password"
          ],
          "password": {
            "user": {
              "name": "username",
              "password": "********",
              "domain": {
                "name": "domainname"
              }
            }
          }
        },
        "scope": {
          "project": {
            "name": "cn-north-4"
          }
        }
      }
    })
    headers = {
      'Content-Type': 'application/json'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload)
    
    print(response.headers["X-Subject-Token"])
图1 获取Token 示例

获取Token后,再调用其他接口时,您需要在请求消息头中添加“X-Auth-Token”的值。例如Token值为“ABCDEFJ....”,则调用接口时将“X-Auth-Token: ABCDEFJ....”加到请求消息头即可,如下所示。

Content-Type: application/json
X-Auth-Token: ABCDEFJ....
support.huaweicloud.com/api-sis/sis_03_0058.html