liu 1 year ago
parent
commit
e2afbfd960
3 changed files with 70 additions and 19 deletions
  1. 55 13
      README.md
  2. 1 1
      backend/open_webui/routers/auths.py
  3. 14 5
      backend/open_webui/test/token_for_signin.py

+ 55 - 13
README.md

@@ -150,13 +150,21 @@ NODE_OPTIONS="--max-old-space-size=4096" npm run build
 # windows 上配置环境变量
 # 密码含特殊字符:将password中的@ $等字符替换为%40 %24
 DATABASE_URL="postgresql://myuser:mysecretpassword@localhost:5432/mydatabase"
-```
-
-### 反向代理配置(windows)
+```### 反向代理配置(windows)
 ```nginx
 # nginx-1.26.3(windows)
+#user  nobody;
+worker_processes  1;
+
+error_log  logs/error.log debug;
+events {
+    worker_connections  1024;
+}
 http {
-    ...
+    include       mime.types;
+    default_type  application/octet-stream;
+    sendfile        on;
+    keepalive_timeout  65;
 
     # 全局优化
     client_max_body_size 100M; # 允许大文件上传
@@ -165,15 +173,23 @@ http {
     gzip on;
 
     server {
-        listen       80;
+        listen       3443;
         server_name  localhost;
-
-        # 指向构建后的静态文件目录(使用 Windows 路径)
-        root C:/Users/liu78/Desktop/workspace/open-webui-main/build;
-        index index.html;
-
+        # 指向构建后的静态文件目录(使用相对路径)
         location / {
-            try_files $uri $uri/ /index.html;
+            proxy_pass http://localhost:8080;
+            proxy_set_header Host $host;
+            proxy_set_header X-Real-IP $remote_addr;
+            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+            proxy_set_header X-Forwarded-Proto $scheme;
+        }
+
+        # 从 /auth 页面提取参数到变量
+        location /auth {
+            add_header Set-Cookie "auth_token=$arg_token; Path=/api/; HttpOnly";
+            # 存储参数到变量(需确保前端页面和 API 在同一个请求会话中)
+            set $auth_token $arg_token;
+            proxy_pass http://localhost:8080/auth;
         }
 
         # 代理后端API请求(关键配置)
@@ -188,6 +204,9 @@ http {
             proxy_set_header Host $host;
             proxy_set_header X-Real-IP $remote_addr;
             proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+
+            # 将 Cookie 值作为请求头或查询参数传递
+            proxy_set_header X-Trusted-Token $cookie_auth_token;
         }
         # 处理/ws路径的Socket.IO连接(需添加协议升级头)
         location /ws/ {
@@ -201,7 +220,7 @@ http {
         }
 
         # 其他路由代理(根据FastAPI挂载路径)
-        location ~ ^/(ollama|openai|auth|users|chats|models|files|retrieval)/ {
+        location ~ ^/(ollama|openai|users|chats|models|files|retrieval)/ {
             proxy_pass http://localhost:8080;
             proxy_set_header Host $host;
             proxy_set_header X-Forwarded-Proto $scheme;
@@ -216,8 +235,31 @@ http {
             proxy_pass http://localhost:8080/cache/;
             expires 1h;
         }
-        ...
+        error_page   500 502 503 504  /50x.html;
+        location = /50x.html {
+            root   html;
+        }
     }
+}
+```
+
+### 单点登录环境变量配置
+```bash
+# 信任邮箱和密码一定要配置,具体值是多少无所谓,可以拷贝
+WEBUI_AUTH_TRUSTED_EMAIL_HEADER=X-Trusted-Email
+WEBUI_AUTH_TRUSTED_NAME_HEADER=X-Trusted-Name
+# 信任的token键值都是固定的,和nginx中配置一致
+WEBUI_AUTH_TRUSTED_TOKEN_HEADER=X-Trusted-Token
 ```
 
+### 单点登录使用
+- 先生成token,最好带时间,保证token值变动,生成的例子看backend\open_webui\test\token_for_signin.py
+- 然后直接跳转:
+```bash
+# localhost 改成具体的IP值
+http://localhost:3443/auth?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InRlc3RAZXhhbXBsZS5jb20iLCJuYW1lIjoiVGVzdCBVc2VyIiwiZXhwIjoxNzQyNTQxNTQwfQ.vcSVmvGazhahzN7azwxiGF8v9v8iolNF3dF8g4Sl5Zc
+```
+
+
+
 

+ 1 - 1
backend/open_webui/routers/auths.py

@@ -336,7 +336,7 @@ async def signin(request: Request, response: Response, form_data: SigninForm):
         trusted_token = request.headers[WEBUI_AUTH_TRUSTED_TOKEN_HEADER]
         # 讲token解密,获取用户名称和邮箱
         try:
-            payload = jwt.decode(trusted_token, "WEBUI_SECRET_KEY", algorithms=["HS256"])
+            payload = jwt.decode(trusted_token, "QCopWfW1tmdxRulrO3axMBx78ygNkOI-fOv7J-4iJaU", algorithms=["HS256"])
         except jwt.ExpiredSignatureError:
             raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_TRUSTED_HEADER)
         except jwt.InvalidTokenError:

+ 14 - 5
backend/open_webui/test/token_for_signin.py

@@ -1,10 +1,12 @@
+import base64
+import secrets
 import jwt
 from datetime import datetime, timedelta
 
 def generate_jwt_token(
     email: str,
     name: str,
-    secret_key: str = "WEBUI_SECRET_KEY",  # 建议通过环境变量注入实际密钥
+    secret_key: str = "QCopWfW1tmdxRulrO3axMBx78ygNkOI-fOv7J-4iJaU",  # 建议通过环境变量注入实际密钥
     expires: int = 3600  # 默认有效期 1 小时(秒)
 ) -> str:
     """
@@ -41,8 +43,15 @@ if __name__ == "__main__":
 
     # 生成已过期 Token(用于测试过期场景)
     expired_token = generate_jwt_token(
-        email="expired@example.com",
-        name="Expired User",
-        expires=-10  # 负值强制过期
+        email="liuq@yg.com",
+        name="liuq",
+        expires=3600  # 负值强制过期
     )
-    print("Expired Token:", expired_token)
+    print("Expired Token:", expired_token)
+
+    # 生成32字节(256位)随机数据
+    key_bytes = secrets.token_bytes(32)
+
+    # 转换为Base64字符串(无填充,URL安全)
+    key_base64 = base64.urlsafe_b64encode(key_bytes).decode().strip("=")
+    print("密钥:", key_base64)