Skip to content
导航

HTTP Basic 认证

HTTP Basic 是最简单的认证策略,由于HTTP是明文传输的,任何代理服务都能查阅,通常这个认证策略仅用于本地或内网环境。

用法

  1. 服务端在响应中返回状态码401,响应头包含以下内容
http
WWW-Authenticate: Basic
  1. 浏览器在收到响应后会向用户弹框 image
  2. 用户在输入用户名和密码后,浏览器会拼接字符串用户名:密码并转为base64,然后添加到请求头上重新请求
http
Authorization: Basic YWRtaW46cGFzc3dvcg==
  1. 服务端校验上述base64,鉴权通过则返回有效数据
  2. 携带 Authorization 的请求在响应成功后会被浏览器缓存,供后续请求免弹窗使用

代码示例

luoway/web-service-demo

ts
import * as http from "http"

const username = 'admin'
const password = 'password'

export function handleAuth(request: http.IncomingMessage, response: http.ServerResponse) {
    const auth = request.headers.authorization
    if(auth){
        const [type, data] = auth.split(/\s/)
        if(type === 'Basic'){
            const authDecoded = Buffer.from(data, 'base64').toString()
            if(authDecoded === `${username}:${password}`){
                return response.writeHead(200).end('auth successfully')
            }
        }
    }
    
    return response.writeHead(401, {
        'WWW-Authenticate': 'Basic'
    }).end()
}

参考资料