A Guide to Implementing Basic HTTP Authentication with Express

Sep 21, 2021 | Programming

In the world of web applications, security is essential, especially when it comes to protecting sensitive data. One of the simplest yet effective ways of securing your application is via HTTP Basic Authentication. In this blog, we will walk you through how to use the express-basic-auth middleware for your Express applications. Let’s dive in!

Installation

To get started, install the package using npm:

npm install express-basic-auth

Basic Usage

Once installed, import the module and set up your Express application to make use of it. Here’s a breakdown:

Imagine your application is a club that only allows certain people inside. The basic authentication acts like a doorman checking the guest list.

const app = require('express')();
const basicAuth = require('express-basic-auth');

app.use(basicAuth({
    users: {
        admin: 'supersecret'
    }
}));

In this analogy, only the ‘admin’ with the password ‘supersecret’ can enter the club (your app). If anyone else tries to enter without the right credentials, they will be turned away.

Static Users

If you want to allow multiple static credentials, you can simply add them like this:

app.use(basicAuth({
    users: {
        admin: 'supersecret',
        adam: 'password1234',
        eve: 'asdfghjkl'
    }
}));

Now, three people can enter the club. The doorman will check that they have the right password before letting them in.

Custom Authorization

Need more advanced checking? Create a custom authorizer function, which allows any logic you want. However, be careful about using standard string comparisons. Think of it like using a private password encrypted in code!

app.use(basicAuth({
    authorizer: myAuthorizer
}));

function myAuthorizer(username, password) {
    const userMatches = basicAuth.safeCompare(username, 'customuser');
    const passwordMatches = basicAuth.safeCompare(password, 'custompassword');
    return userMatches && passwordMatches;
}

This approach ensures robust security while allowing you to define any access rules as needed.

Asynchronous Authorization

For situations where you need to check credentials asynchronously, set up your authorizer accordingly:

app.use(basicAuth({
    authorizer: myAsyncAuthorizer,
    authorizeAsync: true,
}));

function myAsyncAuthorizer(username, password, cb) {
    if (username.startsWith('A') && password.startsWith('secret')) {
        return cb(null, true);
    } else {
        return cb(null, false);
    }
}

Use this method similar to checking if a VIP guest has booked their entry in advance. It may take a little time, but it ensures that only the right people get in.

Custom Unauthorized Responses

You can customize the response for unauthorized attempts. Perhaps you want to tell the user why they’re not allowed in?

app.use(basicAuth({
    users: { Foo: 'bar' },
    unauthorizedResponse: getUnauthorizedResponse
}));

function getUnauthorizedResponse(req) {
    return req.auth
        ? `Credentials ${req.auth.user}:${req.auth.password} rejected`
        : 'No credentials provided';
}

This way, users will know what went wrong when they try to enter the club!

Testing Your Implementation

To ensure everything is functioning properly, test the setup using the example.js file included in the repository:

npm install express express-basic-auth
node example.js

This will spin up a server listening on port 8080, allowing you to play around and see how your newly set up authentication behaves.

TypeScript Usage

For those working with TypeScript, the package includes a declaration file, so you don’t have to install any additional types. You can easily use the req.auth property without errors.

app.use(basicAuth(options), (req: basicAuth.IBasicAuthedRequest, res, next) => {
    res.end(`Welcome ${req.auth.user} (your password is ${req.auth.password})`);
    next();
});

Troubleshooting

  • If you notice that certain users are being denied access who should have been authenticated, double-check the credentials you have set in the middleware.
  • Ensure the imports are accurately spelled, including the correct package name, as JavaScript is case-sensitive.
  • Double-check for any asynchronous code issues if you opted for custom async authorizers.
  • For more insights, updates, or to collaborate on AI development projects, stay connected with fxis.ai.

At fxis.ai, we believe that such advancements are crucial for the future of AI, as they enable more comprehensive and effective solutions. Our team is continually exploring new methodologies to push the envelope in artificial intelligence, ensuring that our clients benefit from the latest technological innovations.

Conclusion

Implementing HTTP Basic Authentication using express-basic-auth can significantly enhance the security of your Express applications. With its straightforward setup and flexible options, you can cater to various authentication needs and ensure that only authorized users gain access.

Stay Informed with the Newest F(x) Insights and Blogs

Tech News and Blog Highlights, Straight to Your Inbox