0

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!

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent, this is exactly what I was looking for. I didn't realise you could pass it in as a tuple!
2

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

3 Comments

Thanks, I have attempted this also, but the issue I was facing was to get the "username:password" string as a variable. I think the code example I provided in the question may have misled you. I'll edit it.
Although your EDIT may potentially work. Say credential = "username:pass", would the second line where you encode('utf-8') work the same as b"username:pass" ?
@Antonio yes and no. b"string" uses the encoding of the source code, "string".encode('utf-8') uses the provided encoding, so you have to handle it yourself (it basically means stick to one encoding and use it consistently when reading and writing the credentials).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.