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);
@luissquall

This comment has been minimized.

Copy link

@luissquall luissquall commented Jul 19, 2017

In Bash:

username='Test'
password='123'
credentials="$(echo -n "$username:$password" | base64)"
header="Authorization: Basic $credentials"
@Zacch

This comment has been minimized.

Copy link

@Zacch Zacch commented Nov 28, 2017

In Swift:

let username = "Test"
let password = "123"
let base64encoded = "\(username):\(password)".data(using: .isoLatin1)?.base64EncodedString() ?? ""
urlRequest.addValue("Basic \(base64encoded)", forHTTPHeaderField: "Authorization")

@yarres

This comment has been minimized.

Copy link

@yarres yarres commented Jan 11, 2018

In zsh:

 #!/bin/zsh
 read "username?Enter a username: "
 read "password?Enter a password: "
 credentials="$(echo -n "$username:$password" | base64)"
 header="Authorization: Basic $credentials"
 echo $header
@crshnbrn66

This comment has been minimized.

Copy link

@crshnbrn66 crshnbrn66 commented Feb 8, 2018

PowerShell

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

This comment has been minimized.

Copy link

@swyatt1120 swyatt1120 commented Mar 6, 2018

In SAS 9.4:

proc fcmp outlib=work.func.cipher;
function b64(string $) $;
length digest $32767;
digest=strip(put(string,$base64x32767.));
return(digest);
endsub;
quit;
options cmplib=(work.func);
data _null_;
string='myUserID:MyPasword';
b64=b64(string);
put b64;
run;

*** Encoded result will be in the log;

@toonsend

This comment has been minimized.

Copy link

@toonsend toonsend commented Mar 28, 2018

example.rb

$header = 'Authorization: Basic ' + Base64.encode64( username + ':' + password ).delete("\n")

@Hossman333

This comment has been minimized.

Copy link

@Hossman333 Hossman333 commented Jun 14, 2018

Scala:

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

This comment has been minimized.

Copy link

@graham-l graham-l commented Jun 19, 2018

Dart:

final auth = "Basic " + BASE64.encode(UTF8.encode("${username}:${password}"));

@pcmccull

This comment has been minimized.

Copy link

@pcmccull 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

This comment has been minimized.

Copy link

@acyuta 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

This comment has been minimized.

Copy link

@KyleWMiller KyleWMiller commented Aug 24, 2018

Node Aug '18 update:

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

@savo92

This comment has been minimized.

Copy link

@savo92 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

This comment has been minimized.

Copy link

@frank-carnovale frank-carnovale commented Jul 19, 2019

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

@theory

This comment has been minimized.

Copy link

@theory theory commented Aug 2, 2019

Better Perl (avoid line breaks):

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

This comment has been minimized.

Copy link

@thedugas thedugas 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

This comment has been minimized.

Copy link

@silvioprog silvioprog commented Aug 27, 2019

In Free Pascal:

uses base64;

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

This comment has been minimized.

Copy link

@thienbao92 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

This comment has been minimized.

Copy link

@AFlowOfCode AFlowOfCode commented May 16, 2020

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

@salluvada

This comment has been minimized.

Copy link

@salluvada 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

This comment has been minimized.

Copy link

@dacr 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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.