1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Cloudflare Pagesで複数のパスに対してBasic認証

Posted at

事前準備

$ npm install wrangler --save-dev
$ mkdir app
$ touch app/index.html
$ mkdir functions
$ vim functions/_middleware.js
$ npx wrangler pages dev app

_middleware.js

functions/_middleware.js
const authSettings = [
  { path: "/protected2", username: "user2", password: "pass2" },
  { path: "/", username: "user1", password: "pass1" },
  // 必要に応じて追加
];

function isAuthorized(authHeader, validCredentials) {
  if (!authHeader || !authHeader.startsWith("Basic ")) {
    return false;
  }
  const [login, password] = atob(authHeader.split(" ")[1]).split(":");
  return validCredentials.some(cred => cred.username === login && cred.password === password);
}

export async function onRequest(context) {
  const { request } = context;
  const { pathname } = new URL(request.url);

  const matchedAuthSettings = authSettings.find(
    setting => pathname === setting.path || pathname.startsWith(setting.path)
  );

  if (matchedAuthSettings) {
    const authHeader = request.headers.get("Authorization");
    const isValid = isAuthorized(authHeader, [matchedAuthSettings]);

    if (!isValid) {
      return new Response("Unauthorized", {
        status: 401,
        headers: {
          "WWW-Authenticate": 'Basic realm="Restricted Area"'
        },
      });
    }
  }

  return await context.next();
}

確認

$ curl -I http://localhost:8788
HTTP/1.1 401 Unauthorized
$ curl -I -u user1:pass1 http://localhost:8788
HTTP/1.1 200 OK
$ curl -I -u user1:pass1 http://localhost:8788/protected2
HTTP/1.1 401 Unauthorized
$ curl -I -u user2:pass2 http://localhost:8788/protected2
HTTP/1.1 200 OK
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?