Skip to content

Instantly share code, notes, and snippets.

@brandonmwest
Last active January 16, 2024 15:52
Star You must be signed in to star a gist
Save brandonmwest/a2632d0a65088a20c00a to your computer and use it in GitHub Desktop.
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);
@pcmccull
Copy link

pcmccull commented Jul 3, 2018

Ruby should use the strict_encode64 method otherwise using long usernames or passwords will end up with a line break:
$header = 'Authorization: Basic ' + Base64.strict_encode64( username + ':' + password ).chomp

@acyuta
Copy link

acyuta commented Jul 17, 2018

Java + Spring Framework:

String authString = "Authorization: Basic " +
                Base64Utils.encodeToString(
                        String.format("%s:%s", username,password)
                                .getBytes()
                );

Vanilla Java:

String authString = "Authorization: Basic " +
                Base64.getEncoder().encodeToString(
                        String.format("%s:%s", username,password)
                                .getBytes()
                );

@KyleWMiller
Copy link

Node Aug '18 update:

const username = 'test',
    password = 'supersecret01!',
    auth = (Buffer.from(`${username}:${password}`).toString('base64')

@savo92
Copy link

savo92 commented Sep 6, 2018

Python3 update: encodestring is deprecated (DeprecationWarning: encodestring() is a deprecated alias since 3.1, use encodebytes()).
I think you should change the snippet to be:

base64string = base64.encodebytes(('%s:%s' % (username, password)).encode('utf8')).decode('utf8').replace('\n', '')
header = ("Authorization: Basic %s" % base64string)   

or, if you prefer a bytes-like str:

base64string = base64.encodebytes(('%s:%s' % (username, password)).encode('utf8')).replace(b'\n', b'')

@frank-carnovale
Copy link

Perl:
'Authorization: Basic ' . MIME::Base64::encode("$username:$password")

@theory
Copy link

theory commented Aug 2, 2019

Better Perl (avoid line breaks):

'Authorization: Basic ' . MIME::Base64::encode("$username:$password", '')

@epDugas
Copy link

epDugas commented Aug 12, 2019

https://gist.github.com/brandonmwest/a2632d0a65088a20c00a#gistcomment-2345632

PowerShell

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

This in incorrect, the enclosing double quote should be after {1}, not $password.

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

@silvioprog
Copy link

In Free Pascal:

uses base64;

header := EncodeStringBase64(Concat(username, ':', password));

@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

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

@salluvada
Copy link

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

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

@helloimalemur
Copy link

helloimalemur commented Jan 22, 2023

in Rust;

use http_auth_basic::Credentials;

let credentials = Credentials::new("username", "password").as_http_header();

assert_eq!(String::from("Basic dXNlcm5hbWU6cGFzc3dvcmQ="), credentials);

@leandroh
Copy link

In Elixir:

username = "username"
password = "password"

"#{username}:#{password}"
|> Base.encode64()

@AndrewElz
Copy link

In kotlin:

val username = "username"
val password = "password
val userpass = username + ":" + password
val encodedAuth = encodeToString(userpass.toByteArray(), NO_WRAP)
val authHeaderValue = "Basic " + encodedAuth
httpURLConnection.setRequestProperty("Authorization", authHeaderValue)

@ilanoh
Copy link

ilanoh commented May 23, 2023

In Salesforce APEX

HttpRequest request = new HttpRequest();
String username = 'test';
String password = 'test';

String accessToken = EncodingUtil.base64Encode(Blob.valueOf(username + ':' + password));
request.setHeader('Authorization', 'Basic ' + accessToken);

@holgerdewall
Copy link

holgerdewall commented Aug 8, 2023

In oracle pl/sql

set serveroutput on;
DECLARE
v_str VARCHAR2(1000);
BEGIN
--Create encoded value
v_str := utl_encode.text_encode('Testuser:verySecret','WE8ISO8859P1', UTL_ENCODE.BASE64);
dbms_output.put_line(v_str);
--Decode the value..
v_str := utl_encode.text_decode(v_str,'WE8ISO8859P1', UTL_ENCODE.BASE64);
dbms_output.put_line(v_str);
END;
/

or

select utl_raw.cast_to_varchar2(utl_encode.base64_encode(utl_raw.cast_to_raw('Testuser:verySecret')))
  from dual;
/

@suaterken-ua
Copy link

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

+1

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