How to resolve Strict Origin Error at angular app - asp.net-core-webapi

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

Related

Asp.net CORS is configured, but not working

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.

CORS Angular 10 ASP.Net

I have an application written in Angular 10 and Angular Material talking to my backend in ASP.Net on the same server but different port.
For example: (Angular Front End) http://something.com:5000 --> (ASP Back End) http://something.com:5100
I am getting blocked by CORS unless I use the MOESIF CORS Extension.
I am adding the 'DisableCors' tag to each method in ASP like so:
[HttpGet("Travelers")]
[DisableCors]
public IEnumerable<PDox_Trav> Get_Trav()
In my 'Startup.cs' I have this:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options => {
options.AddDefaultPolicy(builder => {
builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin();
});
});
services.AddControllers();
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
What am I missing? Do I need something in my Frontend too? I did not think I did...
I am adding cors as bellow.I used this method in few project and it worked.
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>{
builder
.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins("http://localhost:5000","http://localhost:4200");
}));

The CORS error occurred on SignalR negotiation phase

I have the following error in Console after migration from Asp.net core 2.2 to 3.1
Access to XMLHttpRequest at 'someuri/negotiate?negotiateVersion=1' from
origin 'http://localhost:4208'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested
resource.
And the following SignalR configuration:
app.UseCors(Constants.Policy);
app.UseAuthentication();
app.UseEndpoints(
endpoints =>
{
endpoints.MapHub<SomeHub>("/ws/someuri");
});
I've added the following policy:
options.AddPolicy(Constants.Policy,
p =>
p.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.WithOrigins("http://localhost:4208"));
But it didn't help.
You should configure the CORS this way and the order is important!
On your configure method:
public override void Configure(IApplicationBuilder app, HostConfiguration hostConfiguration, ILogger<Startup> logger)
{
base.Configure(app, hostConfiguration, logger);
app.UseWebSockets();
app.UseCors(CorsPolicy); // first configure CORS, then map Hub
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<SomeHub>("/someuri");
});
}
Then when adding CORS:
/// <summary>
/// Adds the CORS.
/// </summary>
private void AddCors(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(CorsPolicy, builder => builder.WithOrigins("http://localhost:4208")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.SetIsOriginAllowed((host) => true));
});
}
You can see more detailed answer here.

asp.net core 2.2 redirect identity loginpath

in our current setup we have a known path for logging in.
But now that we are using core 2.2 I cannot fix the current problem; That is always using loginPath: /Identity/Account/Login but we would like to change this.
Reading a lot on StackOverflow and others, I cannot seem to fix it.
So now i have a complete new MVC app trying to figure out what I am doing wrong.
In my startup I have:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<IdentityUser, IdentityRole>()
// .AddDefaultUI()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = new PathString("/Account/Login2");
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
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.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
What am I doing wrong? Better yet; what is the solution :)
so as it turns out;
I needed to scaffold an identity item (like login) and in the login razor page (login.cshtml) you can add:
#page "~/account/login2"
this is probably also you can fix with the routing in razor during startup:
.AddRazorPagesOptions(options => {...});
haven't tried it out yet, but that is something else..
cheers

Net 2.1, Angular 7, blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested

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");

Resources