Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fastify-swagger: protect access of Swagger UI #465

Closed
simon-tannai opened this issue Mar 10, 2021 · 5 comments · Fixed by #466
Closed

fastify-swagger: protect access of Swagger UI #465

simon-tannai opened this issue Mar 10, 2021 · 5 comments · Fixed by #466
Assignees

Comments

@simon-tannai
Copy link

Hello !

I'm using fastify-swagger to generate API documentation.
It's working fine but I would like to protect the access to Swagger UI with a simple username / password.

Is it possible do to it with fastify-swagger ?

@mcollina
Copy link
Member

It's not currently possible but it would be really useful, would you like to send a PR?

@Eomm Eomm self-assigned this Sep 10, 2021
@Eomm
Copy link
Member

Eomm commented Sep 10, 2021

The swagger-ui used under the hood does not support this kind of feature out of the box.

You can run this snippet to add it:

const fastify = require('fastify')({ logger: true })

const docPrefix = '/docs'

fastify.register(require('fastify-basic-auth'), {
  validate,
  authenticate: true
}).after(() => {
  fastify.addHook('onRoute', function hook (routeOptions) {
    if (routeOptions.url.startsWith(docPrefix)) {
      routeOptions.onRequest = fastify.basicAuth
    }
  })
})
function validate (username, password, req, reply, done) {
  if (username === 'admin' && password === 'admin') {
    done()
  } else {
    done(new Error('Winter is coming'))
  }
}

fastify.register(require('fastify-swagger'), {
  routePrefix: docPrefix,
  ....

And it works

@simon-tannai Would you like to integrate it in our plugin out of the box?
We could accept the onRequest hooks by input so users may provide it without the burden to listen for the onRoute hook

@zekth
Copy link
Member

zekth commented Sep 10, 2021

I'm +1 on hooks addition to the swagger-ui config.

@Eomm Eomm transferred this issue from fastify/help Sep 14, 2021
@Eomm Eomm closed this as completed in #466 Sep 15, 2021
@kalitas
Copy link

kalitas commented Jan 5, 2023

but this will lead that this check runs on every request made to the server..no?

@fornof
Copy link

fornof commented May 26, 2023

yes, that is basic authentication. Generally basic auth is saved in the browser for additional requests so it is transparent to user.
I might store user/pass in environment variable or in a json file with hashed password, then check the hashes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

6 participants