Im making a real time chat app with .NET core 8 web api , signalr and angular. I use new authentication system introduced in .NET core 8 with token authentication.
I have implemented authentication from angular frontend and it works correctly and I access authorized methods.
But when I try to authenticate my chat hub it does not recognize it as authenticated user.
Also Context.User?.Identity?.IsAuthenticated this comes as false. but onConnectedAsync function is decorated as authorize and it works.
this is in my frontend chat service constructor where I build connection.
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl(`${this.baseUrl}/chathub`, {
accessTokenFactory: () => this.authService.getToken()
})
.build();
I checked the network tab. access token is sending with the request.
this is my chat hub.
[Authorize]
public override async Task OnConnectedAsync()
{
var userId = Context.UserIdentifier; // Get user ID from authentication
await Clients.All.SendAsync("ReceiveSystemMessage", $"{userId} joined.");
await base.OnConnectedAsync();
}
[Authorize]
public override async Task OnDisconnectedAsync(Exception exception)
{
var userId = Context.UserIdentifier; // Get user ID from authentication
await Clients.All.SendAsync("ReceiveSystemMessage", $"{userId} left.");
await base.OnDisconnectedAsync(exception);
}
It gets connected successfully and sends messages also. but the system message only shows ” joined” without the id.
this is program.cs
// Add Authentication
builder.Services.AddAuthentication().AddBearerToken(IdentityConstants.BearerScheme);
builder.Services.AddAuthorizationBuilder();
builder.Services.AddIdentityCore<User>()
.AddEntityFrameworkStores<Context>()
.AddApiEndpoints();
var app = builder.Build();
app.UseCors();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapIdentityApi<User>();
app.MapControllers();
app.MapHub<ChatHub>("/chathub");
app.Run();
Yuresh Tharushika is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.