鉴权配置

更新时间:2024-01-08 11:26:01

鉴权令牌的生成需用户配合开发。在控制台新建API后,在“基础信息-鉴权配置”中会看到该API鉴权所需使用的密钥,复制密钥,此密钥即鉴权算法中使用的加密密钥。按照提供的示例代码进行开发,在完成开发后,用户的每一次接口调用,都会带上动态鉴权令牌。在开启网宿密钥对鉴权后,将检测每个请求中鉴权令牌的正确性及有效性,只有在有效期内正确的令牌才可通过鉴权认证。

代码示例支持python、Java、Shell三种语言,完整代码示例如下:

一、配置:
1. 待鉴权api: http://your.domain/api
2. 签名算法:HmacSHA256
3. 密钥key:secret_key_str
4. 鉴权位置:HEADER,对应鉴权头部key:X_Sam_Auth
 
二、代码示例:
1.python
 
import binascii
import hmac
import hashlib
import time
import requests
 
secret_key_str = "secret_key_str"
tmp_timestamp = str(int(time.time()))
tmp_binary = hmac.new(secret_key_str.encode("utf-8"), tmp_timestamp.encode("utf-8"), digestmod=hashlib.sha256).digest()
// 加密后的byte数组转换为16进制字符串
tmp_hex = binascii.hexlify(tmp_binary).decode("utf-8")
 
headers = {
    "X-Date": tmp_timestamp,
    "X_Sam_Auth": tmp_hex
}
url = "http://your.domain/api"
resp = requests.get(url, headers=headers)
 
2.java
 
import cn.hutool.core.util.HexUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
 
public static void main(String[] args) throws Exception{
    String key = "secret_key_str";
    String timestamp = String.valueOf(System.currentTimeMillis()/1000);
    Mac sha256 = Mac.getInstance("HmacSHA256");
    SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"),"HmacSHA256");
    sha256.init(secretKeySpec);
    // 加密后的byte数组转换为16进制字符串
    String hex = HexUtil.encodeHexStr(sha256.doFinal(timestamp.getBytes("UTF-8")));
 
    String url = "http://your.domain/api";
    HttpResponse response = HttpUtil.createGet(url).header("X-Date", timestamp)
            .header("X_Sam_Auth", hex).execute();
}
 
3.shell
 
#!/bin/bash
secret_key_str="secret_key_str"
current=`date "+%Y-%m-%d %H:%M:%S"`
tmp_timestamp=`date -d "$current" +%s`
tmp_hex=`echo -en "$tmp_timestamp" | openssl dgst -sha256 -hmac $secret_key_str -binary | hexdump -ve '/1 "%02x"'`
curl -i --url "http://your.domain/api" \
-X "GET" \
-H "X-Date: $tmp_timestamp" \
-H "X_Sam_Auth: $tmp_hex"
本篇文档内容对您是否有帮助?
有帮助
我要反馈
提交成功!非常感谢您的反馈,我们会继续努力做到更好!