danielgtaylor / huma

Huma REST/HTTP API Framework for Golang with OpenAPI 3.1
https://huma.rocks/
MIT License
1.87k stars 138 forks source link

Add clientId for OAuth 2.0 in code and redeem OAuth 2.0 bearer token through Swagger UI or Stoplight UI #500

Open m-mattia-m opened 1 month ago

m-mattia-m commented 1 month ago

Is there a possibility to define the client_id directly in the code, so I don't have to add it manually in the Swagger UI?

And I'm not sure about this, but I thought it would be nice if I could redeem a bearer token from my external OAuth2.0 provider (Zitadel) directly in the Swagger UI (or better, Stoplight). So I want to have an authorize button, that I can press, and I'll be redirected to my OAuth2.0 login page, and then be redirected back to my Swagger UI (or Stoplight), which stores the token for the requests. (I'm not sure if this also works with the PKCE workflow, but I know it works in Spring Boot with the password flow.) Is this possible yet and do you have an example for this?

(The OpenAPI documentation works, but how do I redeem a token?)

humaConfig.Components.SecuritySchemes = map[string]*huma.SecurityScheme{
    "MyApp": {
        Type: "oauth2",
        Flows: &huma.OAuthFlows{
            AuthorizationCode: &huma.OAuthFlow{
                AuthorizationURL: "https://zitadel.domain.com/oauth/v2/authorize",
                TokenURL:         "https://zitadel.domain.com/oauth/v2/token",
                RefreshURL:       "https://zitadel.domain.com/oauth/v2/token",
                Scopes: map[string]string{
                    "openid":         "",
                    "profile":        "",
                    "email":          "",
                    "offline_access": "",
                },
            },
        },
    },
}

router := gin.Default()
api := humagin.New(router, humaConfig)
danielgtaylor commented 1 month ago

@m-mattia-m your OpenAPI setup looks reasonable. You may want to ask in e.g. https://github.com/stoplightio/elements how to properly set it up to get the authorize/login button and then have it use the response. Many times (depending on provider) you will also need to allow access to your callback URLs.

m-mattia-m commented 1 month ago

@danielgtaylor Thank you for your answer. I have seen that Stoplights is planning to integrate full OAuth 2.0 and OIDC support. However, it's still on their roadmap as a feature request (it's been there for 3 years now, so I don't know if they'll implement it in the near future).

Implemented feature request (#316) about authentication with a note for OAuth 2.0 and OIDC Open feature request for OIDC (#421) Open feature request for OAuth 2.0 token generation #422

I'm going to try it with SwaggerUI.