swaggest / rest

Web services with OpenAPI and JSON Schema done quick in Go
https://pkg.go.dev/github.com/swaggest/rest
MIT License
362 stars 17 forks source link

How to handle JWT Tokens and oauth2? #109

Closed gobijan closed 1 year ago

gobijan commented 1 year ago

Hi first let me say thank you for building these awesome api toolkits (rest & openapi)! Great work :)

Right now I can't find out how describe that some endpoints are protected with JWT Bearer tokens and that I offer several URLs for oauth2 flows.

Are there any examples that show how to secure an API using swaggest/rest and generate the corresponding openapi specs etc?

vearutop commented 1 year ago

Thank you, I'm happy if this library helps!

Here is an example of security instrumentation: https://github.com/swaggest/rest/blob/v0.2.36/_examples/advanced-generic/router.go#L170-L189

    // Security middlewares.
    //  - sessMW is the actual request-level processor,
    //  - sessDoc is a handler-level wrapper to expose docs.
    sessMW := func(handler http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            if c, err := r.Cookie("sessid"); err == nil {
                r = r.WithContext(context.WithValue(r.Context(), "sessionID", c.Value))
            }
        })
    }

    sessDoc := nethttp.SecurityMiddleware(s.OpenAPICollector, "User", openapi3.SecurityScheme{
        APIKeySecurityScheme: &openapi3.APIKeySecurityScheme{
            In:   "cookie",
            Name: "sessid",
        },
    })

    // Security schema is configured for a single top-level route.
    s.With(sessMW, sessDoc).Method(http.MethodGet, "/root-with-session", nethttp.NewHandler(dummy()))

You can change APIKeySecuritySchema to HTTPSecurityScheme with BearerFormat JWT.

See another example.

                HTTPSecurityScheme: (&openapi3.HTTPSecurityScheme{}).
                    WithScheme("bearer").
                    WithBearerFormat("JWT").
                    WithDescription("Admin Access"),                    
vearutop commented 1 year ago

OAuth2 can be described with https://pkg.go.dev/github.com/swaggest/openapi-go/openapi3#OAuth2SecurityScheme, see also https://swagger.io/docs/specification/authentication/oauth2/.

gobijan commented 1 year ago

Thank you :)