oapi-codegen
oapi-codegen copied to clipboard
Is there a way to have authenticated and non-authenticated paths?
What?
I'm using a bearer security scheme and I want to authenticate some endpoints but there are some of them I don't want, for example, the login endpoint that I use to get the JWT token.
Do you folks know how can I handle that?
Also, is there a way to skip a path to be generated? As I couldn't figure out how to have non-authenticated endpoints, my next option would be not to use the generated code to implement the login endpoint. But it turns out, that the only to do that right now is to remove the definitions from my openapi file, what is terrible for my documentation and tests cases :(
Many thanks!
I've done this before with oapi-codegen (v1.11.x) and it should still be viable - do you have an OpenAPI spec to share?
I.e. the following that uses a default of HTTP Basic auth, but allows excluding the auth per-endpoint:
security:
- basic: []
paths:
"/health":
get:
description: Healthcheck endpoint
operationId: healthcheck
security: []
responses:
'200':
description: Service is healthy
content: {}
"/crash":
get:
description: Crash endpoint to test monitoring
operationId: crash
# lack of `security` ensures it defaults to auth
components:
securitySchemes:
basic:
type: http
scheme: basic
@jamietanna many thanks for your answers!
When I asked this question, I was a bit hasty, so it turns out that there is some context missing. I was trying to use the Echo JWT Middleware . I have been using this middleware to validate the JWT of my requests. I was struggling to add it to the generated server.
Usually, we separate the endpoints that will use the JWT middleware or not through echo groups, which I can't have using oapi-codegen.
Reading more the examples founder, I figure out we need to write our own function to validate it, like here: https://github.com/deepmap/oapi-codegen/blob/master/examples/authenticated-api/echo/server/jwt_authenticator.go
Is there a way to use the Echo JWT middleware? 🤔 Is it a good idea to add a way to generate echo groups? If you think it's worth it, I can provide some options to implement that.
Here is the Open API spec: https://github.com/matheuslc/go-social-graph/blob/main/openapi/openapi.yml Here is the generated server: https://github.com/matheuslc/go-social-graph/blob/main/server/server.gen.go
Meanwhile, I've removed the Echo JWT middleware and am now validating my JWT through the authenticate func. This way, it correctly only requires JWT token where I'm declaring a security field on Open API.
Again, many thanks! I'm really enjoying this library!