gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 13:20:47 25 4
gpt4 key购买 nike

我制作了一个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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com