Reputation: 101
I got Cors policy error when trying to do POST request to the web api from my WASM blazor app.
Access to fetch at 'http://localhost:8080/DashboardService/TestConnection' from origin 'https://localhost:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I have no problem in debug mode, only with IIS publish
Startup.cs (WEB API)
public class Startup
{
#region Fields/Attributes
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
private readonly IConfiguration configuration;
#endregion Fields/Attributes
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Startup"/> class.
/// </summary>
/// <param name="configuration">The configuration identifier</param>
public Startup(IConfiguration configuration)
{
logger.Trace($"{GetType().FullName} constructed");
this.configuration = configuration;
}
#endregion Constructors
#region Methods
/// <summary>
/// This method gets called by the runtime. Use this method to add services to the container.
/// </summary>
/// <param name="services">The service collection identifier</param>
public void ConfigureServices(IServiceCollection services)
{
// Statistics And Monitoring Service
services.AddSingleton<IDashboardService, DashboardService>();
services.AddSingleton<IManualLogsService, ManualLogsService>();
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddCors(options => options.AddPolicy("CorsPolicy2",
builder =>
{
builder.WithOrigins("https://localhost:8081").AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
}));
services.AddSignalR(options =>
{
options.EnableDetailedErrors = true;
options.MaximumReceiveMessageSize = long.MaxValue;
options.ClientTimeoutInterval = TimeSpan.FromSeconds(240);
options.KeepAliveInterval = TimeSpan.FromSeconds(120);
})
string identityServerAuthority = "https://localhost:8082";
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, opt =>
{
opt.RequireHttpsMetadata = false;
opt.Authority = identityServerAuthority;
opt.Audience = "backend";
});
logger.Trace($"Services configured");
}
/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// </summary>
/// <param name="app">The application builder identifier</param>
/// <param name="env">The web host environement identifier</param>
/// <param name="agentsService">The AgentsService identifier</param>
/// <param name="collectedValueConverter">The CollectedValueConverter identifier</param>
/// <param name="databaseConnectionService">The DatabaseConnectionService identifier</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Dependency injecting only to force instantiation of Singletons")]
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IDataBaseServiceApplicationConfig dataBaseServiceApplicationConfig, IAgentsService agentsService, IMachineStructureService machineStructureService, ICollectedValueConverter collectedValueConverter, IDatabaseConnectionService databaseConnectionService)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
//app.UseHsts();
}
//app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("CorsPolicy2");
app.UseAuthentication();
app.UseAuthorization();
app.UseStaticFiles();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<BackEndHub>("/DashboardService");
});
}
#endregion Methods
}
I got [Authorize] attributes on my controller, if I remove them it's working...
Could anyone help me with that ? Thanks in advance
Rihen
Upvotes: 0
Views: 714
Reputation: 101
Problem solved: I went to the Event Viewer in windows and was able to see the REAL error, it was a SSL certificate problem. My backend was http, and wasn't accepted like this by identity server. We turned the backend to https and used the Development certificate. We face the same problem, but this time it was the certificate that were stocked in Personal and not Trusted. The steps to manage this: Windows-> Run-> mmc.exe --> Certificate --> this computer--> local--> copy localhost certificate in trusted.
Thanks to everybody for the help.
Upvotes: 0
Reputation: 19941
First problem that I see is that these two lines are in the wrong order:
app.UseAuthorization();
app.UseAuthentication();
You should always do authentication before authorization.
You should also be aware that you have a separate CORS settings in IdentityService client definitions, but these (if I am not wrong) are only applied when you call the IdentityServer endpoints.
Upvotes: 0