Skip to content

Commit

Permalink
Add docs for protecting the documentation routes (#47)
Browse files Browse the repository at this point in the history
* Add docs for protecting the documentation routes

When @fastify/swagger-ui was part of @fastify/swagger there used to be documentation for protecting the documentation routes, but that wasn't transferred over when [it was removed](fastify/fastify-swagger@f15bebd#diff-b335630551682c19a781afebcf4d07bf978fb1f8ac04c6bf87428ed5106870f5L689) it seems.

I know I've spent a bit of time searching for how to do this, stumbling upon fastify/fastify-swagger#466 and getting confused when the docs are not there anymore in the current HEAD.

I think it would be beneficial to add this to the fastify-swagger-ui docs since it's a very common use case.

* Update README.md

Co-authored-by: Uzlopak <aras.abbasi@googlemail.com>

* Update README.md

Add a better example using constant-time comparison to prevent timing attacks

---------

Co-authored-by: Uzlopak <aras.abbasi@googlemail.com>
  • Loading branch information
fertolg and Uzlopak committed Mar 23, 2023
1 parent 2745afa commit bf84b4d
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,52 @@ await fastify.register(require('@fastify/swagger-ui'), {
})
```

#### Protect your documentation routes

You can protect your documentation by configuring an authentication hook.
Here is an example using the [`@fastify/basic-auth`](https://github.com/fastify/fastify-basic-auth) plugin:

##### Example
```js
const fastify = require('fastify')()
const crypto = require('crypto')

fastify.register(require('@fastify/swagger'))

// perform constant-time comparison to prevent timing attacks
function compare (a, b) {
a = Buffer.from(a)
b = Buffer.from(b)
if (a.length !== b.length) {
// Delay return with cryptographically secure timing check.
crypto.timingSafeEqual(a, a)
return false
}

return crypto.timingSafeEqual(a, b)
}

await fastify.register(require('@fastify/basic-auth'), {
validate (username, password, req, reply, done) {
let result = true
result = compare(username, validUsername) && result
result = compare(password, validPassword) && result
if (result) {
done()
} else {
done(new Error('Access denied'))
}
},
authenticate: true
})

await fastify.register(require('@fastify/swagger-ui', {
uiHooks: {
onRequest: fastify.basicAuth
}
})
```
<a name="license"></a>
## License
Expand Down

0 comments on commit bf84b4d

Please sign in to comment.