Home > Back-end >  How to use express-basic-auth so my app returns 401 if credentials are not supplied?
How to use express-basic-auth so my app returns 401 if credentials are not supplied?

Time:10-30

I'm trying to add basic authentication to my app using the express-basic-auth. I'm following the instructions on this page, which also says "If a request is found to not be authorized, it will respond with HTTP 401" but my app simply replies with status code 200 when I do not pass any credentials

It seems I've incorrectly configured express-basic-auth. What have I done wrong?

const express = require('express')
const app = express()
const port = 3001

const basicAuth = require('express-basic-auth')

app.use(basicAuth({
  users: { 'admin': 'supersecret' },
}))

app.get('/', (req, res) => {
  res.send('Hello World!')
})


app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

CodePudding user response:

Your code works. I confirmed with a nodejs client app that the basic auth works when given the right username and password and gives back a 401 when not given the right username and password or given no username and password.

The likely explanation is that you're not actually running your latest code and there's some previous server still running that doesn't require the basic auth.

You can verify that you are hitting the right server by adding

app.use((req, res, next) => { 
    console.log("got new server"); 
    next(); 
}); 

before your basic auth middleware and verify that you see this log in the server console when you try your request. If you don't see this new log in the console, then you aren't hitting the newest code.

  • Related