【发布时间】:2020-10-04 01:49:54
【问题描述】:
我在搞乱 Blazor + SignalR 连接。我想使用 JWT 授权对 SignalR 的调用。
基本上我想附加到 SignalR 调用 JWT
这是我的 Blazor WASM SignalR 代码
@page "/"
@using Microsoft.AspNetCore.SignalR.Client
@inject NavigationManager NavigationManager
@implements IDisposable
<div class="form-group">
<label>
User:
<input @bind="userInput" />
</label>
</div>
<div class="form-group">
<label>
Message:
<input @bind="messageInput" size="50" />
</label>
</div>
<button @onclick="Send" disabled="@(!IsConnected)">Send</button>
<hr>
<ul id="messagesList">
@foreach (var message in messages)
{
<li>@message</li>
}
</ul>
@code {
private HubConnection hubConnection;
private List<string> messages = new List<string>();
private string userInput;
private string messageInput;
protected override async Task OnInitializedAsync()
{
hubConnection = new HubConnectionBuilder()
.WithUrl(NavigationManager.ToAbsoluteUri("/chathub"))
.Build();
hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
{
var encodedMsg = $"{user}: {message}";
messages.Add(encodedMsg);
StateHasChanged();
});
await hubConnection.StartAsync();
}
Task Send() =>
hubConnection.SendAsync("SendMessage", userInput, messageInput);
public bool IsConnected =>
hubConnection.State == HubConnectionState.Connected;
public void Dispose()
{
_ = hubConnection.DisposeAsync();
}
}
但我不确定如何将 JWT 附加到此
我在 Js 版的章节中看到过这个
Bearer token authentication 在
this.connection = new signalR.HubConnectionBuilder()
.withUrl("/hubs/chat", { accessTokenFactory: () => this.loginToken })
.build();
Blazor 的做法是什么?
我试过了:
var token = "eyJhb(...)";
hubConnection = new HubConnectionBuilder()
.WithUrl($"{Configuration["Url"]}/chathub", (HttpConnectionOptions x) =>
{
x.Headers.Add("Authorization", $"Bearer: {token}");
})
.Build();
但它抛出了错误:
Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: The format of value 'Bearer: eyJh' is invalid.
System.FormatException: The format of value 'Bearer: eyJhbG' is invalid.
【问题讨论】:
-
@HenkHolterman 这很奇怪,因为我在
Insomnia中使用该令牌来ping 具有Authorize属性的端点并且它工作正常,同时没有这个令牌我收到@987654329 @。我也在jwt.io上试过,它说signature verified(OK)所以看起来令牌是OK
标签: jwt signalr blazor blazor-client-side