From 7ca33e81d29c0614ed9be26f1c483bdee6a20899 Mon Sep 17 00:00:00 2001 From: "yongyue.sl" Date: Mon, 14 Mar 2022 14:02:27 +0800 Subject: [PATCH] Support AK/SK authing --- nacos/client.py | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/nacos/client.py b/nacos/client.py index 815d111..e8d38c9 100644 --- a/nacos/client.py +++ b/nacos/client.py @@ -6,6 +6,7 @@ import json import platform import time +import hmac try: import ssl @@ -40,7 +41,7 @@ logger = logging.getLogger(__name__) DEBUG = False -VERSION = "0.1.6" +VERSION = "0.1.7" DEFAULT_GROUP_NAME = "DEFAULT_GROUP" DEFAULT_NAMESPACE = "" @@ -771,7 +772,33 @@ def _process_polling_result(self): watcher.last_md5 = md5 def _get_common_headers(self, params, data): - return {} + headers = {} + if self.auth_enabled: + ts = str(int(time.time() * 1000)) + ak, sk = self.ak, self.sk + + headers.update({ + "Spas-AccessKey": ak, + "timeStamp": ts, + }) + sign_str = "" + # in case tenant or group is null + if not params and not data: + return headers + + tenant = (params and params.get("tenant")) or (data and data.get("tenant")) + group = (params and params.get("group")) or (data and data.get("group")) + + if tenant: + sign_str = tenant + "+" + if group: + sign_str = sign_str + group + "+" + + if sign_str: + sign_str += ts + headers["Spas-Signature"] = base64.encodebytes( + hmac.new(sk.encode(), sign_str.encode(), digestmod=hashlib.sha1).digest()).decode().strip() + return headers def _build_metadata(self, metadata, params): if metadata: