What is basic-auth?
The basic-auth npm package is a simple module to parse `Authorization` header for basic authentication in Node.js applications. It extracts the user credentials from the header and makes them available for authentication purposes.
What are basic-auth's main functionalities?
Parse Basic Auth Credentials
This code demonstrates how to use basic-auth to parse the `Authorization` header in an Express.js application. It checks if the credentials match a predefined username and password, and either grants access or denies it with a 401 status code.
const auth = require('basic-auth');
const express = require('express');
const app = express();
app.use((req, res) => {
const credentials = auth(req);
if (!credentials || credentials.name !== 'user' || credentials.pass !== 'pass') {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="example"');
res.end('Access denied');
} else {
res.end('Access granted');
}
});
app.listen(3000);
Other packages similar to basic-auth
passport-http
Passport-http is a strategy for Passport, an authentication middleware for Node.js. It implements Basic and Digest authentication. Compared to basic-auth, passport-http is more feature-rich, allowing for integration with the broader Passport ecosystem and providing more options for authentication.
express-basic-auth
Express-basic-auth is an authentication library designed specifically for Express.js applications. It provides a simple way to protect routes with basic authentication. Unlike basic-auth, which only parses the credentials, express-basic-auth handles the full authentication process, making it easier to use but less flexible for non-Express use cases.
http-auth
Http-auth is a module that provides basic and digest authentication for HTTP and HTTPS protocols. It is similar to basic-auth but offers more features, such as integration with different types of data stores for credential checking and support for digest authentication.
basic-auth
Generic basic auth Authorization header field parser for whatever.
Installation
$ npm install basic-auth
Example
Pass a node request or koa Context object to the module exported. If
parsing fails undefined
is returned, otherwise an object with
.name
and .pass
.
var auth = require('basic-auth');
var user = auth(req);
With vanilla node.js http server
var http = require('http')
var auth = require('basic-auth')
var server = http.createServer(function(req, res){
var credentials = auth(req)
if (!credentials || credentials.name !== 'john' || credentials.pass !== 'secret') {
res.writeHead(401, {
'WWW-Authenticate': 'Basic realm="example"'
})
res.end()
} else {
res.end('Access granted');
}
})
server.listen(3000)
License
MIT