Skip to content

Commit

Permalink
chore: add example for openapi/swagger authentication (#4004)
Browse files Browse the repository at this point in the history
  • Loading branch information
wangle201210 authored Dec 5, 2024
1 parent c0f2ef7 commit 5fa3341
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
9 changes: 9 additions & 0 deletions example/httpserver/swagger/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,14 @@ func main() {
new(Hello),
)
})
// if api.json requires authentication, add openApiBasicAuth handler
s.BindHookHandler(s.GetOpenApiPath(), ghttp.HookBeforeServe, openApiBasicAuth)
s.Run()
}

func openApiBasicAuth(r *ghttp.Request) {
if !r.BasicAuth("OpenApiAuthUserName", "OpenApiAuthPass", "Restricted") {
r.ExitAll()
return
}
}
5 changes: 5 additions & 0 deletions net/ghttp/ghttp_server_config_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,8 @@ func (s *Server) SetSwaggerUITemplate(swaggerUITemplate string) {
func (s *Server) SetOpenApiPath(path string) {
s.config.OpenApiPath = path
}

// GetOpenApiPath returns the configuration of `OpenApiPath` of server.
func (s *Server) GetOpenApiPath() string {
return s.config.OpenApiPath
}
25 changes: 25 additions & 0 deletions net/ghttp/ghttp_z_unit_feature_openapi_swagger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,3 +185,28 @@ func Test_OpenApi_Method_All_Swagger(t *testing.T) {
t.Assert(gstr.Contains(c.GetContent(ctx, "/api.json"), `/test/error`), true)
})
}

func Test_OpenApi_Auth(t *testing.T) {
s := g.Server(guid.S())
apiPath := "/api.json"
s.SetOpenApiPath(apiPath)
s.BindHookHandler(s.GetOpenApiPath(), ghttp.HookBeforeServe, openApiBasicAuth)
s.Start()
defer s.Shutdown()
gtest.C(t, func(t *gtest.T) {
t.Assert(s.GetOpenApiPath(), apiPath)
c := g.Client()
c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", s.GetListenedPort()))
t.Assert(c.GetContent(ctx, apiPath), "Unauthorized")
c.SetBasicAuth("OpenApiAuthUserName", "OpenApiAuthPass")
cc := c.GetContent(ctx, apiPath)
t.AssertNE(cc, "Unauthorized")
})
}

func openApiBasicAuth(r *ghttp.Request) {
if !r.BasicAuth("OpenApiAuthUserName", "OpenApiAuthPass", "Restricted") {
r.ExitAll()
return
}
}

0 comments on commit 5fa3341

Please sign in to comment.