I have a web API written in asp.net core 5.
CORS is configured like below:
services.AddCors(options =>
{
string[] allowedOrigins = _config.GetValue<string>("AllowedOrigins")?.Split(",") ?? new string[0];
options.AddPolicy("Default", builder =>
{
builder.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.WithOrigins("http://localhost:4200");
});
options.AddPolicy("AllowAnyThing", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
// .AllowCredentials();
});
options.AddPolicy("Controlled", builder =>
{
builder.WithOrigins(allowedOrigins);
});
});
and appsettings.json contains the below part:
"AllowedOrigins": "http://localhost:4200,https://localhost:4200",
the client is Angular 11.2
when I try to consume the api through the client application,
it fires up "CORS ERROR" even if I remove and disable CORS in API.
I think the problem is from client side, but I don't know how to fix it.
Thank you for your time and attention.
Related
I have enabled Cors in ASP.Net Core API but after publishing I am still getting error with strict-origin-when-cross-origin.My Program.cs looks like below. I have tried other ways to add the URL of the client as well. I am not sure what causing this error. Any help is appreciated.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors();
builder.Services.AddControllers();
builder.Services.AddRazorPages();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors(x => x
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true) // allow any origin
.AllowCredentials()); // allow credentials
app.UseAuthorization();
app.UseEndpoints(x => x.MapControllers());
app.Run();
I have followed all possible ways listed on MS Website.
https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-7.0
I am using openiddict for custom sso and want to host login ui on a separate domain in spa application. The issue I am facing is propper configuration of challenge action.
I've tried to overwrite OnRedirectToLogin event but that obviously not working
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.Events = new CookieAuthenticationEvents()
{
OnRedirectToLogin = async (context) =>
{
context.HttpContext.Response.Redirect("https://example.com/account/login");
}
};
});
Am I doing smth wrong?
The solution to the following issue was found in this answer
Code to add:
services.ConfigureApplicationCookie(options =>
{
options.Events.OnRedirectToLogin = context =>
{
context.HttpContext.Response.Redirect("http://example.com/login");
return Task.CompletedTask;
};
});
I am getting blocked by CORS policy. I have allowed access to all in my startup.cs This is my startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddDbContext<Models.StockContext>(opt => opt.UseInMemoryDatabase("item"));
app.UseCors(builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowCredentials()
.AllowAnyHeader();
});
just add this lines in your ConfigureServices part and it should work fine:
var corsBuilder = new CorsPolicyBuilder();
corsBuilder.AllowAnyHeader();
corsBuilder.WithMethods("GET", "POST");
corsBuilder.AllowAnyOrigin();
services.AddCors(options => options.AddPolicy("AllowAll",corsBuilder.Build()));
Please follow the documentation.
First, you need to enable CORS middleware inside ConfigureServices()
Second, you need to tell application to use this middleware inside Configure()
Example:
In ConfigureServices():
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins",
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
In Configure():
app.UseCors("AllowAllOrigins");
In my startup file I have below code
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// app.UseMvcWithDefaultRoute();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
);
app.UseMvc();
app.UseExceptionHandler();
app.Run(async (context) =>
{
await context.Response.WriteAsync("Web API running!");
});
}
I'm using angular from front end side and whenver there's bad route from UI .net core send status 200 with Web API running message which is bad.
I want to throw 404 when requested with bad routes.
The reason this is happening is because MVC middleware would pass the request to the next middleware when it doesn't find any route for the request.
So the request would hit the last middleware that you wrote which says "Web API running!"
Why do you need that? Either delete that middleware or at least you can configure it to only work with specific path.
app.Map(new PathString("/monitor"), monitorApp =>
{
monitorApp.Run(async (context) =>
{
await context.Response.WriteAsync("Web API running!");
});
});
I am actually creating a chat with angular 5 and signalR on an ASP.NET Framework API. I followed the documentation but it's still not work. Here is my hub:
public class ChatHub : Hub
{
public void Hello()
{
Clients.All.hello();
}
}
Here is my startup class:
app.Map("/signalr", map =>
{
// Setup the CORS middleware to run before SignalR.
// By default this will allow all origins. You can
// configure the set of origins and/or http verbs by
// providing a cors options with a different policy.
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
EnableJSONP = true
};
// Run the SignalR pipeline. We're not using MapSignalR
// since this branch already runs under the "/signalr"
// path.
map.RunSignalR(hubConfiguration);
});
and here is my angular part which create the hubconnection:
ngOnInit() {
this._hubConnection = new HubConnection('http://localhost:58525/signalr/hubs');
this._hubConnection
.start()
.then(() => console.log('Connection started!'))
.catch(err => console.log('Error while establishing connection :( : ' + err));
this._hubConnection.on('send', data => {
console.log(data);
});
}
I get this error:
If your ASP.NET page runs on another server, then your URL looks not correct.
https://learn.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client#crossdomain
You have to connect to:
this._hubConnection = new HubConnection('http://localhost:58525/signalr');