When you let a user log in with their username and password, we say you are using Basic Authentication.
Using Basic Authentication
In Basic Authentication, you need to:
- Write the username and password in this format:
username:password. - Encode the
username:passwordstring into a base64 string. - Send the encoded string via an
Authorizationheader
Here’s a deeper explanation for steps 2 and 3.
Encoding the username and password
Encoding here means to convert the username:password string into the base64 format.
You can do this with a function called btoa (pronounced as B to A).
btoa stands for binary data to base64-encoded ascii. This function is available natively in both browsers and Node.
Creating the Authorization Header
For Basic authentication, the Authorization header must begin with Basic (with a space), followed by the encoded base64 string.
If you use Fetch, you need to write the entire header yourself.
// Using Fetchfetch('link-to-resource', { method: 'post, headers: { Authorization: `Basic ${encodedString}` }})The process is easier in zlFetch because it encodes the username:password string and writes the Authorization header for you.
All you have to do is pass in an auth option that contains the username and password properties.
zlFetch('link-to-resource', { auth: { username: 'username', password: '12345678', },})Basic authentication in the real world
Very few API services let you authenticate with Basic Authentication today.
Most services require other authentication methods (using tokens, API keys, or API secrets) for security purposes.
When I was writing this course, one of the remaining examples I could find was GitHub. Unfortunately, it has ceased its Basic Authentication service in November 2020.
As far as I know, (thankfully), we can use GitHub’s Basic Authentication service if you replace the password with a Personal Access Token.
Two things to note here:
- You can create a Personal access token by following the steps in this guide.
- You should try using Basic authentication with GitHub (if you can) — doing so will help prove to yourself that you got this lesson down flat.
You can use the following code to perform a Basic Authentication with GitHub. (Just make sure you switch out username and password with the appropriate values!).
zlFetch.post('https://api.github.com/user/repos', { auth: { username: 'username', password: 'personal-access-token', },})That’s all you need to know about Basic Authentication.
Next up, you’ll learn about Bearer Authentication — which is probably one of the most important ways to authenticate nowadays.
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson