Simple plug & play HTTP basic auth middleware for Express.
Just run
npm install express-basic-auth
The module will export a function, that you can call with an options object toget the middleware:
const app = require('express')()
const basicAuth = require('express-basic-auth')
app.use(basicAuth({
users: { 'admin': 'supersecret' }
}))
The middleware will now check incoming requests to match the credentialsadmin:supersecret
.
The middleware will check incoming requests for a basic auth (Authorization
)header, parse it and check if the credentials are legit. If there are anycredentials, an auth
property will be added to the request, containingan object with user
and password
properties, filled with the credentials,no matter if they are legit or not.
If a request is found to not be authorized, it will respond with HTTP 401and a configurable body (default empty).
If you simply want to check basic auth against one or multiple static credentials,you can pass those credentials in the users
option:
app.use(basicAuth({
users: {
'admin': 'supersecret',
'adam': 'password1234',
'eve': 'asdfghjkl',
}
}))
The middleware will check incoming requests to have a basic auth header matchingone of the three passed credentials.
Alternatively, you can pass your own authorizer
function, to check the credentialshowever you want. It will be called with a username and password and is expected toreturn true
or false
to indicate that the credentials were approved or not.
When using your own authorizer
, make sure not to use standard string comparison (==
/ ===
)when comparing user input with secret credentials, as that would make you vulnerable againsttiming attacks. Use the provided safeCompare
function instead - always provide the user input as its first argument. Also make sure to use bitwiselogic operators (|
and &
) instead of the standard ones (||
and &&
) for the same reason, asthe standard ones use shortcuts.
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 will authorize all requests with the credentials 'customuser:custompassword'.In an actual application you would likely look up some data instead ;-) You can do whatever youwant in custom authorizers, just return true
or false
in the end and stay aware of timingattacks.
Note that the authorizer
function above is expected to be synchronous. This isthe default behavior, you can pass authorizeAsync: true
in the options object to indicatethat your authorizer is asynchronous. In this case it will be passed a callbackas the third parameter, which is expected to be called by standard node conventionwith an error and a boolean to indicate if the credentials have been approved or not.Let's look at the same authorizer again, but this time asynchronous:
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)
}
Per default, the response body for unauthorized responses will be empty. It canbe configured using the unauthorizedResponse
option. You can either pass astatic response or a function that gets passed the express request object and isexpected to return the response body. If the response body is a string, it willbe used as-is, otherwise it will be sent as JSON:
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'
}
Per default the middleware will not add a WWW-Authenticate
challenge header toresponses of unauthorized requests. You can enable that by adding challenge: true
to the options object. This will cause most browsers to show a popup to entercredentials on unauthorized responses. You can set the realm (the realmidentifies the system to authenticate against and can be used by clients to savecredentials) of the challenge by passing a static string or a function that getspassed the request object and is expected to return the challenge:
app.use(basicAuth({
users: { 'someuser': 'somepassword' },
challenge: true,
realm: 'Imb4T3st4pp',
}))
The repository contains an example.js
that you can run to play around and trythe middleware. To use it just put it somewhere (or leave it where it is), run
npm install express express-basic-auth
node example.js
This will start a small express server listening at port 8080. Just look at the file,try out the requests and play around with the options.
A declaration file is bundled with the library. You don't have to install a @types/
package.
import * as basicAuth from 'express-basic-auth'
req.auth
express-basic-auth sets req.auth
to an object containing the authorized credentials like { user: 'admin', password: 'supersecret' }
.
In order to use that req.auth
property in TypeScript without an unknown property error, use covariance to downcast the request type:
app.use(basicAuth(options), (req: basicAuth.IBasicAuthedRequest, res, next) => {
res.end(`Welcome ${req.auth.user} (your password is ${req.auth.password})`)
next()
})
Due to some TypeScript's type-system limitation, the arguments' type of the synchronous authorizers are not inferred.For example, on an asynchronous authorizer, the three arguments are correctly inferred:
basicAuth({
authorizeAsync: true,
authorizer: (user, password, authorize) => authorize(null, password == 'secret'),
})
However, on a synchronous authorizer, you'll have to type the arguments yourself:
basicAuth({
authorizer: (user: string, password: string) => (password == 'secret')
})
The cases in the example.js
are also used for automated testing. So if you want
to contribute or just make sure that the package still works, simply run:
npm test
basicAuth中间件为网站添加身份认证功能.在使用了该中间件后, 用户访问网站时必须输入用户名与密码,在用户输入了用户名与密码并通过验证之后才能访问网站. 当用户输入的用户名和密码符合条件,中间件会返回true,允许用户访问网站.否则会返回false.不允许访问网站. 复制代码 代码如下: var express=require("express"); var app=express(); a
在HTTP中,基本认证(Basic access authentication)是一种用来允许网页浏览器或其他客户端程序在请求时提供用户名和口令形式的身份凭证的一种登录验证方式。 在发送之前是以用户名追加一个冒号然后串接上口令,并将得出的结果字符串再用Base64算法编码。例如,提供的用户名是Aladdin、口令是open sesame,则拼接后的结果就是Aladdin:open sesame,然
认证说明 1.Etcd v2以上的版本才支持权限认证,且仅支持Basic Auth 2.Etcd通过用户(user)-角色(role)-权限的方式来控制访问,用户关联角色,角色拥有权限,从而用户也就拥有了相应的权限 3.Etcd默认没有启用认证机制,只要能连接etcd服务就拥有所有的权限,还是非常危险的,另一种安全的访问方式是开启ssl,只有使用受信任的证书才能访问数据 4.Etcd开启Basic
一个PHP项目附带加了一个文档二级目录 密码输入是对的,可是不能访问 查看权限,也给这个目录访问权限了 # 出现403 Forbidden https://www.demo.com/doc # 测试发现,这个地址可以访问 https://www.demo.com/doc/index.html nginx 部分配置如下 server { listen 80; server_n
shell > yum -y install httpd-tools # 安装 htpasswd 工具 shell > cd /usr/local/nginx-1.10.2/conf shell > htpasswd -c pass.db wang # 创建认证用户 wang 并输入密码,添加用户时输入 htpasswd pass.db username shell > vim /usr
整体流程 客户端使用账号和密码登录 服务端使用账号查询用户是否存在,如果不存在则返回错误信息 服务端把传过来的密码进行加密,然后和数据库加密后的密码进行比对,正确则生成token返回客户端 客户端收到token存储在localStorage中 在客户端请求拦截器中对请求头进行操作,使每次请求带上token 服务端每次请求时解析传过来的token进行登录状态验证,失败则通知客户端跳转登录页面 use
odejs express session 身份验证 1)引入模块 var session = require('express-session'); var cookieParser = require('cookie-parser'); 2)应用cookie及session app.use(cookieParser()); app.use(session({ resave: true,
Basic Authorization 认证方法 https://segmentfault.com/a/1190000017563615 HTTP Basic Authorization https://www.cnblogs.com/linxiyue/p/4079768.html HTTP Authorization 之 Basic Auth https://www.jianshu.co
场景: 由于多次调用对方接口失败,对方修改了请求规则,采取Basic Auth进行请求,提供对应的用户名、密码,对接过程中需要请求对方接口,需要添加该Basic Auth. 在PostMan中调用,该参数写的很方便,在代码逻辑中实现,该参数需要安置在Header头中,具体使用如下: Basic Auth作为请求头是以 Base64对用户名密码加密 规则: secre
在 org.springframework.web.client.RestTemplate这个类的使用过程中遇到了点小疑惑,这里和大家分享一下,同时也是做个备忘录。 先给结果,后说疑问: //方法一 使用RestTemplateBuilder来实例化 RestTemplateBuilder builder = new RestTemplateBuilder(); RestTemplate res
# 如果username中携带:, 执行URLencode username,password # https://devpal.co/url-encode/ curl --user username:password https://example.com curl -u username:password https://example.com curl -u 'username:passwo
Random.boolean( min?, max?, current? ) Random.boolean() Random.boolean( min, max, current ) 返回一个随机的布尔值。 min 可选。 指示参数 current 出现的概率。概率计算公式为 min / (min + max)。该参数的默认值为 1,即有 50% 的概率返回参数 current。 max 可选。
描述 (Description) 标准菜单语法用于向下钻取菜单。 对于每个嵌套菜单,属性data-drilldown都包含在根《ul》和.menu中。 例子 (Example) 以下示例演示了在Foundation中使用向下钻取下拉菜单 - <!DOCTYPE html> <html> <head> <title>Foundation Template</title>
A simple implementation of the @handsontable/vue component.import Vue from 'vue'; import { HotTable } from '@handsontable/vue'; import Handsontable from 'handsontable'; new Vue({ el: '#example1', data
An implementation of the @handsontable/angular wrapper.// app.component.ts import { Component } from '@angular/core'; import * as Handsontable from 'handsontable'; @Component({ selector: 'app-root', t
An implementation of the @handsontable/react wrapper.import React from 'react'; import ReactDOM from 'react-dom'; import { HotTable } from '@handsontable/react'; import Handsontable from 'handsontable
Basicauth 中间件提供了Http Basic认证,是一个 Tango 的中间件。 安装 go get github.com/tango-contrib/basicauth 示例 type AuthAction struct {} func (a *AuthAction) Get() string { return "200" } func main() { tg := ta