Home > Back-end >  Azure SignalR on .Net Core Web API and Angular 12 facing 401 Unauthorized Error
Azure SignalR on .Net Core Web API and Angular 12 facing 401 Unauthorized Error

Time:09-10

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'

enter image description here

Here is my frontend SignalR service

enter image description here

In My Backend Program.cs I have added the SignalR Service and the CORS policy

enter image description here enter image description here This is my Strongly Typed Hub enter image description here

I am adding its dependency to my Trigger service here using hub context. This trigger service is later added to a background process.

enter image description here

Networks Tab

enter image description here

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;
                    }
                };
}
  • Related