asp.net 错误:无法完成与服务器的协商:错误:状态代码'401'

owfi6suc  于 2023-01-14  发布在  .NET
关注(0)|答案(1)|浏览(157)

我正在使用SignalR和angular在客户端之间创建一个聊天,在客户端使用jwt令牌成功登录后。

[Authorize]

连接到我的集线器,我在尝试连接到SignalR时收到此错误-
调试:由于错误“错误:无法完成与服务器的协商:错误::状态代码“401”。
在添加此属性之前,我的应用已成功连接到SignalR,因此我知道问题出在授权上。
用户中心-

[Authorize]
public class UserHub : Hub

Program.cs-

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy", builder => builder
        .WithOrigins("http://localhost:4200")
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials()
        .SetIsOriginAllowed((host) => true));
});

builder.Services.AddDbContext<TalkBackDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("TalkBackConnectionString")));

builder.Services.AddScoped<IContactRepository, ContactsRepository>();
builder.Services.AddScoped<IWebAPIService, WebAPIService>();
builder.Services.AddScoped<ISignalrService, SignalrService>();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSignalR(); 
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters()
    {
        ValidateIssuer = false,
        ValidateAudience = false,
        ValidAudience = builder.Configuration["Jwt:Audience"],
        ValidIssuer = builder.Configuration["Jwt:Issuer"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
    };
    options.Events = new JwtBearerEvents
    {
        OnMessageReceived = context =>
        {
            var accessToken = context.Request.Query["access_token"];
            var path = context.HttpContext.Request.Path;
            if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/user")))
            {
                context.Token = accessToken;
            }
            return Task.CompletedTask;
        }
    };
});

客户-

public startSignalrConnection(connectionUrl: any) {
return new Promise<any>((resolve, reject) => {
  this.hubConnection = new HubConnectionBuilder()
    .withUrl(connectionUrl, { 
      withCredentials: false,
    accessTokenFactory: () => localStorage.getItem('jwt')!,
   })
    .configureLogging(LogLevel.Debug)
    .build();
ygya80vv

ygya80vv1#

多次尝试后,我发现了问题所在,我错过了Programidocs上的这一行-

app.UseAuthentication();

我还编辑了我的令牌(在另一个微服务上),使其与此处相同,并添加了以下行-

ValidateIssuerSigningKey=true

现在我可以访问SignalR了。

相关问题