express-basic-auth icon indicating copy to clipboard operation
express-basic-auth copied to clipboard

Using express-basic-auth with router ?

Open Cliff-R-K opened this issue 5 years ago • 3 comments

I can't figure out how to use express-basic-auth correctly. If I make a POST-request to "/abort" with correct authorization everything seams to work correctly. But if I enter the wrong credentials in the header I get the correct "Credentials rejected" message. But it still triggers the "/abort" endpoint and also gives med console.log outputs and 200 message:sucess

What am I missing ? App.js

const getUnauthorizedResponse = (req) => {
  return req.auth
    ? `Credentials ${req.auth.user} : ${req.auth.password} rejected`
    : "No credentials provided";
};

app.use(
  basicAuth({
    users:  {"user":"password"} ,
    unauthorizedResponse: getUnauthorizedResponse,
  })
);

app.get("/", (req, res) => res.send("API Running"));

app.use("/api", require("./routes/api/abort").router);

abort.js

const express = require("express");
const router = express.Router();

router.post('/abort', async (req, res) => {
    try {
        const body = await req.body
        const hostname = body.hostname
        console.log(`Abort datacollection endpoint.\nHostname is ${hostname}`)
        return res.status(200).send({message:"success"})
    } catch (error) {
        console.log("error!!!")
        return res.status(404).send({message:"fail"})
    }
})

module.exports = { router };

Cliff-R-K avatar Oct 05 '20 06:10 Cliff-R-K

@burton666

app.get("route", basicAuth(....), (req, res) => {.....})

coffeeispower avatar Feb 05 '22 17:02 coffeeispower

@tiagodinis33 but if you do it that way you can't use the Request parameters to fetch the basicauth details from somewhere.

AlphaJuliettOmega avatar Feb 18 '22 13:02 AlphaJuliettOmega

It would be nice if there was a way to use the request parameter with app.get. Or at least get the req.auth boolean value provided by the middleware.

		this.app.get( `/getToken`, basicAuth( {
			users: {
				uname: 'secret',
			},
			challenge: true,
			unauthorizedResponse: function( req: Request ) 
			{
				console.log( req.auth )
			}
		} ), this.getToken )

sephentos avatar Sep 02 '22 19:09 sephentos