Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generating Basic Authentication header in a variety of languages
#!/usr/bin/bash
username=my-user
password=my-password
response=$( curl -s -u $username:$password http://my-wordpress/wp-json/wp/v2/posts/232 )
echo $response
#!/usr/bin/bash
username=my-user
password=my-password
authorization_header="Authorization: Basic "$( echo -n $username:$password | base64 )
echo $authorization_header
import java.util.Base64;
public class TestBase64 {
public static void main(String[] args) {
String username = "my-user";
String password = "my-password";
String authorizationHeader = "Authorization: Basic " +
Base64.getEncoder().encodeToString(
String.format( "%s:%s", username, password ).getBytes()
);
System.out.println( authorizationHeader );
}
}
var username = 'my-user';
var password = 'my-password';
var authorization_header = 'Authorization: Basic ' + new Buffer( username + ':' + password ).toString( 'base64' );
process.stdout.write( authorization_header );
#!/bin/perl
use LWP::UserAgent ();
use HTTP::Request::Common;
use strict;
my $username = 'my-user',
my $password = 'my-password';
my $ua = LWP::UserAgent->new();
my $req = HTTP::Request->new( 'GET', ( 'http://my-wordpress/wp-json/wp/v2/posts/232' ) );
$req->authorization_basic( $username, $password );
my $response = $ua->request( $req );
print $response->decoded_content;
#!/bin/perl
use MIME::Base64 ();
use strict;
my $username = 'my-user',
my $password = 'my-password';
my $authorization_header = 'Authorization: Basic ' . MIME::Base64::encode( $username . ':' . $password, '' );
print $authorization_header;
<?php
$username = 'my-user';
$password = 'my-password';
$cu = curl_init( 'http://my-wordpress/wp-json/wp/v2/posts/232' );
curl_setopt_array( $cu, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => $username . ':' . $password
) );
$response = curl_exec( $cu );
<?php
$username = 'my-user';
$password = 'my-password';
$response = wp_remote_request(
'http://my-wordpress/wp-json/wp/v2/posts/232',
array(
'method' => 'GET',
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( $username . ':' . $password )
),
)
);
echo wp_remote_retrieve_body( $response );
<?php
$username = 'my-user';
$password = 'my-password';
$authorization_header = 'Authorization: Basic ' . base64_encode( $username . ':' . $password );
echo $authorization_header;
import base64
username = 'my-user'
password = 'my-password'
authorization_header = ( "Authorization: Basic %s" % base64.encodestring( '%s:%s' % ( username, password ) ).replace( '\n', '' ) )
print authorization_header
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment