You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Thanks for this great project, currently I'm replacing go-swagger by this project based on the chi templates.
Most, but not all of my API endpoints require an authentication based on basic auth, bearer token or an header token, how can this get generated? I think the endpoints that require authentication should add a middleware which calls a configured callback function.
I can't see a way how to properly do that from outside of the code, do I really need to add these checks to every handler manually?
Are you open to some generated middleware instead? For go-swagger I had definitions similar to this, which had been invoked automatically:
Hey, We are currently facing the same issue. We don't want to manually add a security validation to each method in the server interface and instead use a global security verification. We came up with an 2 step based approach:
We added a callback to the ServerInterfaceWrapper struct to contain a
field, which is then called by each operation for each security (if this field is set), right before the actual domain method is called. If secure returns an error the actual handler is never called.
We extended the RegisterHandlers method to take a variable amount of option functions which can be used to modify the ServerInterfaceWrapper. For now we would just generated a WithSecurity HandlerOption to set the secure field used in step 1. This way the RegisterHandlers method would stay backwards compatible but can be easily extended in the future. The generate code looks something like this:
I am also looking into the problem right now. Am wondering @jotdl how did you go with that PR at all? Be also really great to see a demo implementation of this too. As for me, this is taking some research to work out how to apply securitySchemes into my API.
Anyway, let me know how I can help get this over the line.
@lukekhamilton As I didn't get any feedback to the proposed change in this thread, the change is still on hold. But actually I iterated on this last week and came to a solution which doesn't require any changes to oapi-codegen at all, while still reducing maintenance effort to a minimum by relying on code generation:
As you probably know oapi-codegen generates a ServerInterface interface which contains one method for each of your endpoints. By using composition we could generate a wrapper for this interface which wraps each secured method and verifies security. This would look something like:
// SecurityMiddleware authenticates incoming requests against the specified providertypeSecurityMiddlewarefunc(ctx echo.Context, providerstring, scopes []string) error// secureServer is a small wrapper around an ServerInterface to ensure security through a centralised security middlewaretypesecureServerstruct {
ServerInterfacesecureSecurityMiddleware
}
funcNewSecureServer(srvServerInterface, securityLayerSecurityMiddleware) ServerInterface {
return&secureServer{
ServerInterface: srv,
secure: securityLayer,
}
}
For methods/endpoints which need to be secured, we could go with something like this:
This way you stay compatible with the oapi-codegen generated API by reusing the ServerInterface interface and initialising a centralised security layer is as easy as:
As this doesn't require any changes to oapi-codegen (just a little bit more code on top), we dropped my previously suggested approach and went with this one. Once we completely migrated to this approache I will delete the code changes from my previous approach. But in general I would be happy about any feedback about this approach!
The same solution for chi-server should look very similar as it's using a ServerInterface interface there, too.
As oapi-codegen can be easily used as a library, we also generate all of this code in a very lightweight wrapper around oapi-codegen. It just took roughly 100 lines of Go to automate all of this. If you are interested in this I would be happy to share.
The only thing to make this even easier would be the opportunity to add additional code generation templates (not replacing existing ones) to oapi-codegen. I am not aware that this is already possible, but maybe it's worth considering. But except that, we are really happy with the current oapi-codegen API!
Hey @jotdl, thanks for all the info. I'll be sure to give this approach a try tomorrow.
I would also very much love to have a look at the wrapper approach you have put together too and see what I can learn/use here too.
From my understanding of the oapi-codegen codebase I dont think you can add custom/additional code generation templates that are implemented in a project namespace. I know this type of thing exist in the go-swagger approach from memory. Not really sure what it would take to make that possible here tho.
Hi,
Excuse my late reply. Please find below a sample version of the wrapper we are currently using for generating the security layer on top of what's already been generated by oapi codegen:
package main
import (
"bytes""fmt""github.com/getkin/kin-openapi/openapi3""go/format""io/ioutil""os""text/template""github.com/deepmap/oapi-codegen/pkg/codegen""github.com/deepmap/oapi-codegen/pkg/util"
)
constsecurityLayerTmpl=`// SecurityMiddleware authenticates incoming requests against the specified providertype SecurityMiddleware func(ctx echo.Context, provider string, scopes []string) error// secureServer is a small wrapper around an ServerInterface to ensure security through a centralised security middlewaretype secureServer struct { ServerInterface secure SecurityMiddleware}func NewSecureServer(srv ServerInterface, securityLayer SecurityMiddleware) ServerInterface { return &secureServer{ ServerInterface: srv, secure: securityLayer, }}{{range .}}{{- if .SecurityDefinitions -}}// ({{.Method}} {{.Path}})func (s *secureServer) {{.OperationId}}(ctx echo.Context{{genParamArgs .PathParams}}{{if .RequiresParamObject}}, params {{.OperationId}}Params{{end}}) error { {{range .SecurityDefinitions -}} if err := s.secure(ctx, "{{.ProviderName}}", nil); err != nil { return err } {{end -}} return s.ServerInterface.{{.OperationId}}(ctx{{genParamNames .PathParams}}{{if .RequiresParamObject}}, params{{end}})}{{end}}{{end}}`funcmain() {
opts:= codegen.Options{
GenerateEchoServer: true,
GenerateTypes: true,
EmbedSpec: true,
}
swagger, err:=util.LoadSwagger("schema.yaml")
iferr!=nil {
_, _=fmt.Fprintf(os.Stderr, "error loading swagger spec\n: %s", err)
os.Exit(1)
}
code, err:=codegen.Generate(swagger, "main", opts)
iferr!=nil {
_, _=fmt.Fprintf(os.Stderr, "error generating code: %s\n", err)
os.Exit(1)
}
rawCode:= []byte(code)
// let's check if we have security definediflen(swagger.Security) >0 {
rawCode=generateSecurityLayer(code, swagger, err, rawCode)
}
err=ioutil.WriteFile("server.gen.go", rawCode, 0644)
iferr!=nil {
_, _=fmt.Fprintf(os.Stderr, "error writing generated code to file: %s", err)
os.Exit(1)
}
}
funcgenerateSecurityLayer(codestring, swagger*openapi3.Swagger, errerror, currentCode []byte) []byte {
writer:= bytes.Buffer{}
writer.WriteString(code)
ops, _:=codegen.OperationDefinitions(swagger) // err can not occur as this function is also used by codegen.Generate before (and would already fail there)tmpl:=template.Must(template.New("").Funcs(codegen.TemplateFunctions).Parse(securityLayerTmpl))
err=tmpl.Execute(&writer, ops)
iferr!=nil {
_, _=fmt.Fprintf(os.Stderr, "error generating security layer: %s", err)
os.Exit(1)
}
bytes, err:=format.Source(writer.Bytes())
iferr!=nil {
_, _=fmt.Fprintf(os.Stderr, "error formating generated security layer: %s", err)
os.Exit(1)
}
returnbytes
}
We currently invoke this with a //go:generate comment similar to this example
//go:generate go run <pkg>/cmd/generators/server-gen > server.gen.go
or run directly via
go run <pkg>/cmd/generators/server-gen > server.gen.go
This script relies on having the schema.yaml in the same directory where the code generator is executed and also predefines all options passed to oapi-codegen. This fits our usecase as we want to ensure that always the same kind of server is generated. But it might need more options in other use cases.
Basically all of this is heavily inspired by the templates and code which are already in oapi-codegen and just tries to follow the way oapi-codegen is written. But still its in an early phase and might not be perfect, yet.
Please let me know if you have any questions. I would be happy to answer them.
Yeah thanks, heaps for that @jotdl. Today I built in my auth stuff following the advice you gave in this comment.
This has worked to get me over the line with my direct requirement for sure, however, be nice to package this up in this repo.
I looked at the work you have done here and I quite like this approach.
I am wondering if @deepmap-marcinr has any input on how he would like the securitySchemes implementation to look for this package? And if this approach is worth finalizing?
One thing that would be nice is to be able to define a middleware that gets applied to the endpoint and then not having to do the following in the actual endpoint implementation;
Activity
tboerger commentedon Jan 8, 2020
I think #118 could be a solution because I can simply check within a middleware if one of the scopes is given.
tboerger commentedon Jan 8, 2020
My pr won't resolve that as I can't inject a middleware between context and handler :(
jotdl commentedon Jan 27, 2020
Hey, We are currently facing the same issue. We don't want to manually add a security validation to each method in the server interface and instead use a global security verification. We came up with an 2 step based approach:
ServerInterfaceWrapperstruct to contain afield, which is then called by each operation for each security (if this field is set), right before the actual domain method is called. If
securereturns an error the actual handler is never called.RegisterHandlersmethod to take a variable amount of option functions which can be used to modify theServerInterfaceWrapper. For now we would just generated aWithSecurityHandlerOption to set thesecurefield used in step 1. This way the RegisterHandlers method would stay backwards compatible but can be easily extended in the future. The generate code looks something like this:All the required modifications are already done (see https://github.com/jotdl/oapi-codegen/tree/feature/central-security ), I would just need to polish it, add some tests and open the PR.
What do you think about this solution? Does that sound like a useful solution to this problem? Is there interest for this solution in general?
I would be happy about any feedback and change request!
Thanks for your feedback!
utx0 commentedon Apr 28, 2020
Hey guys,
I am also looking into the problem right now. Am wondering @jotdl how did you go with that PR at all? Be also really great to see a demo implementation of this too. As for me, this is taking some research to work out how to apply securitySchemes into my API.
Anyway, let me know how I can help get this over the line.
jotdl commentedon Apr 28, 2020
Hi,
@lukekhamilton As I didn't get any feedback to the proposed change in this thread, the change is still on hold. But actually I iterated on this last week and came to a solution which doesn't require any changes to oapi-codegen at all, while still reducing maintenance effort to a minimum by relying on code generation:
As you probably know oapi-codegen generates a ServerInterface interface which contains one method for each of your endpoints. By using composition we could generate a wrapper for this interface which wraps each secured method and verifies security. This would look something like:
For methods/endpoints which need to be secured, we could go with something like this:
This way you stay compatible with the oapi-codegen generated API by reusing the ServerInterface interface and initialising a centralised security layer is as easy as:
As this doesn't require any changes to oapi-codegen (just a little bit more code on top), we dropped my previously suggested approach and went with this one. Once we completely migrated to this approache I will delete the code changes from my previous approach. But in general I would be happy about any feedback about this approach!
The same solution for chi-server should look very similar as it's using a ServerInterface interface there, too.
As oapi-codegen can be easily used as a library, we also generate all of this code in a very lightweight wrapper around oapi-codegen. It just took roughly 100 lines of Go to automate all of this. If you are interested in this I would be happy to share.
The only thing to make this even easier would be the opportunity to add additional code generation templates (not replacing existing ones) to oapi-codegen. I am not aware that this is already possible, but maybe it's worth considering. But except that, we are really happy with the current oapi-codegen API!
utx0 commentedon Apr 28, 2020
Hey @jotdl, thanks for all the info. I'll be sure to give this approach a try tomorrow.
I would also very much love to have a look at the wrapper approach you have put together too and see what I can learn/use here too.
From my understanding of the oapi-codegen codebase I dont think you can add custom/additional code generation templates that are implemented in a project namespace. I know this type of thing exist in the go-swagger approach from memory. Not really sure what it would take to make that possible here tho.
jotdl commentedon Apr 30, 2020
Hi,
Excuse my late reply. Please find below a sample version of the wrapper we are currently using for generating the security layer on top of what's already been generated by oapi codegen:
We currently invoke this with a
//go:generatecomment similar to this example//go:generate go run <pkg>/cmd/generators/server-gen > server.gen.goor run directly via
This script relies on having the schema.yaml in the same directory where the code generator is executed and also predefines all options passed to oapi-codegen. This fits our usecase as we want to ensure that always the same kind of server is generated. But it might need more options in other use cases.
Basically all of this is heavily inspired by the templates and code which are already in oapi-codegen and just tries to follow the way oapi-codegen is written. But still its in an early phase and might not be perfect, yet.
Please let me know if you have any questions. I would be happy to answer them.
utx0 commentedon Apr 30, 2020
Yeah thanks, heaps for that @jotdl. Today I built in my auth stuff following the advice you gave in this comment.
This has worked to get me over the line with my direct requirement for sure, however, be nice to package this up in this repo.
I looked at the work you have done here and I quite like this approach.
I am wondering if @deepmap-marcinr has any input on how he would like the
securitySchemesimplementation to look for this package? And if this approach is worth finalizing?utx0 commentedon Apr 30, 2020
One thing that would be nice is to be able to define a middleware that gets applied to the endpoint and then not having to do the following in the actual endpoint implementation;
mromaszewicz commentedon Jun 18, 2024
Since this bug was filed, we've created middleware to help with security validation, and also provided examples of how to use it.
tboerger commentedon Jun 18, 2024
Just the chi middleware is incomplete because it's lacking a working context set and get :)
tboerger commentedon Jun 18, 2024
I have worked around it with https://github.com/kleister/kleister-api/blob/7cae049b62f5872e86e03f04d32b936cc5528ed3/pkg/middleware/current/current.go and https://github.com/kleister/kleister-api/blob/7cae049b62f5872e86e03f04d32b936cc5528ed3/pkg/router/router.go#L309