安全地传递用于 API 身份验证的凭据 - Python 3
Securely passing credentials for API authentication - Python 3
在 Python 3 中,我正在传递凭据以验证 API 调用,使用以下行它完全可以正常工作:
userAndPass = b64encode(b"username:password").decode("ascii")
出于安全目的,我更愿意做的是将凭据存储在外部(可能是 yaml 文件或其他地方),而不是对其进行硬编码。我试图替换用户名并传递变量,但这似乎不起作用。我试过将变量 'credentials' 放在方括号中,也试过事先添加一个加号,但都不起作用。
我希望它按如下方式工作:
credentials = "username:password"
userAndPass = b64encode(b'credentails').decode("ascii")
如有任何建议,我们将不胜感激!
requests
让你传递一个 auth
元组,例如:
username = 'Antonio'
password = 'xx1234xx'
user_pass = (username, password)
res = requests.get('https://www.example.com/fetch', auth=user_pass)
在这种特殊情况下,您以错误的方式传递了变量。
b64encode(b'credentails')
表示 编码字节数组 [c, r, e, d, e, n, t, i, a, l, s].
这样使用:
credentials = b"username:password"
userAndPass = b64encode(credentails).decode("ascii")
编辑:
如果您想以不同方式获取凭据:
credentials = somehow_get_credentials_as_string()
bytes_credentials = credentials.encode('utf-8') # or whatever the encoding is
userAndPass = b64encode(bytes_credentials).decode("ascii")
在 Python 3 中,我正在传递凭据以验证 API 调用,使用以下行它完全可以正常工作:
userAndPass = b64encode(b"username:password").decode("ascii")
出于安全目的,我更愿意做的是将凭据存储在外部(可能是 yaml 文件或其他地方),而不是对其进行硬编码。我试图替换用户名并传递变量,但这似乎不起作用。我试过将变量 'credentials' 放在方括号中,也试过事先添加一个加号,但都不起作用。
我希望它按如下方式工作:
credentials = "username:password"
userAndPass = b64encode(b'credentails').decode("ascii")
如有任何建议,我们将不胜感激!
requests
让你传递一个 auth
元组,例如:
username = 'Antonio'
password = 'xx1234xx'
user_pass = (username, password)
res = requests.get('https://www.example.com/fetch', auth=user_pass)
在这种特殊情况下,您以错误的方式传递了变量。
b64encode(b'credentails')
表示 编码字节数组 [c, r, e, d, e, n, t, i, a, l, s].
这样使用:
credentials = b"username:password"
userAndPass = b64encode(credentails).decode("ascii")
编辑:
如果您想以不同方式获取凭据:
credentials = somehow_get_credentials_as_string()
bytes_credentials = credentials.encode('utf-8') # or whatever the encoding is
userAndPass = b64encode(bytes_credentials).decode("ascii")