File admin.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common'; import { Request, Response } from 'express'; @Injectable() export class AdminMiddleware implements NestMiddleware { use(req: Request, res: Response, next: () => void) { let authorization; if(authorization = req.headers['authorization']){ let basic = authorization.match(/^Basic (.+)$/) if(basic){ basic = basic[1] basic = Buffer.from(basic,"base64").toString("utf8") if(basic == "youruser:yourpassword"){ return next(); } } } res.statusCode = 401 res.setHeader("WWW-Authenticate", "Basic realm=\"Login Strict\"") res.send('') } }
Read more:
HTTP authentication
NestJS Middleware