Deno で Basic 認証を動かしたい

Dec 9th, 2022 typescript deno

状況

Http サーバを動かすコード

server.ts を作成し,下記のコードを書く.ドキュメントそのまま.

参考:https://deno.land/manual@v1.28.3/examples/http_server

// server.ts

import { serve } from "https://deno.land/std@0.167.0/http/server.ts";

const port = 8080;

const handler = (request: Request): Response => {

  const body = `Your user-agent is:\n\n${
    request.headers.get("user-agent") ?? "Unknown"
  }`;

  return new Response(body, { status: 200 });
};

console.log(`HTTP webserver running. Access it at: http://localhost:8080/`);
await serve(handler, { port });

Basic 認証を追加

ユーザ名とパスワードを用意しておく(実際は環境変数に設定して読み込むなど).

// server.ts

import { serve } from "https://deno.land/std@0.167.0/http/server.ts";

const port = 8080;

const handler = (request: Request): Response => {

  const user = "admin";
  const password = "password";

  // 🔽ここで認証が動く
  if (
    request.headers.get("Authorization") !== `Basic ${btoa(`${user}:${password}`)}`
  ) {
    const headers = new Headers({
      "WWW-Authenticate": 'Basic realm="Fake Realm"',
    });
    return new Response("Unauthorized", { status: 401, headers });
  }

  const body = `Your user-agent is:\n\n${
    request.headers.get("user-agent") ?? "Unknown"
  }`;

  return new Response(body, { status: 200 });
};

console.log(`HTTP webserver running. Access it at: http://localhost:8080/`);
await serve(handler, { port });

まとめ

意外と情報がなかったので困ったが,毎回同じなので流用すればOK.

以上だ( `・ω・)b