Skip to content

Commit bf84b4d

Browse files
fertolgUzlopak
andauthored
Add docs for protecting the documentation routes (#47)
* 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 <[email protected]> * Update README.md Add a better example using constant-time comparison to prevent timing attacks --------- Co-authored-by: Uzlopak <[email protected]>
1 parent 2745afa commit bf84b4d

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

README.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,52 @@ await fastify.register(require('@fastify/swagger-ui'), {
225225
})
226226
```
227227

228+
#### Protect your documentation routes
229+
230+
You can protect your documentation by configuring an authentication hook.
231+
Here is an example using the [`@fastify/basic-auth`](https://github.com/fastify/fastify-basic-auth) plugin:
232+
233+
##### Example
234+
```js
235+
const fastify = require('fastify')()
236+
const crypto = require('crypto')
237+
238+
fastify.register(require('@fastify/swagger'))
239+
240+
// perform constant-time comparison to prevent timing attacks
241+
function compare (a, b) {
242+
a = Buffer.from(a)
243+
b = Buffer.from(b)
244+
if (a.length !== b.length) {
245+
// Delay return with cryptographically secure timing check.
246+
crypto.timingSafeEqual(a, a)
247+
return false
248+
}
249+
250+
return crypto.timingSafeEqual(a, b)
251+
}
252+
253+
await fastify.register(require('@fastify/basic-auth'), {
254+
validate (username, password, req, reply, done) {
255+
let result = true
256+
result = compare(username, validUsername) && result
257+
result = compare(password, validPassword) && result
258+
if (result) {
259+
done()
260+
} else {
261+
done(new Error('Access denied'))
262+
}
263+
},
264+
authenticate: true
265+
})
266+
267+
await fastify.register(require('@fastify/swagger-ui', {
268+
uiHooks: {
269+
onRequest: fastify.basicAuth
270+
}
271+
})
272+
```
273+
228274
<a name="license"></a>
229275
## License
230276

0 commit comments

Comments
 (0)