diff --git a/config.yml b/config.yml index 25ed05a..15d7bce 100644 --- a/config.yml +++ b/config.yml @@ -11,6 +11,7 @@ server: # 认证密钥配置 auth: + enabled: true app_access_secret: "D4tBb9Y0oHSXRAyHLHpdKfXAuNCyCZ45AZxKJOhMJMs=" device_relay_secret: "p+JtJ8aHlM1lDYu7UGFanX8ALVt1pM1BQmKTpqTJccs=" diff --git a/config/config.go b/config/config.go index a493262..463cca5 100644 --- a/config/config.go +++ b/config/config.go @@ -20,6 +20,7 @@ type ServerConfig struct { InstanceID string `mapstructure:"instance_id"` } type AuthConfig struct { + Enabled bool `mapstructure:"enabled"` AppAccessSecret string `mapstructure:"app_access_secret"` DeviceRelaySecret string `mapstructure:"device_relay_secret"` } diff --git a/main.go b/main.go index 6d05236..19fa879 100644 --- a/main.go +++ b/main.go @@ -245,14 +245,12 @@ func handleAppRequest(w http.ResponseWriter, r *http.Request) { deviceSN := pathParts[1] // --- [App 认证逻辑 - 暂时注释,需要时取消注释即可] --- - /* - appUserID, err := authenticateAppRequest(r) - if err != nil { - log.Printf("App authentication failed for device %s: %v", deviceSN, err) - http.Error(w, "Unauthorized", http.StatusUnauthorized) - return - } - */ + appUserID, err := authenticateAppRequest(r) + if err != nil { + log.Printf("App authentication failed for device %s: %v", deviceSN, err) + http.Error(w, "Unauthorized", http.StatusUnauthorized) + return + } sessionMutex.RLock() sessionInfo, ok := deviceSessions[deviceSN] @@ -263,13 +261,11 @@ func handleAppRequest(w http.ResponseWriter, r *http.Request) { return } - /* --- [所有权检查 - 暂时注释] --- - if sessionInfo.UserID != appUserID { - log.Printf("Forbidden: App user '%s' attempted to access device '%s' owned by '%s'", appUserID, deviceSN, sessionInfo.UserID) + if config.Cfg.Auth.Enabled && sessionInfo.UserID != appUserID { + log.Printf("Forb idden: App user '%s' attempted to access device '%s' owned by '%s'", appUserID, deviceSN, sessionInfo.UserID) http.Error(w, "Forbidden: you do not own this device", http.StatusForbidden) return } - */ proxy := &httputil.ReverseProxy{ Director: func(req *http.Request) { @@ -310,14 +306,18 @@ func handleAppRequest(w http.ResponseWriter, r *http.Request) { // authenticateAppRequest 和 verifyAppToken 保持不变,备用 func authenticateAppRequest(r *http.Request) (string, error) { + if !config.Cfg.Auth.Enabled { + return "", nil + } + authHeader := r.Header.Get("Authorization") if authHeader == "" { return "", errors.New("missing Authorization header") } tokenString := strings.TrimPrefix(authHeader, "Bearer ") - if tokenString == authHeader { - return "", errors.New("authorization header format must be Bearer {token}") - } + //if tokenString == authHeader { + // return "", errors.New("authorization header format must be Bearer {token}") + //} claims, err := verifyAppToken(tokenString) if err != nil { return "", fmt.Errorf("app token verification failed: %w", err)