asp.net - SignalR + Angular : how to add Bearer token to Http Headers

标签 asp.net angular signalr.client

我制作了一个asp.net core 2.0 SignalR Hub,它使用承载 token 进行身份验证。现在我有点不知道如何通过 SignalR Angular 5 客户端连接到它。如果我从集线器中删除授​​权,我实际上可以连接,因此连接正常,现在我相信我只需将授权承载添加到连接的 Http header 中即可。

package.json 中的 SignalR 客户端引用我的 Angular 5 项目的文件:"@aspnet/signalr-client": "^1.0.0-alpha2-final"

我的 Angular 组件:

import { Component, OnInit } from '@angular/core';
import { finalize } from 'rxjs/operators';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ToastrService } from 'ngx-toastr';
import { AuthenticationService } from '../core/authentication/authentication.service';
import { HubConnection } from '@aspnet/signalr-client';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  quote: string;
  isLoading: boolean;
  jwtToken:string;
  private hubConnection: HubConnection;

  constructor(
    private _http: HttpClient, 
    private _auth : AuthenticationService,
    private _toastr: ToastrService) { }

  ngOnInit() {
    this.isLoading = false;
    this.jwtToken = this._auth.currentToken;

    this.hubConnection = new HubConnection('http://localhost:27081/hub/notification/');
    this.hubConnection
      .start()
      .then(() => console.log('Connection started!'))
     .catch(err => console.error('Error while establishing connection :(', err));        
    this.hubConnection.on("send", data => {
        console.log(data);
    });
  }

  showToastr(){
    this._toastr.success('Hello world!', 'Toastr fun!');
  }

}

由于阅读了类似的问题,我尝试了:this.hubConnection.Headers.Add("token", tokenValue);但它不起作用, Headers 属性不存在。

如何将承载 token 添加到 HubConnection 的 Http header 中?

感谢您的帮助

最佳答案

要使用 @aspnet/signalr (^1.1.4) 执行此操作,您可以使用以下代码

const options: IHttpConnectionOptions = {
  accessTokenFactory: () => {
    return "Token is resolved here";
  }
};

const connection = new signalR.HubConnectionBuilder()
  .configureLogging(signalR.LogLevel.Information)
  .withUrl(`${environment.apiUrl}/notify`, options)
  .build();

同时向您的 Hub 添加注释

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

顺便说一句,SignalR 在使用 websocket 协议(protocol)时似乎没有将 Bearer token 作为 header 附加,而是将其作为“access_token”参数添加到请求 URL 中,这需要您配置身份验证来处理此问题当signalR选择使用ws时的token。

services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
                x.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("/notify")))
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }
                        return Task.CompletedTask;
                    }
                };
            });

关于asp.net - SignalR + Angular : how to add Bearer token to Http Headers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48119106/

相关文章:

c# - 网络表单和依赖注入(inject)

angular - 如何在 Angular html 模板中的属性中应用管道

java - SignalR 调用已取消

javascript - 如何在 SignalR 聊天程序中向离线用户发送消息?

c# - SignalR .NET 客户端不接收消息

javascript - 如何设置文本框的货币格式?

c# - 如何将原始电子邮件字符串解析为 System.Net.Mail.MailMessage 对象?

angular - 在 Angular 4 应用程序中使用 DDP

angular - 在 mat-table 的表标记中使用 multiTemplateDataRows 和 formArrayName 时出错

c# - 如何隐藏空列