Skip to content

Commit

Permalink
fix(index): do not set header if authenticate is false (#126)
Browse files Browse the repository at this point in the history
  • Loading branch information
Fdawgs authored Dec 2, 2023
1 parent fa11558 commit d314d9b
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
5 changes: 4 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,10 @@ async function fastifyBasicAuth (fastify, opts) {
}

if (err.statusCode === 401) {
reply.header('WWW-Authenticate', authenticateHeader(req))
const header = authenticateHeader(req)
if (header) {
reply.header('WWW-Authenticate', header)
}
}
next(err)
} else {
Expand Down
48 changes: 48 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,54 @@ test('WWW-Authenticate (authenticate: true)', t => {
})
})

test('WWW-Authenticate (authenticate: false)', t => {
t.plan(6)

const fastify = Fastify()
const authenticate = false
fastify.register(basicAuth, { validate, authenticate, utf8: false })

function validate (username, password, req, res, done) {
if (username === 'user' && password === 'pwd') {
done()
} else {
done(new Error('Unauthorized'))
}
}

fastify.after(() => {
fastify.route({
method: 'GET',
url: '/',
preHandler: fastify.basicAuth,
handler: (req, reply) => {
reply.send({ hello: 'world' })
}
})
})

fastify.inject({
url: '/',
method: 'GET'
}, (err, res) => {
t.error(err)
t.equal(res.headers['www-authenticate'], undefined)
t.equal(res.statusCode, 401)
})

fastify.inject({
url: '/',
method: 'GET',
headers: {
authorization: basicAuthHeader('user', 'pwd')
}
}, (err, res) => {
t.error(err)
t.equal(res.headers['www-authenticate'], undefined)
t.equal(res.statusCode, 200)
})
})

test('WWW-Authenticate Realm (authenticate: {realm: "example"}, utf8: false)', t => {
t.plan(6)

Expand Down

0 comments on commit d314d9b

Please sign in to comment.