问题描述
我有一个 Angular 应用程序,它通过 SignalR 连接到 Net Core 以获取信息。本地运行完美,但当应用程序执行来自 Azure 的请求时,抛出此错误
WebSocket 连接到“wss://mysite.azurewebsites.net/notifications?id=someId&access_token=sometoken”失败:WebSocket 握手期间出错:意外响应代码:302 错误:无法启动传输“WebSockets”:未定义
但仍在返回数据并进行连接并提供信息,只是控制台上出现烦人的错误
这是我对 signalR 的 Angular Side 调用
private createConnection() {
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl(`${this.libraryConfig.api.notification.baseUrl}/notifications`,{ accesstokenFactory: () => this.access_token })
.build();
}
这是我在 Net Core 上启动的代码
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = "https://sts.windows.net/tenat/v2.0";
options.Audience = Configuration.GetSection("AzureAd").GetSection("Audience").Value;
options.TokenValidationParameters.ValidateLifetime = true;
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accesstoken = context.Request.Query["access_token"];
// If the request is for our hub...
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accesstoken) &&
(path.StartsWithSegments("/notifications")))
{
// Read the token out of the query string
context.Token = accesstoken;
}
return Task.CompletedTask;
}
};
});
注意:我使用 Azure Active Directory 登录客户端
解决方法
您需要在 azure 应用服务中启用 Websocket。它在配置->常规设置
下