Skip to content

Basic Auth

  • Easy-to-implement HTTP Basic Authentication for Gaman.
  • Supports static credentials or dynamic validation logic.
  • Customizable challenge realm and invalid authentication messages.


you need to install the following packages

Terminal window
npm install @gaman/basic-auth
  1. Static Credentials

    Use a fixed username and password for authentication:

    example.block.ts
    export default defineBlock({
    includes: [
    basicAuth({
    username: "admin",
    password: "password123",
    }),
    ],
    });
  2. Dynamic Validation

    Use a custom function to validate credentials dynamically:

    example.block.ts
    export default defineBlock({
    includes: [
    basicAuth({
    verifyAuth: async (username, password, ctx) => {
    return username === "user" && password === "pass"; // Example validation logic
    },
    }),
    ],
    });

OptionTypeDescriptionDefault
usernamestringStatic username for authentication.Required
passwordstringStatic password for authentication.Required
verifyAuth(username, password, ctx) => boolCustom function to dynamically validate credentials.undefined
realmstringRealm used in the authentication challenge."Secure Area"
invalidAuthMessagestring | object | MessageFunctionMessage returned on invalid authentication. Can be a string, JSON object, or a function.undefined

example.block.ts
export default defineBlock({
includes: [
basicAuth({
username: "admin",
password: "secret",
realm: "Admin Area",
invalidAuthMessage: { error: "Unauthorized access." },
}),
],
});
example.block.ts
export default defineBlock({
includes: [
basicAuth({
username: "admin",
password: "secret",
invalidAuthMessage: async (ctx) => {
return {
error: "Authentication failed.",
timestamp: new Date().toISOString(),
};
},
}),
],
});

Basic Authentication is a simple method to protect routes by requiring a username and password to access resources.

This middleware streamlines adding HTTP Basic Authentication to your GamanJS applications, whether with static credentials or dynamic logic.


Secure your GamanJS routes effortlessly with gaman/basic-auth!