Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add withBasicAuth utility for authentication #826

Open
wants to merge 1 commit into
base: v1
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions docs/2.utils/98.advanced.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,3 +216,21 @@ eventHandler((event) => {
```

<!-- /automd -->

## Authentication

<!-- automd:jsdocs src="../../src/utils/auth.ts" -->

### `withBasicAuth(auth: { username, password }, handler)`

Protect an event handler with basic authentication

**Example:**

```ts
export default withBasicAuth({ username: 'test', password: 'abc123!' }, defineEventHandler(async (event) => {
return 'Hello, world!';
}));
```

<!-- /automd -->
49 changes: 49 additions & 0 deletions src/utils/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { EventHandler } from "../types";
import { eventHandler, type H3Event } from "../event";
import { getRequestHeaders } from "./request";
import { setResponseHeader, setResponseStatus } from "./response";

const authenticationFailed = (event: H3Event) => {
setResponseHeader(
event,
"WWW-Authenticate",
'Basic realm="Authentication required"',
);
setResponseStatus(event, 401);
return "Authentication required";
};

/**
* Protect an event handler with basic authentication
*
* @example
* export default withBasicAuth({ username: 'test', password: 'abc123!' }, defineEventHandler(async (event) => {
* return 'Hello, world!';
* }));
*
* @param auth The username and password to use for authentication.
* @param handler The event handler to wrap.
*/
export function withBasicAuth(
auth: { username: string; password: string } | string,
handler: EventHandler,
): EventHandler {
const authString =
typeof auth === "string" ? auth : `${auth.username}:${auth.password}`;
return eventHandler(async (event) => {
const headers = getRequestHeaders(event);

if (!headers.authorization) {
return authenticationFailed(event);
}

const b64auth = headers.authorization.split(" ")[1] || "";
const decodedAuthHeader = Buffer.from(b64auth, "base64").toString();

if (decodedAuthHeader !== authString) {
return authenticationFailed(event);
}

return await handler(event);
});
}
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from "./route";
export * from "./auth";
export * from "./body";
export * from "./cache";
export * from "./consts";
Expand Down
95 changes: 95 additions & 0 deletions test/auth.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { Server } from "node:http";
import getPort from "get-port";
import { Client } from "undici";
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import {
createApp,
toNodeListener,
App,
eventHandler,
withBasicAuth,
} from "../src";

describe("auth", () => {
let app: App;
let server: Server;
let client: Client;

beforeEach(async () => {
app = createApp({ debug: true });
server = new Server(toNodeListener(app));
const port = await getPort();
server.listen(port);
client = new Client(`http://localhost:${port}`);
});

afterEach(() => {
client.close();
server.close();
});

describe("withBasicAuth", () => {
it("responds 401 for a missing authorization header", async () => {
app.use(
"/test",
withBasicAuth(
{ username: "test", password: "123!" },
eventHandler(async () => {
return "Hello, world!";
}),
),
);
const result = await client.request({
path: "/test",
method: "GET",
});

expect(await result.body.text()).toBe("Authentication required");
expect(result.statusCode).toBe(401);
});

it("responds 401 for an incorrect authorization header", async () => {
app.use(
"/test",
withBasicAuth(
{ username: "test", password: "123!" },
eventHandler(async () => {
return "Hello, world!";
}),
),
);
const result = await client.request({
path: "/test",
method: "GET",
headers: {
Authorization: `Basic ${Buffer.from("test:wrongpass").toString("base64")}`,
},
});

expect(await result.body.text()).toBe("Authentication required");
expect(result.statusCode).toBe(401);
});

it("responds 200 for a correct authorization header", async () => {
app.use(
"/test",
withBasicAuth(
"test:123!",
eventHandler(async () => {
return "Hello, world!";
}),
),
);
const result = await client.request({
path: "/test",
method: "GET",
headers: {
Authorization: `Basic ${Buffer.from("test:123!").toString("base64")}`,
},
});

expect(await result.body.text()).toBe("Hello, world!");
expect(result.statusCode).toBe(200);
});
});
});