Context.User.Identity.Name即使在用户身份验证后也是null



我正在尝试使用signalR向blazor服务器中的特定用户发送消息

但问题是,即使用户使用Identity进行了身份验证,Context.User.Identity.Name;Context.UserIdentifier;也是空的。将[Authorize]属性放在hub中会出现一个错误,即Response status code does not indicate success: 401 (Unauthorized).

如果能帮助我的代码,那就太好了,谢谢

下面是我的集线器

namespace WebChat.Hubs
{
[Authorize]
public class ChatHub : Hub
{
public async Task Send(string message, string user)
{
await Clients.User(user).SendAsync("Receive", message);
}
public override async Task OnConnectedAsync()
{
var getUserName = Context.User.Identity.Name;
var getUserIdentifier = Context.UserIdentifier;
UserHandler.UserList.Add(getUserName);
UserHandler.UserList.Add(getUserIdentifier);
await base.OnConnectedAsync();
}
}
public static class UserHandler
{
public static List<string> UserList = new List<string>();
}
}

下面是我的Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>();
services.AddDatabaseDeveloperPageExceptionFilter();
services.AddSingleton<WeatherForecastService>();
services.AddSignalR();
services.AddResponseCompression(opts =>
{
opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "application/octet-stream" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseResponseCompression();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapHub<ChatHub>("/chathub");
endpoints.MapFallbackToPage("/_Host");
});
}

下面是我的剃须刀组件
<AuthorizeView>
Hello, @context.User.Identity.Name! //<----- Shows logged-in user email
<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>
</AuthorizeView>

连接到集线器时,需要将cookie加载到服务器中。请参阅下面的示例。

_hubConnection = new HubConnectionBuilder()
.WithUrl("https://localhost:44313/signalr-hubs/messaging", options =>
{
if (HttpContextAccessor.HttpContext != null)
{
foreach (var cookie in HttpContextAccessor.HttpContext.Request.Cookies)
{
options.Cookies.Add(new Cookie(cookie.Key, cookie.Value, null, "localhost"));  
}
}
}).Build();

最新更新