You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python后端连接Azure SignalR遇403错误及正确接入方法咨询

你用错库了——CommunicationIdentityClient是Azure通信服务(ACS)的身份管理工具,和Azure SignalR Service完全不兼容,这就是触发403错误的原因。以下是两种后端对接Azure SignalR的正确方案:

场景1:后端直接推送消息到SignalR(推荐)

用Azure SignalR官方Python SDK直接向指定Hub、用户或组发送消息。

步骤1:安装依赖

pip install azure-signalr

步骤2:编写推送代码

from azure.signalr import SignalRClient

# 你的Azure SignalR连接字符串
connection_string = "Endpoint=https://signalrpro.service.signalr.net;AccessKey=acc;Version=1.0;"

# 初始化客户端
client = SignalRClient.from_connection_string(connection_string)

# 配置推送参数
hub_name = "YourHubName"  # 替换为你的SignalR Hub名称
message_method = "ReceiveMessage"  # 客户端监听的消息方法名
message_content = {"text": "Hello from Python backend!"}  # 消息内容

# 发送消息
client.send(hub_name, message_method, message_content)
print("消息已成功推送")

场景2:生成SignalR客户端访问令牌

如果需要给前端/客户端生成合法的连接令牌,可通过HMAC-SHA256签名手动生成:

import time
import urllib.parse
import hmac
import hashlib
import base64

def generate_signalr_token(connection_string, hub_name, user_id=None, expires_in=3600):
    # 解析连接字符串参数
    conn_params = dict(p.split('=') for p in connection_string.split(';') if p)
    endpoint = conn_params['Endpoint'].rstrip('/')
    access_key = conn_params['AccessKey']
    
    # 构造签名基础参数
    timestamp = int(time.time()) + expires_in
    audience = urllib.parse.quote_plus(f"{endpoint}/client/hubs/{hub_name}")
    
    # 拼接签名字符串
    if user_id:
        user_id_encoded = urllib.parse.quote_plus(user_id)
        signature_string = f"{audience}\n{timestamp}\n{user_id_encoded}"
    else:
        signature_string = f"{audience}\n{timestamp}"
    
    # HMAC-SHA256签名
    key = base64.b64decode(access_key)
    signature = hmac.new(key, signature_string.encode('utf-8'), hashlib.sha256).digest()
    signature_encoded = base64.b64encode(signature).decode('utf-8')
    
    # 组装最终令牌
    token_params = {
        "aud": audience,
        "exp": timestamp,
        "sig": signature_encoded
    }
    if user_id:
        token_params["nameid"] = user_id
    
    token_parts = [f"{k}={urllib.parse.quote_plus(str(v))}" for k, v in token_params.items()]
    return f"Bearer {'&'.join(token_parts)}"

# 使用示例
hub_name = "YourHubName"
user_id = "user_123"  # 可选:指定用户ID实现定向推送
token = generate_signalr_token(connection_string, hub_name, user_id)
print(f"生成的SignalR访问令牌:{token}")

关键注意事项

  • 确保Azure SignalR实例的防火墙/网络规则允许后端服务器的IP访问,否则会触发403错误。
  • 若使用Azure AD身份验证替代连接字符串,可通过DefaultAzureCredential获取令牌,需给服务主体或托管Identity分配SignalR App Server角色。

内容的提问来源于stack exchange,提问作者Debjyoti Sutradhar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 11:10:03