LionC / express-basic-auth

Plug & play basic auth middleware for express
325 stars 57 forks source link

Using express-basic-auth with router ? #36

Open Cliff-R-K opened 3 years ago

Cliff-R-K commented 3 years ago

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 };
coffeeispower commented 2 years ago

@burton666

app.get("route", basicAuth(....), (req, res) => {.....})
AlphaJuliettOmega commented 2 years ago

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

sephentos commented 1 year ago

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 )