koa-basic-auth-connect
v1.0.4
Published
Basic authentication middleware for koa.
Downloads
2
Readme
koa-basic-auth-connect
Installation
npm install koa-basic-auth-connect
Example
const Koa = require('koa');
const basicAuth = require('koa-basic-auth-connect');
const app = new Koa();
app.use(basicAuth({
users: {'SampleUser': 'password'}
}));
The middleware checks for a match to the credentials of the received request. It parses the "Authorization" header according to the Basic Authentication protocol and checks if the credentials are legitimate.
If it is correct, a property is added to ctx.state.auth
. This object contains an object with user
and password
properties
If authentication fails, a 401 HTTP response is returned.
Options
export type FunctionalOption<T>=T | ((ctx: Context) => T);
type Options={
users: Users;
realm?: FunctionalOption<string>;
challenge?: boolean;
authorizer?: Authorizer;
continueIfUnauthorized?: FunctionalOption<boolean>;
};
| Option | Description | Default | |-----------|--------------------------------------------------------------------|-----------| | users | Records by User ID and Secret | | | realm | Set realm on unauthorized response | | | challenge | Add a challenge header on unauthorized response | false | | authorizer | Set custom authorizer function | | |continueIfUnauthorized | Continue middleware chain when unauthenticated | false |
Challenge
By default, the middleware does not add a WWW-Authenticate
challenge header to the unauthorized response.
You can be enable that by challenge
option. This will cause most browsers to display a popup for entering credentials
for unauthenticated responses. You may also add The realm can be used to identify the system to be authenticated and
stored by the client.
app.use(basicAuth({
users: {'ChallengeUser': 'psssword'},
challenge: true,
realm: 'Aiq+LNOl7X+LftH',
}))
Authorizer
The user and password are passed to the callback (async) function.
For example, you can implement your own authentication like this
app.use(basicAuth({
authorizer: (user: string, password: string) => (password == 'anysecret')
}))