Merge pull request #833 from Windfarer/oidc

feat: Authentication with OIDC
This commit is contained in:
lyingbug
2026-03-30 20:43:56 +08:00
committed by GitHub
19 changed files with 1784 additions and 64 deletions
+417
View File
@@ -4,8 +4,12 @@ import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"sync"
@@ -15,12 +19,19 @@ import (
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
type oidcAuthorizationState struct {
Nonce string `json:"nonce"`
RedirectURI string `json:"redirect_uri,omitempty"`
}
var (
jwtSecretOnce sync.Once
jwtSecret string
@@ -49,10 +60,12 @@ type userService struct {
userRepo interfaces.UserRepository
tokenRepo interfaces.AuthTokenRepository
tenantService interfaces.TenantService
config *config.Config
}
// NewUserService creates a new user service instance
func NewUserService(
configInfo *config.Config,
userRepo interfaces.UserRepository,
tokenRepo interfaces.AuthTokenRepository,
tenantService interfaces.TenantService,
@@ -61,6 +74,7 @@ func NewUserService(
userRepo: userRepo,
tokenRepo: tokenRepo,
tenantService: tenantService,
config: configInfo,
}
}
@@ -198,6 +212,116 @@ func (s *userService) Login(ctx context.Context, req *types.LoginRequest) (*type
}, nil
}
// GetOIDCAuthorizationURL builds the OIDC authorization URL.
func (s *userService) GetOIDCAuthorizationURL(ctx context.Context, redirectURI string) (*types.OIDCAuthURLResponse, error) {
cfg, err := s.getOIDCConfig(ctx)
if err != nil {
return nil, err
}
if strings.TrimSpace(redirectURI) == "" {
return nil, errors.New("redirect_uri is required")
}
nonce, err := generateRandomString(24)
if err != nil {
return nil, fmt.Errorf("failed to generate state: %w", err)
}
state, err := encodeOIDCAuthorizationState(&oidcAuthorizationState{
Nonce: nonce,
RedirectURI: strings.TrimSpace(redirectURI),
})
if err != nil {
return nil, fmt.Errorf("failed to encode OIDC state: %w", err)
}
query := url.Values{}
query.Set("response_type", "code")
query.Set("client_id", cfg.ClientID)
query.Set("redirect_uri", redirectURI)
query.Set("scope", strings.Join(cfg.Scopes, " "))
query.Set("state", state)
authURL := cfg.AuthorizationEndpoint
if strings.Contains(authURL, "?") {
authURL += "&" + query.Encode()
} else {
authURL += "?" + query.Encode()
}
return &types.OIDCAuthURLResponse{
Success: true,
ProviderDisplayName: cfg.ProviderDisplayName,
AuthorizationURL: authURL,
State: state,
}, nil
}
// LoginWithOIDC exchanges code for tokens, loads user info, provisions user if needed, and returns local login tokens.
func (s *userService) LoginWithOIDC(ctx context.Context, code, redirectURI string) (*types.OIDCCallbackResponse, error) {
if strings.TrimSpace(code) == "" {
return nil, errors.New("code is required")
}
if strings.TrimSpace(redirectURI) == "" {
return nil, errors.New("redirect_uri is required")
}
cfg, err := s.getOIDCConfig(ctx)
if err != nil {
return nil, err
}
tokenResp, err := s.exchangeOIDCCode(ctx, cfg, code, redirectURI)
if err != nil {
return nil, err
}
userInfo, err := s.resolveOIDCUserInfo(ctx, cfg, tokenResp)
if err != nil {
return nil, err
}
if strings.TrimSpace(userInfo.Email) == "" {
return nil, errors.New("OIDC provider did not return email")
}
user, err := s.userRepo.GetUserByEmail(ctx, userInfo.Email)
if err != nil && !isUserLookupNotFound(err) {
return nil, fmt.Errorf("failed to query user by email: %w", err)
}
isNewUser := false
if isUserLookupNotFound(err) || user == nil {
user, err = s.provisionOIDCUser(ctx, userInfo)
if err != nil {
return nil, err
}
isNewUser = true
}
if !user.IsActive {
return &types.OIDCCallbackResponse{Success: false, Message: "Account is disabled"}, nil
}
accessToken, refreshToken, err := s.GenerateTokens(ctx, user)
if err != nil {
return nil, fmt.Errorf("failed to generate local tokens: %w", err)
}
tenant, err := s.tenantService.GetTenantByID(ctx, user.TenantID)
if err != nil {
logger.Warnf(ctx, "Failed to get tenant info after OIDC login: %v", err)
}
return &types.OIDCCallbackResponse{
Success: true,
Message: "Login successful",
User: user,
Tenant: tenant,
Token: accessToken,
RefreshToken: refreshToken,
IsNewUser: isNewUser,
}, nil
}
// GetUserByID gets a user by ID
func (s *userService) GetUserByID(ctx context.Context, id string) (*types.User, error) {
return s.userRepo.GetUserByID(ctx, id)
@@ -439,3 +563,296 @@ func (s *userService) SearchUsers(ctx context.Context, query string, limit int)
}
return s.userRepo.SearchUsers(ctx, query, limit)
}
type oidcDiscoveryDocument struct {
AuthorizationEndpoint string `json:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint"`
UserInfoEndpoint string `json:"userinfo_endpoint"`
}
type oidcTokenResponse struct {
AccessToken string `json:"access_token"`
IDToken string `json:"id_token"`
TokenType string `json:"token_type"`
}
func (s *userService) getOIDCConfig(ctx context.Context) (*config.OIDCAuthConfig, error) {
if s.config == nil || s.config.OIDCAuth == nil || !s.config.OIDCAuth.Enable {
return nil, errors.New("OIDC login is disabled")
}
cfg := *s.config.OIDCAuth
if cfg.UserInfoMapping == nil {
cfg.UserInfoMapping = &config.OIDCUserInfoMapping{Username: "name", Email: "email"}
}
if err := s.populateOIDCEndpoints(ctx, &cfg); err != nil {
return nil, err
}
return &cfg, nil
}
func (s *userService) populateOIDCEndpoints(ctx context.Context, cfg *config.OIDCAuthConfig) error {
if strings.TrimSpace(cfg.AuthorizationEndpoint) != "" && strings.TrimSpace(cfg.TokenEndpoint) != "" {
return nil
}
if strings.TrimSpace(cfg.DiscoveryURL) == "" {
return errors.New("OIDC discovery_url or explicit endpoints are required")
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, cfg.DiscoveryURL, nil)
if err != nil {
return fmt.Errorf("failed to create OIDC discovery request: %w", err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("failed to load OIDC discovery document: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))
return fmt.Errorf("OIDC discovery request failed: status=%d body=%s", resp.StatusCode, strings.TrimSpace(string(body)))
}
var doc oidcDiscoveryDocument
if err := json.NewDecoder(resp.Body).Decode(&doc); err != nil {
return fmt.Errorf("failed to decode OIDC discovery document: %w", err)
}
if cfg.AuthorizationEndpoint == "" {
cfg.AuthorizationEndpoint = doc.AuthorizationEndpoint
}
if cfg.TokenEndpoint == "" {
cfg.TokenEndpoint = doc.TokenEndpoint
}
if cfg.UserInfoEndpoint == "" {
cfg.UserInfoEndpoint = doc.UserInfoEndpoint
}
if cfg.AuthorizationEndpoint == "" || cfg.TokenEndpoint == "" {
return errors.New("OIDC discovery document missing required endpoints")
}
return nil
}
func (s *userService) exchangeOIDCCode(ctx context.Context, cfg *config.OIDCAuthConfig, code, redirectURI string) (*oidcTokenResponse, error) {
form := url.Values{}
form.Set("grant_type", "authorization_code")
form.Set("code", code)
form.Set("redirect_uri", redirectURI)
form.Set("client_id", cfg.ClientID)
form.Set("client_secret", cfg.ClientSecret)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, cfg.TokenEndpoint, strings.NewReader(form.Encode()))
if err != nil {
return nil, fmt.Errorf("failed to create OIDC token request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to exchange OIDC code: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))
return nil, fmt.Errorf("OIDC token exchange failed: status=%d body=%s", resp.StatusCode, strings.TrimSpace(string(body)))
}
var tokenResp oidcTokenResponse
if err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {
return nil, fmt.Errorf("failed to decode OIDC token response: %w", err)
}
if strings.TrimSpace(tokenResp.AccessToken) == "" && strings.TrimSpace(tokenResp.IDToken) == "" {
return nil, errors.New("OIDC token response missing access_token and id_token")
}
return &tokenResp, nil
}
func (s *userService) resolveOIDCUserInfo(ctx context.Context, cfg *config.OIDCAuthConfig, tokenResp *oidcTokenResponse) (*types.OIDCUserInfo, error) {
claims := map[string]interface{}{}
if strings.TrimSpace(tokenResp.IDToken) != "" {
idTokenClaims, err := decodeJWTClaims(tokenResp.IDToken)
if err != nil {
logger.Warnf(ctx, "Failed to decode OIDC id_token claims: %v", err)
} else {
for k, v := range idTokenClaims {
claims[k] = v
}
}
}
if strings.TrimSpace(cfg.UserInfoEndpoint) != "" && strings.TrimSpace(tokenResp.AccessToken) != "" {
userInfoClaims, err := s.fetchOIDCUserInfo(ctx, cfg.UserInfoEndpoint, tokenResp.AccessToken)
if err != nil {
logger.Warnf(ctx, "Failed to fetch OIDC userinfo, fallback to id_token claims: %v", err)
} else {
for k, v := range userInfoClaims {
claims[k] = v
}
}
}
info := &types.OIDCUserInfo{Claims: claims}
if sub, _ := claims["sub"].(string); sub != "" {
info.Subject = sub
}
info.Username = extractClaimAsString(claims, cfg.UserInfoMapping.Username)
info.Email = extractClaimAsString(claims, cfg.UserInfoMapping.Email)
if info.Username == "" {
info.Username = extractClaimAsString(claims, "preferred_username")
}
if info.Username == "" {
info.Username = extractClaimAsString(claims, "name")
}
if info.Username == "" && info.Email != "" {
info.Username = strings.Split(info.Email, "@")[0]
}
return info, nil
}
func (s *userService) fetchOIDCUserInfo(ctx context.Context, endpoint, accessToken string) (map[string]interface{}, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Accept", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))
return nil, fmt.Errorf("userinfo request failed: status=%d body=%s", resp.StatusCode, strings.TrimSpace(string(body)))
}
var claims map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&claims); err != nil {
return nil, err
}
return claims, nil
}
func (s *userService) provisionOIDCUser(ctx context.Context, info *types.OIDCUserInfo) (*types.User, error) {
username := s.generateOIDCUsername(ctx, info)
randomPassword, err := generateRandomString(32)
if err != nil {
return nil, fmt.Errorf("failed to generate password for OIDC user: %w", err)
}
user, err := s.Register(ctx, &types.RegisterRequest{
Username: username,
Email: info.Email,
Password: randomPassword,
})
if err != nil {
return nil, fmt.Errorf("failed to auto-provision OIDC user: %w", err)
}
return user, nil
}
func (s *userService) generateOIDCUsername(ctx context.Context, info *types.OIDCUserInfo) string {
base := sanitizeUsernameCandidate(info.Username)
if base == "" {
base = sanitizeUsernameCandidate(strings.Split(info.Email, "@")[0])
}
if base == "" {
base = "oidc-user"
}
candidate := base
for i := 0; i < 20; i++ {
existing, err := s.userRepo.GetUserByUsername(ctx, candidate)
if isUserLookupNotFound(err) || (err == nil && existing == nil) {
return candidate
}
if err != nil && !isUserLookupNotFound(err) {
logger.Warnf(ctx, "Failed to check existing OIDC username %q: %v", candidate, err)
}
candidate = fmt.Sprintf("%s-%d", base, i+1)
}
return fmt.Sprintf("%s-%d", base, time.Now().Unix())
}
func generateRandomString(length int) (string, error) {
buffer := make([]byte, length)
if _, err := rand.Read(buffer); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(buffer), nil
}
func encodeOIDCAuthorizationState(state *oidcAuthorizationState) (string, error) {
payload, err := json.Marshal(state)
if err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(payload), nil
}
func decodeJWTClaims(token string) (map[string]interface{}, error) {
parts := strings.Split(token, ".")
if len(parts) < 2 {
return nil, errors.New("invalid JWT format")
}
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return nil, err
}
var claims map[string]interface{}
if err := json.Unmarshal(payload, &claims); err != nil {
return nil, err
}
return claims, nil
}
func extractClaimAsString(claims map[string]interface{}, key string) string {
key = strings.TrimSpace(key)
if key == "" {
return ""
}
value, ok := claims[key]
if !ok || value == nil {
return ""
}
switch v := value.(type) {
case string:
return strings.TrimSpace(v)
default:
return strings.TrimSpace(fmt.Sprint(v))
}
}
func sanitizeUsernameCandidate(value string) string {
value = strings.TrimSpace(strings.ToLower(value))
if value == "" {
return ""
}
var b strings.Builder
lastDash := false
for _, r := range value {
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' || r == '.' {
b.WriteRune(r)
lastDash = false
continue
}
if !lastDash {
b.WriteByte('-')
lastDash = true
}
}
result := strings.Trim(b.String(), "-._")
if len(result) > 50 {
result = strings.Trim(result[:50], "-._")
}
return result
}
func isUserLookupNotFound(err error) bool {
if err == nil {
return false
}
return errors.Is(err, apprepo.ErrUserNotFound) || strings.Contains(strings.ToLower(err.Error()), "user not found")
}
+115 -18
View File
@@ -20,6 +20,7 @@ type Config struct {
Server *ServerConfig `yaml:"server" json:"server"`
KnowledgeBase *KnowledgeBaseConfig `yaml:"knowledge_base" json:"knowledge_base"`
Tenant *TenantConfig `yaml:"tenant" json:"tenant"`
OIDCAuth *OIDCAuthConfig `yaml:"oidc_auth" json:"oidc_auth"`
Models []ModelConfig `yaml:"models" json:"models"`
VectorDatabase *VectorDatabaseConfig `yaml:"vector_database" json:"vector_database"`
DocReader *DocReaderConfig `yaml:"docreader" json:"docreader"`
@@ -85,13 +86,13 @@ type ConversationConfig struct {
Summary *SummaryConfig `yaml:"summary" json:"summary"`
// Prompt template ID fields — resolved to text by backfillConversationDefaults
FallbackPromptID string `yaml:"fallback_prompt_id" json:"fallback_prompt_id"`
RewritePromptID string `yaml:"rewrite_prompt_id" json:"rewrite_prompt_id"`
GenerateSessionTitlePromptID string `yaml:"generate_session_title_prompt_id" json:"generate_session_title_prompt_id"`
GenerateSummaryPromptID string `yaml:"generate_summary_prompt_id" json:"generate_summary_prompt_id"`
ExtractEntitiesPromptID string `yaml:"extract_entities_prompt_id" json:"extract_entities_prompt_id"`
ExtractRelationshipsPromptID string `yaml:"extract_relationships_prompt_id" json:"extract_relationships_prompt_id"`
GenerateQuestionsPromptID string `yaml:"generate_questions_prompt_id" json:"generate_questions_prompt_id"`
FallbackPromptID string `yaml:"fallback_prompt_id" json:"fallback_prompt_id"`
RewritePromptID string `yaml:"rewrite_prompt_id" json:"rewrite_prompt_id"`
GenerateSessionTitlePromptID string `yaml:"generate_session_title_prompt_id" json:"generate_session_title_prompt_id"`
GenerateSummaryPromptID string `yaml:"generate_summary_prompt_id" json:"generate_summary_prompt_id"`
ExtractEntitiesPromptID string `yaml:"extract_entities_prompt_id" json:"extract_entities_prompt_id"`
ExtractRelationshipsPromptID string `yaml:"extract_relationships_prompt_id" json:"extract_relationships_prompt_id"`
GenerateQuestionsPromptID string `yaml:"generate_questions_prompt_id" json:"generate_questions_prompt_id"`
// Resolved prompt text fields (populated by backfill, not from YAML)
FallbackPrompt string `yaml:"-" json:"fallback_prompt"`
@@ -162,6 +163,25 @@ type TenantConfig struct {
EnableCrossTenantAccess bool `yaml:"enable_cross_tenant_access" json:"enable_cross_tenant_access"`
}
type OIDCUserInfoMapping struct {
Username string `yaml:"username" json:"username"`
Email string `yaml:"email" json:"email"`
}
type OIDCAuthConfig struct {
Enable bool `yaml:"enable" json:"enable"`
IssuerURL string `yaml:"issuer_url" json:"issuer_url"`
DiscoveryURL string `yaml:"discovery_url" json:"discovery_url"`
ProviderDisplayName string `yaml:"provider_display_name" json:"provider_display_name"`
ClientID string `yaml:"client_id" json:"client_id"`
ClientSecret string `yaml:"client_secret" json:"-"`
AuthorizationEndpoint string `yaml:"authorization_endpoint" json:"authorization_endpoint"`
TokenEndpoint string `yaml:"token_endpoint" json:"token_endpoint"`
UserInfoEndpoint string `yaml:"user_info_endpoint" json:"user_info_endpoint"`
Scopes []string `yaml:"scopes" json:"scopes"`
UserInfoMapping *OIDCUserInfoMapping `yaml:"user_info_mapping" json:"user_info_mapping"`
}
// PromptTemplateI18n holds localized name and description for a prompt template.
type PromptTemplateI18n struct {
Name string `yaml:"name" json:"name"`
@@ -175,16 +195,16 @@ type PromptTemplateI18n struct {
// - user: 用户侧 Prompt(仅在需要 system+user 配对的模板中使用,如 rewrite、keywords_extraction)
// - i18n: 多语言 name/description,键为 locale(如 "zh-CN"、"en-US"、"ko-KR"),后端根据请求语言替换 Name/Description 再返回
type PromptTemplate struct {
ID string `yaml:"id" json:"id"`
Name string `yaml:"name" json:"name"`
Description string `yaml:"description" json:"description"`
Content string `yaml:"content" json:"content"`
User string `yaml:"user" json:"user,omitempty"`
HasKnowledgeBase bool `yaml:"has_knowledge_base" json:"has_knowledge_base,omitempty"`
HasWebSearch bool `yaml:"has_web_search" json:"has_web_search,omitempty"`
Default bool `yaml:"default" json:"default,omitempty"`
Mode string `yaml:"mode" json:"mode,omitempty"`
I18n map[string]PromptTemplateI18n `yaml:"i18n" json:"-"`
ID string `yaml:"id" json:"id"`
Name string `yaml:"name" json:"name"`
Description string `yaml:"description" json:"description"`
Content string `yaml:"content" json:"content"`
User string `yaml:"user" json:"user,omitempty"`
HasKnowledgeBase bool `yaml:"has_knowledge_base" json:"has_knowledge_base,omitempty"`
HasWebSearch bool `yaml:"has_web_search" json:"has_web_search,omitempty"`
Default bool `yaml:"default" json:"default,omitempty"`
Mode string `yaml:"mode" json:"mode,omitempty"`
I18n map[string]PromptTemplateI18n `yaml:"i18n" json:"-"`
}
// PromptTemplatesConfig 提示词模板配置
@@ -386,6 +406,8 @@ func LoadConfig() (*Config, error) {
}
// Validate configuration values
applyOIDCEnvOverrides(&cfg)
if err := ValidateConfig(&cfg); err != nil {
return nil, err
}
@@ -398,6 +420,19 @@ func LoadConfig() (*Config, error) {
func ValidateConfig(cfg *Config) error {
var errs []string
if cfg.OIDCAuth != nil && cfg.OIDCAuth.Enable {
if strings.TrimSpace(cfg.OIDCAuth.ClientID) == "" {
errs = append(errs, "oidc_auth.client_id is required when OIDC is enabled")
}
if strings.TrimSpace(cfg.OIDCAuth.ClientSecret) == "" {
errs = append(errs, "oidc_auth.client_secret is required when OIDC is enabled")
}
if strings.TrimSpace(cfg.OIDCAuth.DiscoveryURL) == "" &&
(strings.TrimSpace(cfg.OIDCAuth.AuthorizationEndpoint) == "" || strings.TrimSpace(cfg.OIDCAuth.TokenEndpoint) == "") {
errs = append(errs, "oidc_auth.discovery_url or both oidc_auth.authorization_endpoint and oidc_auth.token_endpoint are required when OIDC is enabled")
}
}
if cfg.Conversation != nil {
if cfg.Conversation.EmbeddingTopK < 0 {
errs = append(errs, "conversation.embedding_top_k must be >= 0")
@@ -437,6 +472,68 @@ func ValidateConfig(cfg *Config) error {
return nil
}
func applyOIDCEnvOverrides(cfg *Config) {
if cfg.OIDCAuth == nil {
cfg.OIDCAuth = &OIDCAuthConfig{}
}
if cfg.OIDCAuth.UserInfoMapping == nil {
cfg.OIDCAuth.UserInfoMapping = &OIDCUserInfoMapping{}
}
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_ENABLE")); value != "" {
cfg.OIDCAuth.Enable = strings.EqualFold(value, "true")
}
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_ISSUER_URL")); value != "" {
cfg.OIDCAuth.IssuerURL = value
}
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_DISCOVERY_URL")); value != "" {
cfg.OIDCAuth.DiscoveryURL = value
}
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_PROVIDER_DISPLAY_NAME")); value != "" {
cfg.OIDCAuth.ProviderDisplayName = value
}
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_CLIENT_ID")); value != "" {
cfg.OIDCAuth.ClientID = value
}
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_CLIENT_SECRET")); value != "" {
cfg.OIDCAuth.ClientSecret = value
}
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_AUTHORIZATION_ENDPOINT")); value != "" {
cfg.OIDCAuth.AuthorizationEndpoint = value
}
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_TOKEN_ENDPOINT")); value != "" {
cfg.OIDCAuth.TokenEndpoint = value
}
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_USER_INFO_ENDPOINT")); value != "" {
cfg.OIDCAuth.UserInfoEndpoint = value
}
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_SCOPES")); value != "" {
cfg.OIDCAuth.Scopes = strings.Fields(strings.ReplaceAll(value, ",", " "))
}
if value := strings.TrimSpace(os.Getenv("OIDC_USER_INFO_MAPPING_USER_NAME")); value != "" {
cfg.OIDCAuth.UserInfoMapping.Username = value
}
if value := strings.TrimSpace(os.Getenv("OIDC_USER_INFO_MAPPING_EMAIL")); value != "" {
cfg.OIDCAuth.UserInfoMapping.Email = value
}
if cfg.OIDCAuth.ProviderDisplayName == "" {
cfg.OIDCAuth.ProviderDisplayName = "OIDC"
}
if len(cfg.OIDCAuth.Scopes) == 0 {
cfg.OIDCAuth.Scopes = []string{"openid", "profile", "email"}
}
if cfg.OIDCAuth.UserInfoMapping.Username == "" {
cfg.OIDCAuth.UserInfoMapping.Username = "name"
}
if cfg.OIDCAuth.UserInfoMapping.Email == "" {
cfg.OIDCAuth.UserInfoMapping.Email = "email"
}
if cfg.OIDCAuth.DiscoveryURL == "" && cfg.OIDCAuth.IssuerURL != "" {
cfg.OIDCAuth.DiscoveryURL = strings.TrimRight(cfg.OIDCAuth.IssuerURL, "/") + "/.well-known/openid-configuration"
}
}
// backfillConversationDefaults resolves prompt template ID references
// into actual prompt text content. Only xxx_id fields are used;
// no fallback to default templates.
@@ -592,7 +689,7 @@ func loadPromptTemplates(configDir string) (*PromptTemplatesConfig, error) {
"agent_system_prompt.yaml": &config.AgentSystemPrompt,
"graph_extraction.yaml": &config.GraphExtraction,
"generate_questions.yaml": &config.GenerateQuestions,
"intent_prompts.yaml": &config.IntentPrompts,
"intent_prompts.yaml": &config.IntentPrompts,
}
// 加载每个模板文件
+157
View File
@@ -1,6 +1,8 @@
package handler
import (
"encoding/base64"
"encoding/json"
"net/http"
"os"
"strings"
@@ -157,6 +159,161 @@ func (h *AuthHandler) Login(c *gin.Context) {
c.JSON(http.StatusOK, response)
}
// GetOIDCAuthorizationURL godoc
// @Summary 获取OIDC授权地址
// @Description 根据后端OIDC配置生成第三方登录跳转地址
// @Tags 认证
// @Accept json
// @Produce json
// @Param redirect_uri query string true "OIDC回调地址"
// @Success 200 {object} types.OIDCAuthURLResponse
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 403 {object} errors.AppError "OIDC未启用"
// @Router /auth/oidc/url [get]
func (h *AuthHandler) GetOIDCAuthorizationURL(c *gin.Context) {
ctx := c.Request.Context()
redirectURI := strings.TrimSpace(c.Query("redirect_uri"))
if redirectURI == "" {
appErr := errors.NewValidationError("redirect_uri is required")
c.Error(appErr)
return
}
resp, err := h.userService.GetOIDCAuthorizationURL(ctx, redirectURI)
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
}
c.JSON(http.StatusOK, resp)
}
// GetOIDCConfig godoc
// @Summary 获取OIDC登录配置
// @Description 返回OIDC是否启用以及provider展示名称,供前端决定是否展示OIDC登录入口
// @Tags 认证
// @Accept json
// @Produce json
// @Success 200 {object} types.OIDCConfigResponse
// @Router /auth/oidc/config [get]
func (h *AuthHandler) GetOIDCConfig(c *gin.Context) {
providerDisplayName := ""
enabled := false
if h.configInfo != nil && h.configInfo.OIDCAuth != nil {
enabled = h.configInfo.OIDCAuth.Enable
providerDisplayName = strings.TrimSpace(h.configInfo.OIDCAuth.ProviderDisplayName)
}
c.JSON(http.StatusOK, &types.OIDCConfigResponse{
Success: true,
Enabled: enabled,
ProviderDisplayName: providerDisplayName,
})
}
// OIDCRedirectCallback godoc
// @Summary OIDC登录重定向回调
// @Description 接收OIDC provider回调并由后端完成code交换,随后重定向回前端登录页
// @Tags 认证
// @Accept json
// @Produce json
// @Param code query string false "OIDC授权码"
// @Param state query string false "OIDC状态"
// @Param error query string false "OIDC错误码"
// @Success 302
// @Router /auth/oidc/callback [get]
func (h *AuthHandler) OIDCRedirectCallback(c *gin.Context) {
ctx := c.Request.Context()
frontendRedirectURI := "/"
if providerError := strings.TrimSpace(c.Query("error")); providerError != "" {
redirectURL := frontendRedirectURI + "#oidc_error=" + urlQueryEscape(providerError)
if description := strings.TrimSpace(c.Query("error_description")); description != "" {
redirectURL += "&oidc_error_description=" + urlQueryEscape(description)
}
c.Redirect(http.StatusFound, redirectURL)
return
}
state := strings.TrimSpace(c.Query("state"))
decodedState, err := decodeOIDCState(state)
if err != nil {
logger.Errorf(ctx, "Failed to decode OIDC state: %v", err)
c.Redirect(http.StatusFound, frontendRedirectURI+"#oidc_error="+urlQueryEscape("invalid_state"))
return
}
code := strings.TrimSpace(c.Query("code"))
if code == "" {
c.Redirect(http.StatusFound, frontendRedirectURI+"#oidc_error="+urlQueryEscape("missing_code"))
return
}
resp, err := h.userService.LoginWithOIDC(ctx, code, strings.TrimSpace(decodedState.RedirectURI))
if err != nil {
logger.Errorf(ctx, "Failed to complete OIDC login via redirect callback: %v", err)
c.Redirect(http.StatusFound, frontendRedirectURI+"#oidc_error="+urlQueryEscape("login_failed")+"&oidc_error_description="+urlQueryEscape(err.Error()))
return
}
if !resp.Success {
c.Redirect(http.StatusFound, frontendRedirectURI+"#oidc_error="+urlQueryEscape("login_failed")+"&oidc_error_description="+urlQueryEscape(resp.Message))
return
}
payload, err := encodeOIDCCallbackPayload(resp)
if err != nil {
logger.Errorf(ctx, "Failed to encode OIDC callback payload: %v", err)
c.Redirect(http.StatusFound, frontendRedirectURI+"#oidc_error="+urlQueryEscape("payload_encode_failed"))
return
}
c.Redirect(http.StatusFound, frontendRedirectURI+"#oidc_result="+urlQueryEscape(payload))
}
func encodeOIDCCallbackPayload(resp *types.OIDCCallbackResponse) (string, error) {
payload, err := json.Marshal(resp)
if err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(payload), nil
}
type oidcStatePayload struct {
Nonce string `json:"nonce"`
RedirectURI string `json:"redirect_uri,omitempty"`
}
func decodeOIDCState(raw string) (*oidcStatePayload, error) {
decoded, err := base64.RawURLEncoding.DecodeString(strings.TrimSpace(raw))
if err != nil {
return nil, err
}
var payload oidcStatePayload
if err := json.Unmarshal(decoded, &payload); err != nil {
return nil, err
}
if strings.TrimSpace(payload.RedirectURI) == "" {
return nil, errors.NewValidationError("state.redirect_uri is required")
}
return &payload, nil
}
func urlQueryEscape(value string) string {
replacer := strings.NewReplacer(
"%", "%25",
" ", "%20",
"#", "%23",
"&", "%26",
"+", "%2B",
"=", "%3D",
"?", "%3F",
)
return replacer.Replace(value)
}
// Logout godoc
// @Summary 用户登出
// @Description 撤销当前访问令牌并登出
+7 -4
View File
@@ -18,10 +18,13 @@ import (
// 无需认证的API列表
var noAuthAPI = map[string][]string{
"/health": {"GET"},
"/api/v1/auth/register": {"POST"},
"/api/v1/auth/login": {"POST"},
"/api/v1/auth/refresh": {"POST"},
"/health": {"GET"},
"/api/v1/auth/register": {"POST"},
"/api/v1/auth/login": {"POST"},
"/api/v1/auth/oidc/config": {"GET"},
"/api/v1/auth/oidc/url": {"GET"},
"/api/v1/auth/oidc/callback": {"GET"},
"/api/v1/auth/refresh": {"POST"},
}
// 检查请求是否在无需认证的API列表中
+3
View File
@@ -393,6 +393,9 @@ func RegisterEvaluationRoutes(r *gin.RouterGroup, handler *handler.EvaluationHan
func RegisterAuthRoutes(r *gin.RouterGroup, handler *handler.AuthHandler) {
r.POST("/auth/register", handler.Register)
r.POST("/auth/login", handler.Login)
r.GET("/auth/oidc/config", handler.GetOIDCConfig)
r.GET("/auth/oidc/url", handler.GetOIDCAuthorizationURL)
r.GET("/auth/oidc/callback", handler.OIDCRedirectCallback)
r.POST("/auth/refresh", handler.RefreshToken)
r.GET("/auth/validate", handler.ValidateToken)
r.POST("/auth/logout", handler.Logout)
+4
View File
@@ -12,6 +12,10 @@ type UserService interface {
Register(ctx context.Context, req *types.RegisterRequest) (*types.User, error)
// Login authenticates a user and returns tokens
Login(ctx context.Context, req *types.LoginRequest) (*types.LoginResponse, error)
// GetOIDCAuthorizationURL builds the third-party OIDC authorization URL
GetOIDCAuthorizationURL(ctx context.Context, redirectURI string) (*types.OIDCAuthURLResponse, error)
// LoginWithOIDC exchanges the callback code, auto-provisions users if needed, and completes login
LoginWithOIDC(ctx context.Context, code, redirectURI string) (*types.OIDCCallbackResponse, error)
// GetUserByID gets a user by ID
GetUserByID(ctx context.Context, id string) (*types.User, error)
// GetUserByEmail gets a user by email
+30
View File
@@ -64,6 +64,36 @@ type LoginRequest struct {
Password string `json:"password" binding:"required,min=6"`
}
type OIDCAuthURLResponse struct {
Success bool `json:"success"`
ProviderDisplayName string `json:"provider_display_name,omitempty"`
AuthorizationURL string `json:"authorization_url,omitempty"`
State string `json:"state,omitempty"`
}
type OIDCConfigResponse struct {
Success bool `json:"success"`
Enabled bool `json:"enabled"`
ProviderDisplayName string `json:"provider_display_name,omitempty"`
}
type OIDCCallbackResponse struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
User *User `json:"user,omitempty"`
Tenant *Tenant `json:"tenant,omitempty"`
Token string `json:"token,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
IsNewUser bool `json:"is_new_user,omitempty"`
}
type OIDCUserInfo struct {
Subject string `json:"subject,omitempty"`
Username string `json:"username,omitempty"`
Email string `json:"email,omitempty"`
Claims map[string]interface{} `json:"claims,omitempty"`
}
// RegisterRequest represents a registration request
type RegisterRequest struct {
Username string `json:"username" binding:"required,min=2,max=50"`