iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📑

Basic Authentication in Next.js

に公開
2023/03/26

What is Basic Authentication?

Overview

Looking at this title, many of you might be like, "Basic Authentication...?"
To be honest, I was also like ??????? 😇 lol
However, just by looking at this image, I think you'll go, "Oh! I've seen this before!"

image.png

This is Basic Authentication.
Basic Authentication is one of the methods for setting access restrictions on a website (an authentication system provided by HTTP functions) and is an easy way to apply limits.
A key feature is that you can apply restrictions to specific areas only.

How it Works

In Basic Authentication, when you enter a URL or click a link, the browser sends a request to the web server.
If Basic Authentication is configured, the web server notifies the browser that authentication is required.

Upon receiving the authentication notice from the web server, the browser displays an authentication dialog on the screen to request credentials. If the correct values are entered, authentication is successful, and access is granted.

In the Basic Authentication described above, two files, ".htaccess" and ".htpasswd", are at work.
Basic Authentication is set up simply by creating these two files in the folder you want to protect and writing specific code in each.
(In Next.js, writing code in a slightly special way will create similar files for you.)
The system works by verifying the ID and password specified in these files to allow or deny access.

If the login information matches, access is granted; if it doesn't match, access is denied, and the user cannot reach the files.
(Files: In the context of Next.js, the term "pages" might be easier to understand!)

This is how the Basic Authentication mechanism works 🙌

Pros and Cons

For Those in a Hurry

  • Pros
    • Relatively easier than other authentication methods
    • Once authenticated, login information is recorded
  • Cons
    • Authentication settings cannot span across different servers
    • Crawlers cannot circulate, so SEO measures cannot be taken
    • Low security level

Pros

  1. Relatively easier than other authentication methods
  2. Once authenticated, login information is recorded

Cons

  1. Authentication settings cannot span across different servers
  2. Crawlers cannot circulate, so SEO measures cannot be taken
  3. Low security level

The scope of Basic Authentication is limited to the directory where the ".htaccess" header file is located, so restrictions cannot be applied beyond that directory or across servers.

Additionally, areas where Basic Authentication is applied become inaccessible to "crawlers." Since crawlers cannot navigate these areas, information cannot be retrieved, and the pages won't appear in search results. Therefore, if you are aiming for SEO, it's better to avoid using Basic Authentication.

Regarding the low security level, Basic Authentication uses a character encoding called "Base64" when entering login information. Since Base64 communicates using only 64 types of characters (alphabets, numbers, and symbols), it is a communication method that is easily eavesdropped on.

Furthermore, if this simple "Base64" communication is sent over "HTTP," which transmits data in plain text, the risk of it being intercepted or bypassed increases. This is why Basic Authentication is said to have high vulnerability. (If using HTTPS, it is relatively better as it is encrypted with SSL/TLS.)

While there are such pros and cons, I adopted it this time because the use case was for internal use only at my internship site!

Implementation

To implement this, the following 2 points are necessary!

  1. API
  2. Middleware
  3. Environment variables

It's designed so you can implement it almost entirely with copy-paste! 🙌

API

First, write the following code for the API.

pages/api/auth.ts
import type { NextApiRequest, NextApiResponse } from 'next'

export default function handler(_: NextApiRequest, res: NextApiResponse) {
  res.setHeader('WWW-authenticate', 'Basic realm="Secure Area"')
  res.statusCode = 401
  res.end(`Basic Auth Required.`)
}

Explanation

res.setHeader('WWW-authenticate', 'Basic realm="Secure Area"') is the response header configuration.
If you are curious about the header content (WWW-authenticate), the following article might be helpful!

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/WWW-Authenticate

In res.statusCode = 401, we set the status code 401, which represents Unauthorized, indicating that authentication was not granted.

Finally, in res.end(`Basic Auth Required.`), you include the message to be displayed upon authentication failure.

Next, let's implement the middleware!

Middleware

Copy and paste the following code!

pages/_middleware.ts
import { NextRequest, NextResponse } from 'next/server'

export function middleware(req: NextRequest) {
  const url = req.nextUrl
  if (!url.pathname.startsWith('/')) return

  const basicAuth = req.headers.get('authorization')

  if (basicAuth) {
    const authValue = basicAuth.split(' ')[1]
    const [user, pwd] = Buffer.from(authValue, 'base64').toString().split(':')

    if (
      user === process.env.NEXT_PUBLIC_BASIC_AUTH_NAME &&
      pwd === process.env.NEXT_PUBLIC_BASIC_AUTH_PASSWORD
    ) {
      return NextResponse.next()
    }
  }
  url.pathname = '/api/auth'

  return NextResponse.rewrite(url)
}

Explanation

For if (!url.pathname.startsWith('/')) return, you should place the path of the page you want to protect where the / is. I've used an early return here because I don't want Basic Authentication to trigger on pages other than those intended.

const [user, pwd] = Buffer.from(authValue, 'base64').toString().split(':')
This part is significantly different from what often appears in search results. While many results show atob(), Buffer.from is the currently recommended syntax, so I used that instead!

if ( user === process.env.NEXT_PUBLIC_BASIC_AUTH_NAME && pwd === process.env.NEXT_PUBLIC_BASIC_AUTH_PASSWORD )
This is also slightly different from other articles found online, but since it's risky if passwords leak, I've defined them in .env and handled them as environment variables!

Setting Environment Variables

.env
NEXT_PUBLIC_BASIC_AUTH_NAME=username
NEXT_PUBLIC_BASIC_AUTH_PASSWORD=password

These are the environment variables we prepared earlier! In Next.js, they need to start with NEXT_PUBLIC_, so please keep that in mind!

Conclusion

How did you find Basic Authentication? It's incredibly handy for cases where you want to authenticate quickly and easily, provided it fits your use case! I hope you'll find appropriate use cases and implement the right authentication for your projects ✊ See you later 👋

References

https://www.cybersolutions.co.jp/blog/basic/#:~:text=Basic認証とはWeb,られる点が特徴です。

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/WWW-Authenticate

https://nextjs.org/docs/advanced-features/middleware

Discussion