I am trying to connect my backend server on .Net Core to my front end on Angular using the Azure SignalR service. I am getting the following error
Error: Failed to complete negotiation with the server: Error: Unauthorized: Status code '401'
Here is my frontend SignalR service
In My Backend Program.cs I have added the SignalR Service and the CORS policy
I am adding its dependency to my Trigger service here using hub context. This trigger service is later added to a background process.
Networks Tab
So the flow is like this. Angular sends an HTTP post request, which sets the background service in motion. When the process completes, I want to send the push notification to the Angular front end that the process is complete using SignalR. I am trying to do that but am getting this unauthorized error for some reason.
CodePudding user response:
You are not sending the token for authentication.
First you need to change the createConnection from Angular:
.withUrl("https://localhost:7226/hub/generation", { accessTokenFactory: () => this.loginToken })
this.loginToken is the token you send everytime for other api request.
Second thing to change (assuming your using JWT for auth):
.AddJwtBearer(cfg =>
{
cfg.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["authorization"];
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hub/generation"))
{
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
}