Basic Authentication Code Samples

Basic Authentication Code Samples

Here we list code samples for generating the authentication header value for the Basic-based schema in some common programming languages. Some modifications to the included code may be required, depending on the user’s system.

Java

import java.util.Base64;
 
 
public class Main
{
    public static void main(String[]args)
    {
        if(args.length != 2) {
            System.out.println("Usage: \"java -jar app <api-key> <secret-key>\"");
            return;
        }
        System.out.println("Authorization: " + getAuthenticationValue(args[0], args[1]));
    }
 
    private static String getAuthenticationValue(String apiKey, String secretKey)
    {
        String decodedValue = apiKey + ":" + secretKey;
        return "Basic " + Base64.getEncoder().encodeToString(decodedValue.getBytes());
    }
} 

Javascript

const API_KEY = '<api-key>';
const SECRET_KEY = '<secret-key>';
 
function getAuthenticationValue(apiKey, secretKey) {
  const decodedValue = apiKey + ":" + secretKey;
  return (
    'Basic ' +
    CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(decodedValue))
  );
}
 
console.log('Authentication: ' + getAuthenticationValue(API_KEY, SECRET_KEY)); 

C#

using System;
using System.Text;
 
 
namespace AuthenticationGeneration {
    class Program {
        public static void Main (string[] args) {
            if (args.Length != 2) {
                Console.WriteLine ("Usage: ./app <api-key> <secret-key>");
                return;
            }
 
            string API_KEY = args[0];
            string SECRET_KEY = args[1];
 
            Console.WriteLine ("Authentication: " + getAuthenticationValue (API_KEY, SECRET_KEY));
        }
 
        private static string getAuthenticationValue (string apiKey, string secretKey) {
            string decodedValue = apiKey + ":" + secretKey;
            Encoding encoding = new System.Text.UTF8Encoding ();
            return "Basic " + Convert.ToBase64String (encoding.GetBytes (decodedValue));
        }
    }
} 

PHP

<?php
 
 
$API_KEY = "<api-key>";
$SECRET_KEY = "<secret-key>";
 
function getAuthenticationValue($apiKey, $secretKey)
{
    $decodedValue = sprintf("%s:%s:", $apiKey, $secretKey);
    return "Basic " . base64_encode($decodedValue);
}
 
echo "\r\n";
echo "Authorization: " . getAuthenticationValue($API_KEY, $SECRET_KEY);
echo "\r\n"; 

PYTHON

import base64
 
 
API_KEY = '<api-key>'
SECRET_KEY = '<secret-key>'
 
def getAuthenticationValue(api_key, secret_key):
    decoded_value = api_key + ':' + secret_key
    return "Basic " + base64.b64encode(decoded_value.encode()).decode()
 
print()
print("Authorization: " + getAuthenticationValue(API_KEY, SECRET_KEY))