Blazor Server共享认证库与SignalR时JWT传递失败问题排查
SignalR JWT认证问题解决指南
客户端:正确传递JWT到SignalR连接
Blazor Server是服务端渲染,无法直接在服务端读取客户端localStorage,必须通过JS互操作获取token,再在SignalR连接时传递:
- 在Blazor组件中注入
IJSRuntime,用于读取localStorage的token - 构建Hub连接时,通过
AccessTokenProvider自动将token附加到请求的access_token查询参数中
示例代码:
@inject IJSRuntime JSRuntime @inject NavigationManager NavigationManager @using Microsoft.AspNetCore.SignalR @implements IAsyncDisposable <button @onclick="ConnectHub">连接SignalR Hub</button> @code { private HubConnection _hubConnection; protected override async Task OnInitializedAsync() { _hubConnection = new HubConnectionBuilder() .WithUrl(NavigationManager.ToAbsoluteUri("/yourHubPath"), options => { // 从localStorage获取JWT options.AccessTokenProvider = async () => await JSRuntime.InvokeAsync<string>("localStorage.getItem", "access_token"); }) .Build(); // 注册消息接收方法 _hubConnection.On<string>("ReceiveMessage", msg => { // 处理消息逻辑 }); } private async Task ConnectHub() { await _hubConnection.StartAsync(); } public async ValueTask DisposeAsync() { if (_hubConnection != null) { await _hubConnection.DisposeAsync(); } } }
服务端:配置JwtBearer从Query参数读取token
默认JwtBearer中间件只会从Authorization头读取token,但SignalR WebSocket/SSE请求不会自动携带该头,需手动配置从查询参数提取:
- 在
Program.cs中添加JwtBearer认证,同时保留已有的Cookie认证 - 重写
OnMessageReceived事件,从Query的access_token参数中提取token - 关闭默认的挑战跳转逻辑,避免和Cookie认证冲突
示例代码:
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using System.Text; var builder = WebApplication.CreateBuilder(args); // 添加认证服务,保留原有Cookie认证,新增JWT认证 builder.Services.AddAuthentication(options => { // 默认认证方案仍使用Cookie,SignalR Hub单独指定JWT options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie() .AddJwtBearer(options => { // 配置JWT验证参数,确保和签发端一致 options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = builder.Configuration["Jwt:Issuer"], ValidAudience = builder.Configuration["Jwt:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])) }; // 关键:从SignalR请求的Query参数中读取token options.Events = new JwtBearerEvents { OnMessageReceived = context => { var accessToken = context.Request.Query["access_token"]; var hubPath = context.HttpContext.Request.Path; // 仅针对SignalR Hub路径提取token if (!string.IsNullOrEmpty(accessToken) && hubPath.StartsWithSegments("/yourHubPath")) { context.Token = accessToken; } return Task.CompletedTask; }, // 关闭默认挑战跳转,避免干扰Blazor Server的Cookie认证流程 OnChallenge = context => { context.HandleResponse(); return Task.CompletedTask; } }; }); // 添加SignalR服务 builder.Services.AddSignalR(); var app = builder.Build(); // 启用认证中间件 app.UseAuthentication(); app.UseAuthorization(); // 映射Hub路由 app.MapHub<YourHub>("/yourHubPath"); app.Run();
Hub指定JWT认证方案
在Hub类上添加[Authorize]特性,并指定使用JwtBearer认证方案,确保Hub使用JWT而非Cookie认证:
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.SignalR; [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public class YourHub : Hub { public async Task SendMessage(string message) { // 此时Context.User已包含JWT中的Claims信息 var userName = Context.User.Identity.Name; await Clients.All.SendAsync("ReceiveMessage", $"{userName}: {message}"); } }
注意事项
- 确保JWT的签发参数(Issuer、Audience、Key)和服务端验证参数完全一致
- 如果是跨域场景,需配置CORS允许
access_token查询参数和WebSocket请求 - 检查客户端localStorage中的
access_token是否有效、未过期 - Blazor Server中必须通过
IJSRuntime读取localStorage,不能直接在服务端代码中访问客户端存储
内容的提问来源于stack exchange,提问作者BlazorStudio
相关产品推荐
相关产品推荐

