Como diz no título, estou com um problema de CORS com as Credentials usando o SignalR, o erro retornado é:
Access to fetch at
https://localhost:54083/notification/negotiate?negotiateVersion=1
from originhttp://localhost:3000
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.
O meu problema é que eu já adicionei no meu Startup.cs, em services.AddCors
, o método AllowCredentials()
, e agora tenho ficado sem muitas opções de como resolver.
Segue meus métodos ConfigureServices
e Configure
de Startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
services.ConfigureCloudFoundryOptions(Configuration);
services.AddSession();
services.AddControllersWithViews();
services.AddControllers();
services.AddControllers().AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
services.AddCors(options =>
{
options.AddPolicy("ClientPermission", policy =>
{
policy.AllowAnyHeader()
.AllowAnyMethod()
.WithOrigins("http://localhost:3000")
.AllowCredentials();
});
});
services.AddSignalR();
var key = Encoding.ASCII.GetBytes(Configuration.GetValue<string>("JWT:Key"));
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
x.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
// If the request is for our hub...
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) &&
(path.StartsWithSegments("/notification")))
{
// Read the token out of the query string
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
services.AddSingleton<IUserIdProvider, NameUserIdProvider>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/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.UseCors("ClientPermission");
app.UseRouting();
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<NotificationHub>("/notification");
});
}
}
O frontend é em React e é feito o consumo do serviço do SignalR desta forma aqui:
useEffect(() => {
const newConnection = new HubConnectionBuilder()
.withUrl("https://localhost:54083/notification")
.withAutomaticReconnect()
.build();
setConnection(newConnection);
}, []);
useEffect(() => {
if (connection) {
console.log(connection)
connection
.start()
.then((result) => {
console.log("Connected!");
connection.on("ReceiveMessage", (message) => {
setNotifications(...notifications.push(message));
});
})
.catch((e) => console.log("Connection failed: ", e));
}
}, [connection]);
WithCredentials()
não é mais utilizado, aparentemente.