Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(auth): add /auth/oidc/start endpoint for direct 302 OIDC login
sunmh95ddeae06798
diff --git a/docs/api/auth.md b/docs/api/auth.mdindex d65f607f6..8999914ed 100644--- a/docs/api/auth.md+++ b/docs/api/auth.md@@ -191,6 +191,24 @@ curl --location 'http://localhost:8080/api/v1/auth/oidc/url?redirect=%2Fdashboar---+## GET `/auth/oidc/start` - 发起 OIDC 登录(直接 302)++与 `/auth/oidc/url` 不同,此端点**直接 302 重定向**到 OIDC Provider 的授权页,不返回 JSON,因此无需前端 JS 介入。适用于外部平台(如企业门户 / Nexus)直接给出一个链接即可触发 OIDC 授权码流程,借助 IdP 的 SSO session 实现免再次输密码。++回调地址由后端根据请求自身的 origin(`<scheme>://<host>/api/v1/auth/oidc/callback`)自动构造,无需调用方提供。++**请求**:++```curl+curl --location 'http://localhost:8080/api/v1/auth/oidc/start'+```++**响应**:`302 Found`,`Location` 指向 IdP 授权页(含 `client_id` / `state` / `redirect_uri` / `scope`)。++> 登录成功后的回调行为与 `/auth/oidc/callback` 一致:302 回前端首页并把登录结果编码进 URL hash。当前登录后固定落到默认首页 `/platform/knowledge-bases`(直达指定业务页的 `next` 参数为未来扩展)。++---+## POST `/auth/refresh` - 刷新令牌**参数说明(请求体)**:diff --git a/internal/handler/auth.go b/internal/handler/auth.goindex b4370bafe..7696f035a 100644--- a/internal/handler/auth.go+++ b/internal/handler/auth.go@@ -287,15 +287,55 @@ func (h *AuthHandler) GetOIDCAuthorizationURL(c *gin.Context) {// Bind the state nonce to this browser so an attacker cannot replay// their own authorization code into a victim's callback.- if resp.Nonce != "" {- secure := c.Request.TLS != nil || strings.EqualFold(c.GetHeader("X-Forwarded-Proto"), "https")- c.SetSameSite(http.SameSiteLaxMode)- c.SetCookie(oidcNonceCookieName, resp.Nonce, oidcNonceCookieMaxAge, "/", "", secure, true)- }+ setOIDCNonceCookie(c, resp.Nonce)c.JSON(http.StatusOK, resp)}+// setOIDCNonceCookie binds the OIDC state nonce to this browser so an+// attacker cannot replay their own authorization code into a victim's+// callback. Shared by /auth/oidc/url (JSON) and /auth/oidc/start (302).+func setOIDCNonceCookie(c *gin.Context, nonce string) {+ if nonce == "" {+ return+ }+ secure := c.Request.TLS != nil || strings.EqualFold(c.GetHeader("X-Forwarded-Proto"), "https")+ c.SetSameSite(http.SameSiteLaxMode)+ c.SetCookie(oidcNonceCookieName, nonce, oidcNonceCookieMaxAge, "/", "", secure, true)+}++// oidcCallbackURL derives the absolute /auth/oidc/callback URL from the+// request's own origin (scheme + host), so external platforms can deep-link+// to /auth/oidc/start without supplying a redirect_uri.+func oidcCallbackURL(c *gin.Context) string {+ scheme := "http"+ if c.Request.TLS != nil || strings.EqualFold(c.GetHeader("X-Forwarded-Proto"), "https") {+ scheme = "https"+ }+ return scheme + "://" + c.Request.Host + "/api/v1/auth/oidc/callback"+}++// OIDCStart godoc+// @Summary 发起 OIDC 登录(直接 302)+// @Description 与 /auth/oidc/url 不同,此端点直接 302 重定向到 OIDC Provider 的授权页,+// @Description 无需前端 JS 介入。适用于外部平台(如企业门户)直接给出一个链接即可+// @Description 触发 OIDC 授权码流程,借助 IdP 的 SSO session 实现免再次输密码。+// @Tags 认证+// @Success 302+// @Router /auth/oidc/start [get]+func (h *AuthHandler) OIDCStart(c *gin.Context) {+ ctx := c.Request.Context()+ resp, err := h.userService.GetOIDCAuthorizationURL(ctx, oidcCallbackURL(c))+ if err != nil {+ logger.Errorf(ctx, "Failed to generate OIDC authorization URL: %v", err)+ appErr := errors.NewForbiddenError("OIDC authorization unavailable").WithDetails(err.Error())+ c.Error(appErr)+ return+ }+ setOIDCNonceCookie(c, resp.Nonce)+ c.Redirect(http.StatusFound, resp.AuthorizationURL)+}+// GetOIDCConfig godoc// @Summary 获取OIDC登录配置// @Description 返回OIDC是否启用以及provider展示名称,供前端决定是否展示OIDC登录入口diff --git a/internal/handler/auth_oidc_start_test.go b/internal/handler/auth_oidc_start_test.gonew file mode 100644index 000000000..1b7b2335f--- /dev/null+++ b/internal/handler/auth_oidc_start_test.go@@ -0,0 +1,123 @@+package handler++import (+ "context"+ "fmt"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/Tencent/WeKnora/internal/config"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/Tencent/WeKnora/internal/types/interfaces"+ "github.com/gin-gonic/gin"+)++// stubOIDCStartUserService only implements GetOIDCAuthorizationURL; every+// other UserService call panics via the nil interface embedding. Keeps the+// test focused on the OIDCStart handler's branching logic.+type stubOIDCStartUserService struct {+ interfaces.UserService+ getOIDCAuthorizationURL func(ctx context.Context, redirectURI string) (*types.OIDCAuthURLResponse, error)+}++func (s *stubOIDCStartUserService) GetOIDCAuthorizationURL(ctx context.Context, redirectURI string) (*types.OIDCAuthURLResponse, error) {+ return s.getOIDCAuthorizationURL(ctx, redirectURI)+}++func newOIDCStartTestRouter(h *AuthHandler) *gin.Engine {+ gin.SetMode(gin.TestMode)+ r := gin.New()+ r.Use(errorCapture())+ r.GET("/auth/oidc/start", h.OIDCStart)+ return r+}++// TestOIDCStart_RedirectsToAuthProvider: on success the handler must 302+// to the IdP authorization URL and bind the nonce via cookie (CSRF/replay+// defence), exactly like /auth/oidc/url.+func TestOIDCStart_RedirectsToAuthProvider(t *testing.T) {+ const authURL = "http://idp.example.com/authorize?client_id=weknora"+ us := &stubOIDCStartUserService{+ getOIDCAuthorizationURL: func(context.Context, string) (*types.OIDCAuthURLResponse, error) {+ return &types.OIDCAuthURLResponse{+ Success: true,+ AuthorizationURL: authURL,+ State: "state123",+ Nonce: "nonce456",+ }, nil+ },+ }+ h := NewAuthHandler(&config.Config{}, us, nil, nil, nil)+ r := newOIDCStartTestRouter(h)++ req := httptest.NewRequest(http.MethodGet, "/auth/oidc/start", nil)+ req.Host = "weknora.example.com"+ w := httptest.NewRecorder()+ r.ServeHTTP(w, req)++ if w.Code != http.StatusFound {+ t.Fatalf("status = %d, want 302", w.Code)+ }+ if loc := w.Header().Get("Location"); loc != authURL {+ t.Errorf("Location = %q, want %q", loc, authURL)+ }+ var hasNonce bool+ for _, ck := range w.Result().Cookies() {+ if ck.Name == oidcNonceCookieName && ck.Value == "nonce456" {+ hasNonce = true+ }+ }+ if !hasNonce {+ t.Errorf("expected %s cookie to be set with the nonce", oidcNonceCookieName)+ }+}++// TestOIDCStart_BuildsCallbackURLFromRequestOrigin: redirect_uri handed to+// the IdP is derived from the request's own origin (no caller-supplied+// value needed); X-Forwarded-Proto upgrades the scheme to https.+func TestOIDCStart_BuildsCallbackURLFromRequestOrigin(t *testing.T) {+ var captured string+ us := &stubOIDCStartUserService{+ getOIDCAuthorizationURL: func(_ context.Context, redirectURI string) (*types.OIDCAuthURLResponse, error) {+ captured = redirectURI+ return &types.OIDCAuthURLResponse{Success: true, AuthorizationURL: "http://idp", Nonce: "n"}, nil+ },+ }+ h := NewAuthHandler(&config.Config{}, us, nil, nil, nil)+ r := newOIDCStartTestRouter(h)++ req := httptest.NewRequest(http.MethodGet, "/auth/oidc/start", nil)+ req.Host = "weknora.example.com"+ req.Header.Set("X-Forwarded-Proto", "https")+ w := httptest.NewRecorder()+ r.ServeHTTP(w, req)++ const want = "https://weknora.example.com/api/v1/auth/oidc/callback"+ if captured != want {+ t.Errorf("callback URL passed to IdP = %q, want %q", captured, want)+ }+ if w.Code != http.StatusFound {+ t.Fatalf("status = %d, want 302", w.Code)+ }+}++// TestOIDCStart_ServiceErrorReturnsNonRedirect: if the IdP URL cannot be+// built, never 302 — surface the error the same way /auth/oidc/url does.+func TestOIDCStart_ServiceErrorReturnsNonRedirect(t *testing.T) {+ us := &stubOIDCStartUserService{+ getOIDCAuthorizationURL: func(context.Context, string) (*types.OIDCAuthURLResponse, error) {+ return nil, fmt.Errorf("idp unavailable")+ },+ }+ h := NewAuthHandler(&config.Config{}, us, nil, nil, nil)+ r := newOIDCStartTestRouter(h)++ req := httptest.NewRequest(http.MethodGet, "/auth/oidc/start", nil)+ w := httptest.NewRecorder()+ r.ServeHTTP(w, req)++ if w.Code == http.StatusFound {+ t.Fatalf("status = 302, want non-redirect on service error")+ }+}diff --git a/internal/middleware/auth.go b/internal/middleware/auth.goindex 2ea5a54ee..f9ac6f6a2 100644--- a/internal/middleware/auth.go+++ b/internal/middleware/auth.go@@ -49,6 +49,7 @@ var noAuthAPI = map[string][]string{"/api/v1/auth/config": {"GET"},"/api/v1/auth/oidc/config": {"GET"},"/api/v1/auth/oidc/url": {"GET"},+ "/api/v1/auth/oidc/start": {"GET"},"/api/v1/auth/oidc/callback": {"GET"},// MCP OAuth provider redirect: the third-party authorization server// redirects the browser here without a WeKnora bearer token. The requestdiff --git a/internal/router/routes_auth_tenant.go b/internal/router/routes_auth_tenant.goindex 86c9c44b1..cd5f55f10 100644--- a/internal/router/routes_auth_tenant.go+++ b/internal/router/routes_auth_tenant.go@@ -193,6 +193,8 @@ func RegisterAuthRoutes(r *gin.RouterGroup, handler *handler.AuthHandler, g *rbar.GET("/auth/oidc/config", handler.GetOIDCConfig)r.GET("/auth/oidc/url", handler.GetOIDCAuthorizationURL)r.GET("/auth/oidc/callback", handler.OIDCRedirectCallback)+ // /auth/oidc/start:直连 302 跳转到 OIDC 提供方,供前端无法走 JS 拉取 URL 的场景直接发起登录+ r.GET("/auth/oidc/start", handler.OIDCStart)r.POST("/auth/refresh", handler.RefreshToken)r.GET("/auth/validate", handler.ValidateToken)r.POST("/auth/logout", handler.Logout)