Reputation: 31
I have a hub with signalR and i want to secure it with the [Authorize] attribute. The hub can gets the user from the JWT token and gives me 401 when the token is invalid so all seems to be ok. But when i publish it to dev environment and the the frontend client connects to the hub it gives an CORS error.
I have a testing client in local and i use it to connect to localhost and even to the hub of development env. From that testing client everything works fine, but not from the frontend of dev environment.
If i remove the [Authorize] attribute all works fine again. No cors error and still can get the user from the token but the hub its not actually secured.
So i assume there has to be some additional configuration that i have missed.
I have tried different configuration of cors policy and none of them changed anything. I also have tried to add the cors policy manually to the hub:
app.MapHub<TestHub>("/hubs/test")
.RequireCors("CorsPolicy")
Upvotes: 2
Views: 445
Reputation: 96
I set the logs to Verbose and got the message in the log: OPTIONS requests are not supported.
I added the middleware from this post (Accepted answer):
Enable OPTIONS header for CORS on .NET Core Web API
Because I am using Authorization header, full block of code with if in the BeginInvoke method in the OptionsMiddleware looks like this:
if (context.Request.Method == "OPTIONS")
{
context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { (string)context.Request.Headers["Origin"] });
context.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Origin, X-Requested-With, Content-Type, Accept, Authorization, x-signalr-user-agent" });
context.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "GET, POST, PUT, DELETE, OPTIONS" });
context.Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });
context.Response.StatusCode = 200;
return context.Response.WriteAsync("OK");
}
Hope it helps, because I was stuck almost two days on this.
Upvotes: 0