Check authorization with express basic auth only

I’m trying to check if someone has entered an authorized username and password in my link for a specific path called '/protected' example: admin:[email protected]:8080/protected

If the person has inputted this then he will arrive to a page says “welcome authorized”

If the person hasn’t inputted the link like this instead just: localhost:8080/protected He will receive a message “not authorized” along with error 401

This is the code that i came up with but only if you are authorized will receive a message, else you don’t receive anything.

router.get('/protected', basicAuth({
        users: {'admin':'admin'}
    }),(req,res)=>{
    res.send('Welcome, authenticated client');
});

Answer

It looks like you are using the express-basic-auth package, which by default sends no response body when authorization is rejected.

Per the documentation, to add a response body to requests that fail authorization, you need to add the unauthorizedResponse property to the object you pass to the basicAuth middleware.

To add a generic message, it can be as simple as a string.

router.get('/protected', basicAuth({
        users: {'admin':'admin'},
        unauthorizedResponse: 'not authorized'
    }),(req,res)=>{
    res.send('Welcome, authenticated client');
});

To add a dynamic message, you can use a function (which will have access to the request object through the first parameter):

router.get('/protected', basicAuth({
        users: {'admin':'admin'},
        unauthorizedResponse: getUnauthorizedResponse
    }),(req,res)=>{
    res.send('Welcome, authenticated client');
});

function getUnauthorizedResponse(req) {
    const { user } = req.auth?.user ?? {}
    return user ? `invalid credentials for user '${user}'` : 'no credentials provided';
}

Leave a Reply

Your email address will not be published. Required fields are marked *