繁体   English   中英

将 JWT 令牌与 SignalR 一起使用

[英]Use JWT Token with SignalR

我想使用 JWT 令牌接收 signalR 请求。 但是当 React 应用程序尝试启动连接时会发生错误。 我收到类似这样的错误 ERROR: Cross-Origin Request Blocked: Same Origin Policy disallows reading the remote resource at https://localhost:5001/hub/users/negotiate?negotiateVersion=1。 (原因:CORS 请求没有成功)。 状态码:(空).2

错误是什么?

反应代码

export const connect = (url: string) => {
  const { token } = importFromLocalStorage('user');
  const connect = new HubConnectionBuilder()
    .withUrl(url, { accessTokenFactory: () => `Bearer ${token}` })
    .withAutomaticReconnect()
    .build();
  return connect;
};

.NET 配置代码

builder.Services.AddCors(options => options.AddDefaultPolicy(builder =>
{
    builder.WithOrigins("http://localhost:3000")
        .AllowAnyHeader()
        .AllowAnyMethod()
        .AllowCredentials();
}));

builder.Services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters()
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            RequireExpirationTime = true,
            ValidIssuer = builder.Configuration["Jwt:Issuer"],
            ValidAudience = builder.Configuration["Jwt:Audience"],
            ClockSkew = TimeSpan.Zero,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration[signinKey]))
        };
        
        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("/hub")))
                {
                    context.Token = accessToken;
                }
                return Task.CompletedTask;
            }
        };
    });

.NET 轮毂代码

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class UsersHub : Hub
{
    public override Task OnConnectedAsync()
    {
        var x = this.Context.ConnectionId;
        return base.OnConnectedAsync();
    }
}

您只允许来自域http://localhost:3000的来源。

确保您也允许https://localhost:5001

builder.Services.AddCors(options => options.AddDefaultPolicy(builder =>
{
    builder.WithOrigins("http://localhost:3000", "https://localhost:5001")
        .AllowAnyHeader()
        .AllowAnyMethod()
        .AllowCredentials();
}));

我相信你有app.UseCors(); 在您的配置方法中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM