This is an automated email from the ASF dual-hosted git repository.

LinkinStars pushed a commit to branch fix/2.0.4/user
in repository https://gitbox.apache.org/repos/asf/answer.git

commit 444cd4e3aa01a693800beb130cdb6c6e4a7773d8
Author: LinkinStars <[email protected]>
AuthorDate: Fri Oct 30 17:01:31 2026 +0800

    fix(security): keep login tokens out of URLs
---
 cmd/wire_gen.go                                    |   7 +-
 docs/docs.go                                       |  66 +++++++++
 docs/swagger.json                                  |  66 +++++++++
 docs/swagger.yaml                                  |  41 ++++++
 internal/base/constant/cache_key.go                |   2 +
 internal/base/middleware/auth.go                   |   3 -
 .../base/middleware/auth_test.go                   |  38 ++---
 internal/controller/connector_controller.go        |  10 +-
 .../controller/login_handoff.go                    |  35 +++--
 internal/controller/login_handoff_test.go          | 156 +++++++++++++++++++++
 .../controller/plugin_user_center_controller.go    |  16 ++-
 internal/controller/user_controller.go             |  30 ++++
 internal/router/answer_api_router.go               |   1 +
 internal/schema/user_schema.go                     |  10 ++
 internal/service/auth/login_handoff.go             |  88 ++++++++++++
 internal/service/auth/login_handoff_test.go        | 136 ++++++++++++++++++
 internal/service/provider.go                       |   1 +
 ui/src/pages/Users/AuthCallback/index.tsx          |  26 +++-
 ui/src/services/common.ts                          |   7 +
 19 files changed, 684 insertions(+), 55 deletions(-)

diff --git a/cmd/wire_gen.go b/cmd/wire_gen.go
index 3445eaad..92b9cd1b 100644
--- a/cmd/wire_gen.go
+++ b/cmd/wire_gen.go
@@ -153,6 +153,7 @@ func initApplication(debug bool, serverConf *conf.Server, 
dbConf *data.Database,
        authRepo := auth.NewAuthRepo(dataData)
        apiKeyRepo := api_key.NewAPIKeyRepo(dataData)
        authService := auth2.NewAuthService(authRepo, apiKeyRepo)
+       loginHandoffService := auth2.NewLoginHandoffService(dataData)
        userRepo := user.NewUserRepo(dataData)
        uniqueIDRepo := unique.NewUniqueIDRepo(dataData)
        configRepo := config.NewConfigRepo(dataData)
@@ -194,7 +195,7 @@ func initApplication(debug bool, serverConf *conf.Server, 
dbConf *data.Database,
        userService := content.NewUserService(userRepo, userActiveActivityRepo, 
activityRepo, emailService, authService, siteInfoCommonService, 
userRoleRelService, userCommon, userExternalLoginService, 
userNotificationConfigRepo, userNotificationConfigService, questionCommon, 
eventqueueService, fileRecordService)
        captchaRepo := captcha.NewCaptchaRepo(dataData)
        captchaService := action.NewCaptchaService(captchaRepo)
-       userController := controller.NewUserController(authService, 
userService, captchaService, emailService, siteInfoCommonService, 
userNotificationConfigService)
+       userController := controller.NewUserController(authService, 
userService, captchaService, emailService, siteInfoCommonService, 
userNotificationConfigService, loginHandoffService)
        commentRepo := comment.NewCommentRepo(dataData, uniqueIDRepo)
        commentCommonRepo := comment.NewCommentCommonRepo(dataData, 
uniqueIDRepo)
        objService := object_info.NewObjService(answerRepo, questionRepo, 
commentCommonRepo, tagCommonRepo, tagCommonService)
@@ -302,9 +303,9 @@ func initApplication(debug bool, serverConf *conf.Server, 
dbConf *data.Database,
        templateRenderController := 
templaterender.NewTemplateRenderController(questionService, userService, 
tagService, answerService, commentService, siteInfoCommonService, questionRepo)
        templateController := 
controller.NewTemplateController(templateRenderController, 
siteInfoCommonService, eventqueueService, userService, questionService)
        templateRouter := router.NewTemplateRouter(templateController, 
templateRenderController, siteInfoController, authUserMiddleware)
-       connectorController := 
controller.NewConnectorController(siteInfoCommonService, emailService, 
userExternalLoginService)
+       connectorController := 
controller.NewConnectorController(siteInfoCommonService, emailService, 
userExternalLoginService, loginHandoffService)
        userCenterLoginService := 
user_external_login2.NewUserCenterLoginService(userRepo, userCommon, 
userExternalLoginRepo, userActiveActivityRepo, siteInfoCommonService)
-       userCenterController := 
controller.NewUserCenterController(userCenterLoginService, 
siteInfoCommonService)
+       userCenterController := 
controller.NewUserCenterController(userCenterLoginService, 
siteInfoCommonService, loginHandoffService)
        captchaController := controller.NewCaptchaController()
        embedController := controller.NewEmbedController()
        renderController := controller.NewRenderController()
diff --git a/docs/docs.go b/docs/docs.go
index 4e48c88d..16accbe4 100644
--- a/docs/docs.go
+++ b/docs/docs.go
@@ -7546,6 +7546,52 @@ const docTemplate = `{
                 }
             }
         },
+        "/answer/api/v1/user/login/handoff": {
+            "post": {
+                "description": "Exchange a short-lived, one-time login handoff 
code for an access token",
+                "consumes": [
+                    "application/json"
+                ],
+                "produces": [
+                    "application/json"
+                ],
+                "tags": [
+                    "User"
+                ],
+                "summary": "Exchange a login handoff code",
+                "parameters": [
+                    {
+                        "description": "Login handoff code",
+                        "name": "data",
+                        "in": "body",
+                        "required": true,
+                        "schema": {
+                            "$ref": 
"#/definitions/schema.LoginHandoffExchangeReq"
+                        }
+                    }
+                ],
+                "responses": {
+                    "200": {
+                        "description": "OK",
+                        "schema": {
+                            "allOf": [
+                                {
+                                    "$ref": "#/definitions/handler.RespBody"
+                                },
+                                {
+                                    "type": "object",
+                                    "properties": {
+                                        "data": {
+                                            "$ref": 
"#/definitions/schema.LoginHandoffExchangeResp"
+                                        }
+                                    }
+                                }
+                            ]
+                        }
+                    }
+                }
+            }
+        },
         "/answer/api/v1/user/logout": {
             "get": {
                 "security": [
@@ -10832,6 +10878,26 @@ const docTemplate = `{
                 }
             }
         },
+        "schema.LoginHandoffExchangeReq": {
+            "type": "object",
+            "required": [
+                "code"
+            ],
+            "properties": {
+                "code": {
+                    "type": "string",
+                    "maxLength": 128
+                }
+            }
+        },
+        "schema.LoginHandoffExchangeResp": {
+            "type": "object",
+            "properties": {
+                "access_token": {
+                    "type": "string"
+                }
+            }
+        },
         "schema.NotificationChannelConfig": {
             "type": "object",
             "properties": {
diff --git a/docs/swagger.json b/docs/swagger.json
index a075dfe4..01e97612 100644
--- a/docs/swagger.json
+++ b/docs/swagger.json
@@ -7519,6 +7519,52 @@
                 }
             }
         },
+        "/answer/api/v1/user/login/handoff": {
+            "post": {
+                "description": "Exchange a short-lived, one-time login handoff 
code for an access token",
+                "consumes": [
+                    "application/json"
+                ],
+                "produces": [
+                    "application/json"
+                ],
+                "tags": [
+                    "User"
+                ],
+                "summary": "Exchange a login handoff code",
+                "parameters": [
+                    {
+                        "description": "Login handoff code",
+                        "name": "data",
+                        "in": "body",
+                        "required": true,
+                        "schema": {
+                            "$ref": 
"#/definitions/schema.LoginHandoffExchangeReq"
+                        }
+                    }
+                ],
+                "responses": {
+                    "200": {
+                        "description": "OK",
+                        "schema": {
+                            "allOf": [
+                                {
+                                    "$ref": "#/definitions/handler.RespBody"
+                                },
+                                {
+                                    "type": "object",
+                                    "properties": {
+                                        "data": {
+                                            "$ref": 
"#/definitions/schema.LoginHandoffExchangeResp"
+                                        }
+                                    }
+                                }
+                            ]
+                        }
+                    }
+                }
+            }
+        },
         "/answer/api/v1/user/logout": {
             "get": {
                 "security": [
@@ -10805,6 +10851,26 @@
                 }
             }
         },
+        "schema.LoginHandoffExchangeReq": {
+            "type": "object",
+            "required": [
+                "code"
+            ],
+            "properties": {
+                "code": {
+                    "type": "string",
+                    "maxLength": 128
+                }
+            }
+        },
+        "schema.LoginHandoffExchangeResp": {
+            "type": "object",
+            "properties": {
+                "access_token": {
+                    "type": "string"
+                }
+            }
+        },
         "schema.NotificationChannelConfig": {
             "type": "object",
             "properties": {
diff --git a/docs/swagger.yaml b/docs/swagger.yaml
index b3416a10..01224117 100644
--- a/docs/swagger.yaml
+++ b/docs/swagger.yaml
@@ -1648,6 +1648,19 @@ definitions:
       text:
         type: string
     type: object
+  schema.LoginHandoffExchangeReq:
+    properties:
+      code:
+        maxLength: 128
+        type: string
+    required:
+    - code
+    type: object
+  schema.LoginHandoffExchangeResp:
+    properties:
+      access_token:
+        type: string
+    type: object
   schema.NotificationChannelConfig:
     properties:
       enable:
@@ -7988,6 +8001,34 @@ paths:
       summary: UserEmailLogin
       tags:
       - User
+  /answer/api/v1/user/login/handoff:
+    post:
+      consumes:
+      - application/json
+      description: Exchange a short-lived, one-time login handoff code for an 
access
+        token
+      parameters:
+      - description: Login handoff code
+        in: body
+        name: data
+        required: true
+        schema:
+          $ref: '#/definitions/schema.LoginHandoffExchangeReq'
+      produces:
+      - application/json
+      responses:
+        "200":
+          description: OK
+          schema:
+            allOf:
+            - $ref: '#/definitions/handler.RespBody'
+            - properties:
+                data:
+                  $ref: '#/definitions/schema.LoginHandoffExchangeResp'
+              type: object
+      summary: Exchange a login handoff code
+      tags:
+      - User
   /answer/api/v1/user/logout:
     get:
       consumes:
diff --git a/internal/base/constant/cache_key.go 
b/internal/base/constant/cache_key.go
index ab278cc0..7874bcf2 100644
--- a/internal/base/constant/cache_key.go
+++ b/internal/base/constant/cache_key.go
@@ -45,6 +45,8 @@ const (
        ConnectorOAuthStateCacheKey                = 
"answer:connector:oauth-state:"
        ConnectorOAuthStateCacheTime               = 10 * time.Minute
        ConnectorOAuthBindStateCacheTime           = 5 * time.Minute
+       LoginHandoffCacheKey                       = "answer:login:handoff:"
+       LoginHandoffCacheTime                      = time.Minute
        SiteMapQuestionCacheKeyPrefix              = 
"answer:sitemap:question:%d"
        SiteMapQuestionCacheTime                   = time.Hour
        SitemapMaxSize                             = 50000
diff --git a/internal/base/middleware/auth.go b/internal/base/middleware/auth.go
index bb4cf255..9f6ada3c 100644
--- a/internal/base/middleware/auth.go
+++ b/internal/base/middleware/auth.go
@@ -320,8 +320,5 @@ func GetLoginUserIDInt64FromContext(ctx *gin.Context) 
(userID int64) {
 // ExtractToken extract token from context
 func ExtractToken(ctx *gin.Context) (token string) {
        token = ctx.GetHeader("Authorization")
-       if len(token) == 0 {
-               token = ctx.Query("Authorization")
-       }
        return strings.TrimPrefix(token, "Bearer ")
 }
diff --git a/ui/src/pages/Users/AuthCallback/index.tsx 
b/internal/base/middleware/auth_test.go
similarity index 55%
copy from ui/src/pages/Users/AuthCallback/index.tsx
copy to internal/base/middleware/auth_test.go
index 3218c7c1..c28e46e7 100644
--- a/ui/src/pages/Users/AuthCallback/index.tsx
+++ b/internal/base/middleware/auth_test.go
@@ -17,25 +17,25 @@
  * under the License.
  */
 
-import { FC, memo, useEffect } from 'react';
-import { useTranslation } from 'react-i18next';
-import { useSearchParams, useNavigate } from 'react-router-dom';
+package middleware
 
-import { usePageTags } from '@/hooks';
-import { guard } from '@/utils';
+import (
+       "net/http/httptest"
+       "testing"
 
-const Index: FC = () => {
-  const { t } = useTranslation('translation', { keyPrefix: 'page_title' });
-  const [searchParams] = useSearchParams();
-  const navigate = useNavigate();
-  useEffect(() => {
-    const token = searchParams.get('access_token');
-    guard.handleLoginWithToken(token, navigate);
-  }, []);
-  usePageTags({
-    title: t('oauth_callback'),
-  });
-  return null;
-};
+       "github.com/gin-gonic/gin"
+)
 
-export default memo(Index);
+func TestExtractTokenDoesNotReadQueryParameters(t *testing.T) {
+       gin.SetMode(gin.TestMode)
+       ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
+       ctx.Request = httptest.NewRequest("GET", 
"/?Authorization=Bearer%20query-token", nil)
+       if token := ExtractToken(ctx); token != "" {
+               t.Fatalf("query token was accepted: %q", token)
+       }
+
+       ctx.Request.Header.Set("Authorization", "Bearer header-token")
+       if token := ExtractToken(ctx); token != "header-token" {
+               t.Fatalf("header token = %q, want header-token", token)
+       }
+}
diff --git a/internal/controller/connector_controller.go 
b/internal/controller/connector_controller.go
index 28aa5fc6..08d3df1b 100644
--- a/internal/controller/connector_controller.go
+++ b/internal/controller/connector_controller.go
@@ -27,6 +27,7 @@ import (
        "github.com/apache/answer/internal/base/handler"
        "github.com/apache/answer/internal/base/middleware"
        "github.com/apache/answer/internal/schema"
+       "github.com/apache/answer/internal/service/auth"
        "github.com/apache/answer/internal/service/export"
        "github.com/apache/answer/internal/service/siteinfo_common"
        "github.com/apache/answer/internal/service/user_external_login"
@@ -46,6 +47,7 @@ type ConnectorController struct {
        siteInfoService     siteinfo_common.SiteInfoCommonService
        userExternalService *user_external_login.UserExternalLoginService
        emailService        *export.EmailService
+       loginHandoffService *auth.LoginHandoffService
 }
 
 // NewConnectorController new controller
@@ -53,11 +55,13 @@ func NewConnectorController(
        siteInfoService siteinfo_common.SiteInfoCommonService,
        emailService *export.EmailService,
        userExternalService *user_external_login.UserExternalLoginService,
+       loginHandoffService *auth.LoginHandoffService,
 ) *ConnectorController {
        return &ConnectorController{
                siteInfoService:     siteInfoService,
                userExternalService: userExternalService,
                emailService:        emailService,
+               loginHandoffService: loginHandoffService,
        }
 }
 
@@ -195,8 +199,10 @@ func (cc *ConnectorController) ConnectorRedirect(connector 
plugin.Connector) (fn
                        return
                }
                if len(resp.AccessToken) > 0 {
-                       ctx.Redirect(http.StatusFound, 
fmt.Sprintf("%s/users/auth-landing?access_token=%s",
-                               siteGeneral.SiteUrl, resp.AccessToken))
+                       if err := redirectToAuthLanding(ctx, 
siteGeneral.SiteUrl, cc.loginHandoffService, resp.AccessToken); err != nil {
+                               log.Errorf("create login handoff failed: %v", 
err)
+                               ctx.Redirect(http.StatusFound, "/50x")
+                       }
                } else {
                        ctx.Redirect(http.StatusFound, 
fmt.Sprintf("%s/users/confirm-email?binding_key=%s",
                                siteGeneral.SiteUrl, resp.BindingKey))
diff --git a/ui/src/pages/Users/AuthCallback/index.tsx 
b/internal/controller/login_handoff.go
similarity index 55%
copy from ui/src/pages/Users/AuthCallback/index.tsx
copy to internal/controller/login_handoff.go
index 3218c7c1..46f81a13 100644
--- a/ui/src/pages/Users/AuthCallback/index.tsx
+++ b/internal/controller/login_handoff.go
@@ -17,25 +17,22 @@
  * under the License.
  */
 
-import { FC, memo, useEffect } from 'react';
-import { useTranslation } from 'react-i18next';
-import { useSearchParams, useNavigate } from 'react-router-dom';
+package controller
 
-import { usePageTags } from '@/hooks';
-import { guard } from '@/utils';
+import (
+       "fmt"
+       "net/http"
 
-const Index: FC = () => {
-  const { t } = useTranslation('translation', { keyPrefix: 'page_title' });
-  const [searchParams] = useSearchParams();
-  const navigate = useNavigate();
-  useEffect(() => {
-    const token = searchParams.get('access_token');
-    guard.handleLoginWithToken(token, navigate);
-  }, []);
-  usePageTags({
-    title: t('oauth_callback'),
-  });
-  return null;
-};
+       "github.com/apache/answer/internal/service/auth"
+       "github.com/gin-gonic/gin"
+)
 
-export default memo(Index);
+func redirectToAuthLanding(ctx *gin.Context, siteURL string, 
loginHandoffService *auth.LoginHandoffService, accessToken string) error {
+       code, err := loginHandoffService.Create(ctx, accessToken)
+       if err != nil {
+               return err
+       }
+       ctx.Header("Cache-Control", "no-store")
+       ctx.Redirect(http.StatusFound, 
fmt.Sprintf("%s/users/auth-landing#code=%s", siteURL, code))
+       return nil
+}
diff --git a/internal/controller/login_handoff_test.go 
b/internal/controller/login_handoff_test.go
new file mode 100644
index 00000000..58f095bb
--- /dev/null
+++ b/internal/controller/login_handoff_test.go
@@ -0,0 +1,156 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package controller
+
+import (
+       "context"
+       "encoding/json"
+       "net/http"
+       "net/http/httptest"
+       "net/url"
+       "strings"
+       "testing"
+
+       "github.com/apache/answer/internal/base/data"
+       "github.com/apache/answer/internal/service/auth"
+       "github.com/gin-gonic/gin"
+)
+
+func TestRedirectToAuthLandingDoesNotExposeAccessToken(t *testing.T) {
+       gin.SetMode(gin.TestMode)
+       cache, cleanup, err := data.NewCache(&data.CacheConf{})
+       if err != nil {
+               t.Fatal(err)
+       }
+       t.Cleanup(cleanup)
+
+       service := auth.NewLoginHandoffService(&data.Data{Cache: cache})
+       const accessToken = "session-token-that-must-not-appear-in-location"
+       w := httptest.NewRecorder()
+       ctx, _ := gin.CreateTestContext(w)
+       ctx.Request = httptest.NewRequest(http.MethodGet, "/callback", nil)
+
+       if err := redirectToAuthLanding(ctx, "https://answer.example";, service, 
accessToken); err != nil {
+               t.Fatal(err)
+       }
+       location := w.Header().Get("Location")
+       if strings.Contains(location, accessToken) || 
strings.Contains(location, "?") {
+               t.Fatalf("redirect exposes access token in URL: %q", location)
+       }
+       if !strings.HasPrefix(location, 
"https://answer.example/users/auth-landing#code=";) {
+               t.Fatalf("unexpected redirect location: %q", location)
+       }
+       if w.Header().Get("Cache-Control") != "no-store" {
+               t.Fatalf("Cache-Control = %q, want no-store", 
w.Header().Get("Cache-Control"))
+       }
+}
+
+func TestExchangeLoginHandoffReturnsTokenOnceAndDoesNotCacheResponse(t 
*testing.T) {
+       gin.SetMode(gin.TestMode)
+       cache, cleanup, err := data.NewCache(&data.CacheConf{})
+       if err != nil {
+               t.Fatal(err)
+       }
+       t.Cleanup(cleanup)
+
+       service := auth.NewLoginHandoffService(&data.Data{Cache: cache})
+       const accessToken = "session-token-only-in-post-body"
+       code, err := service.Create(context.Background(), accessToken)
+       if err != nil {
+               t.Fatal(err)
+       }
+       controller := &UserController{loginHandoffService: service}
+       router := gin.New()
+       router.POST("/handoff", controller.ExchangeLoginHandoff)
+
+       req := httptest.NewRequest(http.MethodPost, "/handoff", 
strings.NewReader(`{"code":"`+code+`"}`))
+       req.Header.Set("Content-Type", "application/json")
+       w := httptest.NewRecorder()
+       router.ServeHTTP(w, req)
+       if w.Code != http.StatusOK {
+               t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
+       }
+       if w.Header().Get("Cache-Control") != "no-store" {
+               t.Fatalf("Cache-Control = %q, want no-store", 
w.Header().Get("Cache-Control"))
+       }
+       var response struct {
+               Data struct {
+                       AccessToken string `json:"access_token"`
+               } `json:"data"`
+       }
+       if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
+               t.Fatal(err)
+       }
+       if response.Data.AccessToken != accessToken {
+               t.Fatalf("access token = %q, want %q", 
response.Data.AccessToken, accessToken)
+       }
+
+       req = httptest.NewRequest(http.MethodPost, "/handoff", 
strings.NewReader(`{"code":"`+code+`"}`))
+       req.Header.Set("Content-Type", "application/json")
+       w = httptest.NewRecorder()
+       router.ServeHTTP(w, req)
+       if w.Code != http.StatusBadRequest {
+               t.Fatalf("second exchange status = %d, body = %s", w.Code, 
w.Body.String())
+       }
+}
+
+func TestAuthLandingHandoffFlow(t *testing.T) {
+       gin.SetMode(gin.TestMode)
+       cache, cleanup, err := data.NewCache(&data.CacheConf{})
+       if err != nil {
+               t.Fatal(err)
+       }
+       t.Cleanup(cleanup)
+
+       service := auth.NewLoginHandoffService(&data.Data{Cache: cache})
+       const accessToken = "session-token-returned-only-by-exchange"
+       redirectWriter := httptest.NewRecorder()
+       redirectContext, _ := gin.CreateTestContext(redirectWriter)
+       redirectContext.Request = httptest.NewRequest(http.MethodGet, 
"/callback", nil)
+       if err := redirectToAuthLanding(redirectContext, 
"https://answer.example";, service, accessToken); err != nil {
+               t.Fatal(err)
+       }
+       location, err := url.Parse(redirectWriter.Header().Get("Location"))
+       if err != nil {
+               t.Fatal(err)
+       }
+       if code := location.Query().Get("code"); code != "" {
+               t.Fatalf("handoff code must not be in query: %q", 
location.String())
+       }
+       fragment, err := url.ParseQuery(location.Fragment)
+       if err != nil {
+               t.Fatal(err)
+       }
+       code := fragment.Get("code")
+       if code == "" {
+               t.Fatalf("handoff code missing from fragment: %q", 
location.String())
+       }
+
+       controller := &UserController{loginHandoffService: service}
+       router := gin.New()
+       router.POST("/handoff", controller.ExchangeLoginHandoff)
+       req := httptest.NewRequest(http.MethodPost, "/handoff", 
strings.NewReader(`{"code":"`+code+`"}`))
+       req.Header.Set("Content-Type", "application/json")
+       w := httptest.NewRecorder()
+       router.ServeHTTP(w, req)
+       if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), 
accessToken) {
+               t.Fatalf("handoff exchange failed: status=%d body=%s", w.Code, 
w.Body.String())
+       }
+}
diff --git a/internal/controller/plugin_user_center_controller.go 
b/internal/controller/plugin_user_center_controller.go
index d426f45d..4c1e3593 100644
--- a/internal/controller/plugin_user_center_controller.go
+++ b/internal/controller/plugin_user_center_controller.go
@@ -26,6 +26,7 @@ import (
        "github.com/apache/answer/internal/base/handler"
        "github.com/apache/answer/internal/base/middleware"
        "github.com/apache/answer/internal/schema"
+       "github.com/apache/answer/internal/service/auth"
        "github.com/apache/answer/internal/service/siteinfo_common"
        "github.com/apache/answer/internal/service/user_external_login"
        "github.com/apache/answer/plugin"
@@ -42,16 +43,19 @@ const (
 type UserCenterController struct {
        userCenterLoginService *user_external_login.UserCenterLoginService
        siteInfoService        siteinfo_common.SiteInfoCommonService
+       loginHandoffService    *auth.LoginHandoffService
 }
 
 // NewUserCenterController new controller
 func NewUserCenterController(
        userCenterLoginService *user_external_login.UserCenterLoginService,
        siteInfoService siteinfo_common.SiteInfoCommonService,
+       loginHandoffService *auth.LoginHandoffService,
 ) *UserCenterController {
        return &UserCenterController{
                userCenterLoginService: userCenterLoginService,
                siteInfoService:        siteInfoService,
+               loginHandoffService:    loginHandoffService,
        }
 }
 
@@ -162,8 +166,10 @@ func (uc *UserCenterController) 
UserCenterLoginCallback(ctx *gin.Context) {
                return
        }
        userCenter.AfterLogin(userInfo.ExternalID, resp.AccessToken)
-       ctx.Redirect(http.StatusFound, 
fmt.Sprintf("%s/users/auth-landing?access_token=%s",
-               siteGeneral.SiteUrl, resp.AccessToken))
+       if err := redirectToAuthLanding(ctx, siteGeneral.SiteUrl, 
uc.loginHandoffService, resp.AccessToken); err != nil {
+               log.Errorf("create login handoff failed: %v", err)
+               ctx.Redirect(http.StatusFound, "/50x")
+       }
 }
 
 func (uc *UserCenterController) UserCenterSignUpCallback(ctx *gin.Context) {
@@ -197,8 +203,10 @@ func (uc *UserCenterController) 
UserCenterSignUpCallback(ctx *gin.Context) {
                return
        }
        userCenter.AfterLogin(userInfo.ExternalID, resp.AccessToken)
-       ctx.Redirect(http.StatusFound, 
fmt.Sprintf("%s/users/auth-landing?access_token=%s",
-               siteGeneral.SiteUrl, resp.AccessToken))
+       if err := redirectToAuthLanding(ctx, siteGeneral.SiteUrl, 
uc.loginHandoffService, resp.AccessToken); err != nil {
+               log.Errorf("create login handoff failed: %v", err)
+               ctx.Redirect(http.StatusFound, "/50x")
+       }
 }
 
 // UserCenterUserSettings user center user settings
diff --git a/internal/controller/user_controller.go 
b/internal/controller/user_controller.go
index 531d88b4..75817209 100644
--- a/internal/controller/user_controller.go
+++ b/internal/controller/user_controller.go
@@ -50,6 +50,7 @@ type UserController struct {
        emailService                  *export.EmailService
        siteInfoCommonService         siteinfo_common.SiteInfoCommonService
        userNotificationConfigService 
*user_notification_config.UserNotificationConfigService
+       loginHandoffService           *auth.LoginHandoffService
 }
 
 // NewUserController new controller
@@ -60,6 +61,7 @@ func NewUserController(
        emailService *export.EmailService,
        siteInfoCommonService siteinfo_common.SiteInfoCommonService,
        userNotificationConfigService 
*user_notification_config.UserNotificationConfigService,
+       loginHandoffService *auth.LoginHandoffService,
 ) *UserController {
        return &UserController{
                authService:                   authService,
@@ -68,9 +70,37 @@ func NewUserController(
                emailService:                  emailService,
                siteInfoCommonService:         siteInfoCommonService,
                userNotificationConfigService: userNotificationConfigService,
+               loginHandoffService:           loginHandoffService,
        }
 }
 
+// ExchangeLoginHandoff exchanges a short-lived, one-time login handoff code 
for an access token.
+// @Summary Exchange a login handoff code
+// @Description Exchange a short-lived, one-time login handoff code for an 
access token
+// @Tags User
+// @Accept json
+// @Produce json
+// @Param data body schema.LoginHandoffExchangeReq true "Login handoff code"
+// @Success 200 {object} handler.RespBody{data=schema.LoginHandoffExchangeResp}
+// @Router /answer/api/v1/user/login/handoff [post]
+func (uc *UserController) ExchangeLoginHandoff(ctx *gin.Context) {
+       req := &schema.LoginHandoffExchangeReq{}
+       if handler.BindAndCheck(ctx, req) {
+               return
+       }
+       accessToken, exists, err := uc.loginHandoffService.Consume(ctx, 
req.Code)
+       if err != nil {
+               handler.HandleResponse(ctx, err, nil)
+               return
+       }
+       if !exists {
+               handler.HandleResponse(ctx, 
errors.BadRequest(reason.RequestFormatError), nil)
+               return
+       }
+       ctx.Header("Cache-Control", "no-store")
+       handler.HandleResponse(ctx, nil, 
&schema.LoginHandoffExchangeResp{AccessToken: accessToken})
+}
+
 // GetUserInfoByUserID get user info, if user no login response http code is 
200, but user info is null
 // @Summary GetUserInfoByUserID
 // @Description get user info, if user no login response http code is 200, but 
user info is null
diff --git a/internal/router/answer_api_router.go 
b/internal/router/answer_api_router.go
index 84b8b4e1..ae03027e 100644
--- a/internal/router/answer_api_router.go
+++ b/internal/router/answer_api_router.go
@@ -151,6 +151,7 @@ func (a *AnswerAPIRouter) 
RegisterMustUnAuthAnswerAPIRouter(authUserMiddleware *
 
        // user
        r.GET("/user/info", a.userController.GetUserInfoByUserID)
+       r.POST("/user/login/handoff", a.userController.ExchangeLoginHandoff)
        r.GET("/user/action/record", authUserMiddleware.Auth(), 
a.userController.ActionRecord)
        routerGroup := r.Group("", middleware.BanAPIForUserCenter)
        routerGroup.POST("/user/login/email", a.userController.UserEmailLogin)
diff --git a/internal/schema/user_schema.go b/internal/schema/user_schema.go
index 0683a5af..c5f4cb37 100644
--- a/internal/schema/user_schema.go
+++ b/internal/schema/user_schema.go
@@ -103,6 +103,16 @@ type UserLoginResp struct {
        SuspendedUntil int64 `json:"suspended_until"`
 }
 
+// LoginHandoffExchangeReq exchanges a short-lived authentication handoff code.
+type LoginHandoffExchangeReq struct {
+       Code string `json:"code" validate:"required,gt=0,lte=128"`
+}
+
+// LoginHandoffExchangeResp contains the access token after a successful 
exchange.
+type LoginHandoffExchangeResp struct {
+       AccessToken string `json:"access_token"`
+}
+
 func (r *UserLoginResp) ConvertFromUserEntity(userInfo *entity.User) {
        _ = copier.Copy(r, userInfo)
        r.CreatedAt = userInfo.CreatedAt.Unix()
diff --git a/internal/service/auth/login_handoff.go 
b/internal/service/auth/login_handoff.go
new file mode 100644
index 00000000..8676af3d
--- /dev/null
+++ b/internal/service/auth/login_handoff.go
@@ -0,0 +1,88 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package auth
+
+import (
+       "context"
+       "crypto/rand"
+       "encoding/base64"
+       "sync"
+
+       "github.com/apache/answer/internal/base/constant"
+       "github.com/apache/answer/internal/base/data"
+       "github.com/apache/answer/internal/base/reason"
+       "github.com/segmentfault/pacman/errors"
+)
+
+type atomicStringConsumer interface {
+       ConsumeString(ctx context.Context, key string) (data string, exist 
bool, err error)
+}
+
+// LoginHandoffService exchanges a short-lived, one-time code for an access 
token.
+// Cache backends that implement atomicStringConsumer provide cross-process
+// single-use semantics. The mutex protects the built-in in-memory cache.
+type LoginHandoffService struct {
+       data *data.Data
+       mu   sync.Mutex
+}
+
+func NewLoginHandoffService(data *data.Data) *LoginHandoffService {
+       return &LoginHandoffService{data: data}
+}
+
+// Create stores an access token behind an opaque short-lived code.
+func (s *LoginHandoffService) Create(ctx context.Context, accessToken string) 
(string, error) {
+       codeBytes := make([]byte, 32)
+       if _, err := rand.Read(codeBytes); err != nil {
+               return "", 
errors.InternalServer(reason.UnknownError).WithError(err).WithStack()
+       }
+       code := base64.RawURLEncoding.EncodeToString(codeBytes)
+       if err := s.data.Cache.SetString(ctx, 
constant.LoginHandoffCacheKey+code, accessToken, 
constant.LoginHandoffCacheTime); err != nil {
+               return "", 
errors.InternalServer(reason.DatabaseError).WithError(err).WithStack()
+       }
+       return code, nil
+}
+
+// Consume returns the token for code once. Expired, unknown, and already-used
+// codes all return exists=false without disclosing which condition occurred.
+func (s *LoginHandoffService) Consume(ctx context.Context, code string) 
(accessToken string, exists bool, err error) {
+       if len(code) == 0 {
+               return "", false, nil
+       }
+
+       key := constant.LoginHandoffCacheKey + code
+       if consumer, ok := s.data.Cache.(atomicStringConsumer); ok {
+               accessToken, exists, err = consumer.ConsumeString(ctx, key)
+       } else {
+               s.mu.Lock()
+               defer s.mu.Unlock()
+               accessToken, exists, err = s.data.Cache.GetString(ctx, key)
+               if err == nil && exists {
+                       err = s.data.Cache.Del(ctx, key)
+               }
+       }
+       if err != nil {
+               return "", false, 
errors.InternalServer(reason.DatabaseError).WithError(err).WithStack()
+       }
+       if !exists {
+               return "", false, nil
+       }
+       return accessToken, true, nil
+}
diff --git a/internal/service/auth/login_handoff_test.go 
b/internal/service/auth/login_handoff_test.go
new file mode 100644
index 00000000..2f8f939a
--- /dev/null
+++ b/internal/service/auth/login_handoff_test.go
@@ -0,0 +1,136 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package auth
+
+import (
+       "context"
+       "strings"
+       "sync"
+       "testing"
+
+       "github.com/apache/answer/internal/base/data"
+       "github.com/segmentfault/pacman/cache"
+)
+
+type atomicTestCache struct {
+       cache.Cache
+       consumeCalled bool
+}
+
+func (c *atomicTestCache) ConsumeString(ctx context.Context, key string) 
(string, bool, error) {
+       c.consumeCalled = true
+       value, exists, err := c.GetString(ctx, key)
+       if err != nil || !exists {
+               return value, exists, err
+       }
+       return value, true, c.Del(ctx, key)
+}
+
+func TestLoginHandoffServiceConsumesCodeOnlyOnce(t *testing.T) {
+       cache, cleanup, err := data.NewCache(&data.CacheConf{})
+       if err != nil {
+               t.Fatal(err)
+       }
+       t.Cleanup(cleanup)
+
+       service := NewLoginHandoffService(&data.Data{Cache: cache})
+       const accessToken = "long-lived-session-token"
+       code, err := service.Create(context.Background(), accessToken)
+       if err != nil {
+               t.Fatal(err)
+       }
+       if code == "" || strings.Contains(code, accessToken) {
+               t.Fatalf("handoff code must be opaque: %q", code)
+       }
+
+       got, exists, err := service.Consume(context.Background(), code)
+       if err != nil || !exists || got != accessToken {
+               t.Fatalf("first consume = (%q, %v, %v), want (%q, true, nil)", 
got, exists, err, accessToken)
+       }
+
+       got, exists, err = service.Consume(context.Background(), code)
+       if err != nil || exists || got != "" {
+               t.Fatalf("second consume = (%q, %v, %v), want (empty, false, 
nil)", got, exists, err)
+       }
+}
+
+func TestLoginHandoffServiceConcurrentConsumeReturnsTokenOnce(t *testing.T) {
+       cache, cleanup, err := data.NewCache(&data.CacheConf{})
+       if err != nil {
+               t.Fatal(err)
+       }
+       t.Cleanup(cleanup)
+
+       service := NewLoginHandoffService(&data.Data{Cache: cache})
+       code, err := service.Create(context.Background(), "session-token")
+       if err != nil {
+               t.Fatal(err)
+       }
+
+       const consumers = 16
+       var wg sync.WaitGroup
+       results := make(chan bool, consumers)
+       for range consumers {
+               wg.Add(1)
+               go func() {
+                       defer wg.Done()
+                       _, exists, err := service.Consume(context.Background(), 
code)
+                       if err != nil {
+                               t.Errorf("consume: %v", err)
+                               return
+                       }
+                       results <- exists
+               }()
+       }
+       wg.Wait()
+       close(results)
+
+       successes := 0
+       for exists := range results {
+               if exists {
+                       successes++
+               }
+       }
+       if successes != 1 {
+               t.Fatalf("successful consumes = %d, want 1", successes)
+       }
+}
+
+func TestLoginHandoffServiceUsesAtomicCacheConsumer(t *testing.T) {
+       memoryCache, cleanup, err := data.NewCache(&data.CacheConf{})
+       if err != nil {
+               t.Fatal(err)
+       }
+       t.Cleanup(cleanup)
+
+       atomicCache := &atomicTestCache{Cache: memoryCache}
+       service := NewLoginHandoffService(&data.Data{Cache: atomicCache})
+       code, err := service.Create(context.Background(), "session-token")
+       if err != nil {
+               t.Fatal(err)
+       }
+       _, exists, err := service.Consume(context.Background(), code)
+       if err != nil || !exists {
+               t.Fatalf("consume = (_, %v, %v), want (_, true, nil)", exists, 
err)
+       }
+       if !atomicCache.consumeCalled {
+               t.Fatal("atomic cache consumer was not used")
+       }
+}
diff --git a/internal/service/provider.go b/internal/service/provider.go
index d848272f..963c2688 100644
--- a/internal/service/provider.go
+++ b/internal/service/provider.go
@@ -84,6 +84,7 @@ var ProviderSetService = wire.NewSet(
        collection.NewCollectionService,
        action.NewCaptchaService,
        auth.NewAuthService,
+       auth.NewLoginHandoffService,
        content.NewUserService,
        content.NewQuestionService,
        content.NewAnswerService,
diff --git a/ui/src/pages/Users/AuthCallback/index.tsx 
b/ui/src/pages/Users/AuthCallback/index.tsx
index 3218c7c1..2fade799 100644
--- a/ui/src/pages/Users/AuthCallback/index.tsx
+++ b/ui/src/pages/Users/AuthCallback/index.tsx
@@ -17,20 +17,36 @@
  * under the License.
  */
 
-import { FC, memo, useEffect } from 'react';
+import { FC, memo, useEffect, useRef } from 'react';
 import { useTranslation } from 'react-i18next';
-import { useSearchParams, useNavigate } from 'react-router-dom';
+import { useNavigate } from 'react-router-dom';
 
 import { usePageTags } from '@/hooks';
 import { guard } from '@/utils';
+import { exchangeLoginHandoff } from '@/services/common';
 
 const Index: FC = () => {
   const { t } = useTranslation('translation', { keyPrefix: 'page_title' });
-  const [searchParams] = useSearchParams();
   const navigate = useNavigate();
+  const handled = useRef(false);
   useEffect(() => {
-    const token = searchParams.get('access_token');
-    guard.handleLoginWithToken(token, navigate);
+    if (handled.current) {
+      return;
+    }
+    handled.current = true;
+    const code = new 
URLSearchParams(window.location.hash.slice(1)).get('code');
+    window.history.replaceState(
+      null,
+      document.title,
+      `${window.location.pathname}${window.location.search}`,
+    );
+    if (!code) {
+      guard.handleLoginWithToken(null, navigate);
+      return;
+    }
+    exchangeLoginHandoff(code)
+      .then((res) => guard.handleLoginWithToken(res.access_token, navigate))
+      .catch(() => guard.handleLoginWithToken(null, navigate));
   }, []);
   usePageTags({
     title: t('oauth_callback'),
diff --git a/ui/src/services/common.ts b/ui/src/services/common.ts
index f612bac9..6ccfbce0 100644
--- a/ui/src/services/common.ts
+++ b/ui/src/services/common.ts
@@ -23,6 +23,13 @@ import useSWR from 'swr';
 import request from '@/utils/request';
 import type * as Type from '@/common/interface';
 
+export const exchangeLoginHandoff = (code: string) => {
+  return request.post<{ access_token: string }>(
+    '/answer/api/v1/user/login/handoff',
+    { code },
+  );
+};
+
 export const uploadImage = (params: { file: File; type: Type.UploadType }) => {
   const form = new FormData();
   form.append('source', String(params.type));

Reply via email to