【问题标题】:Securely passing credentials for API authentication - Python 3安全地传递 API 身份验证的凭据 - Python 3
【发布时间】:2018-09-25 23:32:26
【问题描述】:

在 Python 3 中,我正在传递凭据以验证 API 调用,并且使用以下行完全可以正常工作:

userAndPass = b64encode(b"username:password").decode("ascii")

出于安全目的,我更愿意将凭据存储在外部(可能是 yaml 文件或其他地方),而不是对其进行硬编码。我试图替换用户名并用变量传递,但这似乎不起作用。我尝试将变量“凭据”放在括号中,还尝试在手边添加一个加号,但都不起作用。

我希望它按如下方式工作:

credentials = "username:password"
userAndPass = b64encode(b'credentails').decode("ascii")

欢迎提出任何建议!

【问题讨论】:

    标签: python api authentication python-requests restful-authentication


    【解决方案1】:

    在这种特殊情况下,您以错误的方式传递变量。

    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")

    【讨论】:

    • 谢谢,我也尝试过,但我面临的问题是将“用户名:密码”字符串作为变量。我认为我在问题中提供的代码示例可能会误导您。我会编辑它。
    • 尽管您的 EDIT 可能会起作用。说 credential = "username:pass",您编码的第二行 ('utf-8') 是否与 b"username:pass" 相同?
    • @Antonio 是和否。 b"string" 使用源代码的编码,"string".encode('utf-8') 使用提供的编码,所以你必须自己处理(它基本上意味着坚持一种编码并在读取和写入凭据时始终使用它)。
    【解决方案2】:

    requests 让你传递一个auth 元组,例如:

    username = 'Antonio'
    password = 'xx1234xx'
    user_pass = (username, password)
    
    res = requests.get('https://www.example.com/fetch', auth=user_pass)
    

    【讨论】:

    • 太好了,这正是我想要的。我没有意识到你可以将它作为一个元组传递!
    猜你喜欢
    • 2010-12-08
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    相关资源
    最近更新 更多