Python encodes Basic Auth using simple instances of the method


This blog post focuses on encoding your username and password into a string in the Python3 environment.

The code is as follows:

import base64
def get_basic_auth_str(username, password):
  temp_str = username + ':' + password
  #  into bytes string
  bytesString = temp_str.encode(encoding="utf-8")
  # base64  coding
  encodestr = base64.b64encode(bytesString)
  #  decoding
  decodestr = base64.b64decode(encodestr)

  return 'Basic ' + encodestr.decode()

Call sample:

print(get_basic_auth_str('admin', '123456'))

The output

Basic YWRtaW46MTIzNDU2

Thank you for reading, I hope to help you, thank you for your support of this site!