我已经部署了 Azure SignalR 服务,还有 Azure Functions 和带有 HTTPTrigger 的 Negotiate 方法。部署前端+后端部分后,我的前端部分无法连接到 SignalR 服务,但如果我在本地代理时执行此操作 - 它可以工作。我想问题可能出在我的 Azure Front Door 上。但我不知道在哪里查看 Azure Frontdoor 来访问我的 SignalR。
我允许 CORS * 进行测试,但它不起作用,看起来这是一个 Azure 前门阻止了它,因为我们有一项政策,不允许从公共网络访问我们的服务。 所以我试着让你了解如何解决问题,有什么想法吗?我尝试用 google 搜索,但看起来这不是一个完全清楚的 CORS 错误。预先感谢!
这是来自 UI 的代码:
const connection = new signalR.HubConnectionBuilder()
.withUrl(url, {
withCredentials: false,
})
.withAutomaticReconnect()
.configureLogging(signalR.LogLevel.Information)
.build();
这是我在函数应用程序中的后端函数:
[FunctionName(nameof(Negotiate))]
public SignalRConnectionInfo Negotiate(
[HttpTrigger(AuthorizationLevel.Function)] HttpRequest req,
[SignalRConnectionInfo(HubName = "notificationsSignalR", ConnectionStringSetting = "AzureSignalRConnectionString")] SignalRConnectionInfo connectionInfo)
{
return connectionInfo;
}
这是我的部署脚本(已成功部署,连接字符串显示在函数应用程序中):
param namespace_name string
param location string = resourceGroup().location
resource signalR 'Microsoft.SignalRService/signalR@2023-02-01' = {
name: namespace_name
location: location
sku: {
capacity: 2
name: 'Standard_S1'
tier: 'Standard'
}
kind: 'SignalR'
identity: {
type: 'SystemAssigned'
}
properties: {
tls: {
clientCertEnabled: false
}
features: [
{
flag: 'ServiceMode'
value: 'Serverless'
properties: {}
}
{
flag: 'EnableConnectivityLogs'
value: string(true)
}
]
cors: {
allowedOrigins: [
'*'
]
}
serverless: {
connectionTimeoutInSeconds: 30
}
networkACLs: {
defaultAction: 'Deny'
publicNetwork: {
allow: [
'ClientConnection'
]
}
privateEndpoints: [
{
name: 'mySignalRService.1fa229cd-bf3f-47f0-8c49-afb36723997e'
allow: [
'ServerConnection'
]
}
]
}
upstream: {
templates: []
}
}
}
首先,我在 Azure Front Door 中扩展了(如错误所述)此规则:
来自:
"default-src 'self' *.my.com graph.microsoft.com"
致:
"default-src 'self' *.my.com graph.microsoft.com *.service.signalr.net"
修复后我发现第二个类似的错误: 拒绝连接到
'wss://.....service.signalr.net........'
,因为它违反了以下 内容安全策略 指令:"default-src 'self' *.my.com graph.microsoft.com *.service.signalr.net"
。请注意,“connect-src”未明确设置,因此“default-src”用作后备
这是因为 Azure Front Door 不支持 Web Sockets,请参阅: https://github.com/MicrosoftDocs/architecture-center/issues/1891#issuecomment-805714146
因此,对我来说,从 WebSocket 切换到服务器端事件(SSE)是适用的,因为我仅使用从服务器到客户端的方向。之后,一切开始工作。
希望我的回答对某人有帮助。