Antonio
Antonio

Reputation: 77

Securely passing credentials for API authentication - Python 3

In Python 3, I'm passing credentials to authenticate an API call and it works completely fine using the following line:

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

For security purposes, what I would prefer to do is store the credentials externally (possibly a yaml file or elsewhere) rather than hard code it. I attempted to replace the username and pass with variables, but that doesn't seem to work. I've tried placing the variable 'credentials' in brackets and also tried adding a plus before hand, neither work.

I would like it to work as follows:

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

Any suggestion is appreciated!

Upvotes: 0

Views: 6179

Answers (2)

Vojtech Kane
Vojtech Kane

Reputation: 559

In this particular case you are passing the variable in a wrong way.

b64encode(b'credentails') means encode the bytes array [c, r, e, d, e, n, t, i, a, l, s].

Use it like that:

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

EDIT:

In case you would like to obtain the credentials differently:

credentials = somehow_get_credentials_as_string() bytes_credentials = credentials.encode('utf-8') # or whatever the encoding is userAndPass = b64encode(bytes_credentials).decode("ascii")

Upvotes: 2

Sam Mason
Sam Mason

Reputation: 16164

requests lets you pass an auth tuple, for example:

username = 'Antonio'
password = 'xx1234xx'
user_pass = (username, password)

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

Upvotes: 2

Related Questions