Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generating base64-encoded Authorization headers in a variety of languages
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", username, password))));
$header = "Authorization: Basic " . base64_encode($username . ':' . $password);
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
header = ("Authorization: Basic %s" % base64string)
$header = 'Authorization: Basic ' + Base64.encode64( username + ':' + password ).chomp
$.ajax
({
type: "GET",
url: "https://www.example.com",
dataType: 'json',
headers: {
"Authorization", btoa(username + ":" + password)
},
data: '{}',
success: function (){
...
}
});
var username = 'Test';
var password = '123';
var auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');
var header = {'Host': 'www.example.com', 'Authorization': auth};
var request = client.request('GET', '/', header);
@thienbao92
Copy link

thienbao92 commented May 11, 2020

in Golang:

client := &http.Client{}
request, err := http.NewRequest("POST","https://example.com", nil)

encodedCredential := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", CLIENT_ID, CLIENT_SECRET)))
request.Header.Add("Authorization", fmt.Sprintf("Basic %s", sEnc))

@AFlowOfCode
Copy link

AFlowOfCode commented May 16, 2020

Line 7 correction for jquery snippet: "Authorization", "Basic " + btoa(username + ":" + password)

@salluvada
Copy link

salluvada commented Jun 25, 2020

PowerShell

$username = 'test'
$password = 'password'
$base64AuthInfo = [convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1} -f $username, $password")))
$base64AuthInfo

The code above doesn't work. Below is the fix.

$username = 'test'
$password = 'password'
$base64AuthInfo = [convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("${username}:${password}")))
$base64AuthInfo

@dacr
Copy link

dacr commented Nov 9, 2020

Scala:

val bytesFromString = (username ++ ":" ++ password).getBytes("UTF-8")
val urlAuth = "Basic " ++ Base64.encode(bytesFromString)

The right scala implementation which run directly :

  val tokenBytes = s"$username:$password".getBytes("UTF-8")
  val tokenB64 = new String(java.util.Base64.getEncoder.encode(tokenBytes))
  val token = s"Basic $tokenB64"

@arnaudlacour
Copy link

arnaudlacour commented Feb 16, 2021

in JQuery, aren't we missing the 'Basic ' prefix?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment