fix websocket cookie auth

This commit is contained in:
hjlarry 2025-10-21 11:46:00 +08:00
parent ba17f576e9
commit 8e3b412ff6
2 changed files with 27 additions and 4 deletions

View File

@ -3,8 +3,10 @@ import time
from extensions.ext_redis import redis_client
from extensions.ext_socketio import sio
from libs.token import extract_access_token
from libs.passport import PassportService
from services.account_service import AccountService
from werkzeug.wrappers import Request as WerkzeugRequest
@sio.on("connect")
@ -15,6 +17,14 @@ def socket_connect(sid, environ, auth):
token = None
if auth and isinstance(auth, dict):
token = auth.get("token")
if not token:
try:
request_environ = WerkzeugRequest(environ)
token = extract_access_token(request_environ)
except Exception:
token = None
if not token:
return False

View File

@ -1,5 +1,6 @@
import type { Socket } from 'socket.io-client'
import { io } from 'socket.io-client'
import { ACCESS_TOKEN_LOCAL_STORAGE_NAME } from '@/config'
import type { DebugInfo, WebSocketConfig } from '../types/websocket'
export class WebSocketClient {
@ -40,13 +41,25 @@ export class WebSocketClient {
this.connecting.add(appId)
const authToken = localStorage.getItem('console_token')
const socket = io(this.config.url!, {
const authToken = typeof window === 'undefined'
? undefined
: window.localStorage.getItem(ACCESS_TOKEN_LOCAL_STORAGE_NAME) ?? undefined
const socketOptions: {
path: string
transports: WebSocketConfig['transports']
withCredentials?: boolean
auth?: { token: string }
} = {
path: '/socket.io',
transports: this.config.transports,
auth: { token: authToken },
withCredentials: this.config.withCredentials,
})
}
if (authToken)
socketOptions.auth = { token: authToken }
const socket = io(this.config.url!, socketOptions)
this.connections.set(appId, socket)
this.setupBaseEventListeners(socket, appId)