在我的示例项目中,SignalR和WebSocket Trasport协议存在问题。 当我尝试在AuthorizeAttribute下连接集线器时,响应为:
Microsoft.AspNetCore.Hosting.Internal.WebHost:信息:请求启动HTTP / 1.1 POST http://localhost:44341/chat/negotiate文本/纯文本;字符集= UTF-8 0 Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information:策略执行成功。 Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler:信息:已成功验证令牌。 Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:信息:授权成功。 Microsoft.AspNetCore.Hosting.Internal.WebHost:信息:请求已在37.4131ms中完成200 application / json Microsoft.AspNetCore.Hosting.Internal.WebHost:信息:请求启动HTTP / 1.1 GET http://localhost:44341/chat?id=bSfQQIMQk3-AWf7jTVfwsw&access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYW5kcmVhLnRvc2F0byIsImV4cCI6MTUzNDQ5OTI5NywiaXNzIjoiY2xvdWRnZW4uY29kZWdlbi5jb20iLCJhdWQiOiJjbG91ZGdlbi5jb2RlZ2VuLmNvbSJ9.47NxR5bGKWqPyPDi7Yz_PaYJTHKUJcJyRWfftxJRBq4
Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information:策略执行成功。 Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:信息:授权失败。 Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler:信息:AuthenticationScheme:承载受到了挑战。
客户端,在WebSocket之后,服务器发送事件失败。使用Long-polling,一切正常。
我的客户:
this.connection = new HubConnectionBuilder()
.withUrl(environment.baseHubs + '/chat', {
accessTokenFactory: () => token,
logger: LogLevel.Trace
})
// .withHubProtocol(new JsonHubProtocol())
.withHubProtocol(new MessagePackHubProtocol())
.build();
this.connection.start()
.catch(this.errorConnection.bind(this))
.then(x => {
this.connection.invoke('GetUserContext').then(this.getUserContext.bind(this));
});
我的服务器代码:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Authentication:Issuer"],
ValidAudience = Configuration["Authentication:Audiance"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Authentication:SecurityKey"]))
};
});
答案 0 :(得分:0)
分辨率:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Authentication:Issuer"],
ValidAudience = Configuration["Authentication:Audiance"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Authentication:SecurityKey"]))
};
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
if (!string.IsNullOrEmpty(accessToken))
{
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});