NestJS Authentication Basic middleware example


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

Recent search terms:

  • base64 auth nestjs
  • nestjs basic auth decode
  • nestjs basic auth header
  • nestjs header BASIC

Leave a Reply