0.3.0 • Published 7 months ago

@andrew-pyle/basicauthheader v0.3.0

Weekly downloads
-
License
MIT
Repository
github
Last release
7 months ago

Basic Authorization Header

Construct a Basic Authorization string for the Authorization HTTP Header according to RFC 7617:

If the user agent wishes to send the user-id "Aladdin" and password "open sesame", it would use the following header field:

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

Installation

$ npm i @andrew-pyle/basicauthheader

Usage

Uses only standard JavaScript. Nothing Node.js-specific. Code provided as ES module only.

import { BasicAuth } from '@andrew-pyle/basicauthheader';
// CommonJS environments can probably use import('@andrew-pyle/basicauthheader')

const username = "Aladdin";
const password = "open sesame";

// Authorization Header String
const basicAuthString = new BasicAuth({ username, password }).toString(); 
// => "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="

// Directly Compatible with Web APIs: Headers, Request, fetch

const headers = new Headers({
  Authorization: new BasicAuth({ username, password })
});
// => Headers { authorization: "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" }

const request = new Request("https://example.com", {
  headers: {
    Authorization: new BasicAuth({ username, password })
  }
});
// => Response

const response = await fetch("https://example.com", {
  headers: {
    Authorization: new BasicAuth({ username, password })
  }
});
// => Response

// Exposes Credentials Property
const base64EncodedCredentials = new BasicAuth({ username, password }).credentials;
// => "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="

Base64 Encoding Strategy

Binary Encoding

Encodes strings into a binary Uint8Array as UTF-8. For a discussion of the need for encoding as UTF-8, see "The Unicode Problem" on MDN. If another text encoding is necessary, Pull Requests are welcome.

Base64 Conversion

The UTF-8 binary data in the Uint8Array (MDN) is then encoded as Base64 by Uint8Array.prototype.toBase64() (TC39), currently a stage 2 TC39 Proposal, falling back to btoa() if the environment doesn't support or polyfill Uint8Array.prototype.toBase64().

References

Prior Art

0.3.0

7 months ago

0.2.0

7 months ago