And*_*uiz 3 asp.net signalr.client angular
我制作了一个使用Bearer令牌进行身份验证的asp.net核心2.0 SignalR集线器。现在我对如何通过SignalR Angular 5客户端连接到它有些迷茫。如果我从集线器中删除授权,我实际上可以连接,因此连接可以正常工作,现在我相信我只需要将授权承载添加到连接的Http标头中即可。
package.json我的Angular 5项目文件中的SignalR客户端参考:"@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!');
}
}
Run Code Online (Sandbox Code Playgroud)
由于阅读了类似的问题,因此尝试了以下操作:this.hubConnection.Headers.Add("token", tokenValue);但这不起作用,因此Headers属性不存在。
如何将Bearer令牌添加到HubConnection的Http标头中?
谢谢你的帮助
Dax*_*xxy 16
要使用@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();
Run Code Online (Sandbox Code Playgroud)
还要向您的中心添加注释
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
Run Code Online (Sandbox Code Playgroud)
作为旁注,SignalR 在使用 websocket 协议时似乎没有将 Bearer 令牌附加为标头,而是将其作为“access_token”参数添加到请求 URL 中,这需要您配置身份验证以在 signalR 时处理此令牌选择使用 ws。
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;
}
};
});
Run Code Online (Sandbox Code Playgroud)
通过阅读他们的源代码和测试,您似乎可以提供一个包含访问令牌的options对象,如下所示
var options = {
transport: transportType,
logging: signalR.LogLevel.Trace,
accessToken: function () {
return jwtToken;
}
};
hubConnection = new signalR.HubConnection('/authorizedhub', options);
hubConnection.start();
Run Code Online (Sandbox Code Playgroud)
在测试文件中特别的代码在这里
| 归档时间: |
|
| 查看次数: |
4657 次 |
| 最近记录: |