简体   繁体   English

授权 signalR 集线器未在 ASP 核心中连接

[英]Authorize signalR Hub not connected in ASP Core

Authorize signalR Hub not getting connect to hub with front end angular, unable to invoke jwt access token to hub connection.授权 signalR 集线器没有连接到前端 angular 的集线器,无法调用 jwt 访问令牌到集线器连接。 How to connect Authurized signalr hub in asp core with angular project i have the following code in my project,如何将 ASP 内核中的授权 signalr 集线器与 angular 项目连接我的项目中有以下代码,

Here my Code这是我的代码

    public class Startup
    {
    readonly string CorsPolicy = "CorsPolicy";
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddCors(options =>
        {
            options.AddPolicy(name: CorsPolicy,
                builder =>
                {
                    builder
                        .AllowAnyHeader()
                        .AllowAnyMethod()

                     .WithOrigins("http://localhost:3000", "http://localhost:4200", "http://localhost:1234")
                        .AllowCredentials();
                });
        });

        services.AddControllers();

        services.AddSignalR()
        .AddJsonProtocol(options =>
        {
            options.PayloadSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
        });

       //jwt token
        services.AddAuthentication(opt =>
        {
            opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            opt.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        })
       .AddJwtBearer(options =>
       {
           options.RequireHttpsMetadata = false;
           options.SaveToken = false;
           options.TokenValidationParameters = new TokenValidationParameters
           {
               ValidateIssuer = false,
               ValidateAudience = false,
               ValidateLifetime = true,
               ValidateIssuerSigningKey = true,

               ValidIssuer = Configuration["Jwt:Issuer"],
               ValidAudience = Configuration["Jwt:Audience"],
               IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])),
               ClockSkew = TimeSpan.Zero
           };

           options.Events = new JwtBearerEvents
           {
               OnMessageReceived = context =>
               {
                   var accessToken = "Bearer " + context.Request.Query["access_token"];

                  var path = context.HttpContext.Request.Path;
                   if (!string.IsNullOrEmpty(accessToken) &&
                      (path.StartsWithSegments("/connecthub")))
                  {
                    //  Read the token out of the query string
                      context.Token = accessToken;
                  }
                  return Task.CompletedTask;
              }
           };

       });

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ApplicationDatabaseContext context)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();

        app.UseAuthorization();

        app.UseCors(CorsPolicy);

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapHub<signalR_Hub>("/connecthub");
        });


       }
    }
}

This my Hub connection这是我的集线器连接

[Authorize]
public class sample_Hub :Hub
{
}

This my controller这是我的 controller

    [Authorize]
    [HttpPut("{id}")]
    public async Task<IActionResult> Putfilecreations(string id, filecreations filecreations)
    {
        var entity = _context.file_creations.Where(x => x.file_creation_id == id).FirstOrDefault();
        entity.client_type_id = filecreations.client_type_id;

         _context.file_creations.Update(entity);
        await _context.SaveChangesAsync();

        await _hubContext.Clients.All.SendAsync("FileUpdated", entity);
        return Ok(entity);
    }

This my Angular code for connect Hub这是我用于连接集线器的 Angular 代码

   this.hubConnection = new HubConnectionBuilder()
  .withUrl(environment.baseUrls.server + 'connecthub')
  .configureLogging(LogLevel.Information)
  .build(); 

Try to add CORS this way, the order is important:尝试这样添加CORS ,顺序很重要:

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

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

相关问题 调用SignalR Hub不适用于Asp.Net Core Web API - Invoking SignalR Hub not working for Asp.Net Core Web API ASP .NET MVC 核心 + SignalR:从集线器重定向到 Controller - ASP .NET MVC Core + SignalR: Redirecting from a Hub to a Controller 来自客户端的集线器方法未在ASP.NET Core SignalR中调用 - Hub method from client is not invoking in ASP.NET Core SignalR ASP.NET Core SignalR可从任何地方访问Hub方法 - ASP.NET Core SignalR acces Hub method from anywhere SignalR集线器Authorize属性不起作用 - SignalR hub Authorize attribute doesn't work 如何使用Cookie授权SignalR集线器连接? - How to Authorize SignalR Hub Connection using Cookie? 获取连接到 SignalR 集线器的侦听器、客户端的数量 - Get number of listeners, clients connected to SignalR hub ASP.NET Core 2 SignalR Hub 接收复杂对象而不是字符串 - ASP.NET Core 2 SignalR Hub to receive complex object instead of string 在两个ASP.NET Core 2.1 Razor Web应用程序中将SignalR既用作集线器又用作客户端 - Use SignalR as both a Hub and a Client in two ASP.NET Core 2.1 Razor web apps 您如何在控制器外部获得对ASP.NET Core SignalR集线器上下文的引用? - How do you get a reference to an ASP.NET Core SignalR hub context outside of a controller?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM