CORS not working in ASP.NET core Web API project - c#

I built an ASP.NET core Web API (net core 3.1), and I try to enable CORS but it seems not working.
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowMyOrigin",
builder =>
{
builder.SetIsOriginAllowed(t => true)
.AllowCredentials();
});
});
...
}
‌
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("AllowMyOrigin");
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseHttpsRedirection();
}
Controller:
[Route("api/[controller]")]
[ApiController]
public class airdata_updateController : ControllerBase
{
[EnableCors("AllowMyOrigin")]
[HttpGet]
public string test()
{
return "ok";
}
...
}
I use Postman test my API on local computer and it working well:
local computer
But I use Postman on other computer in the same LAN to call my API, it failed:
other computer
What should I do?

Try this:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddCors();
...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseCors(
options => options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()
);
...
}
You won't need any decorators in your controller methods, the specified CORS policy ( AllowAnyOrigin, AllowAnyHeader, AllowAnyMethod) is applied in all of them. In order to customize the policy, check https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1

maybe this option can help you.
services.AddCors(options =>
{
options.AddPolicy("AllowMyOrigin",
builder => builder
.AllowAnyMethod()
.AllowAnyHeader()
.AllowAnyOrigin()
);
});

Related

How to troubleshoot cors error on IIS server

I'm working on an application which the backend is a net core API with SignalR and the front end is Angular. Debugging on my computer it works as expected but when I publish on the server it shows Cors error even after enabling them on the startup.cs.
This is the error Im getting:
Access to XMLHttpRequest at 'http://server:10079/fareg/api/account' from origin 'http://server' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Can anyone please help to identify what I'm doing wrong to get ride of the CORS error?
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//add Windows authentication for http options request
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
services.AddDbContext<FAContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("FADB")));
services.AddCors(options =>
{
options.AddPolicy(name: _MyCors, builder =>
{
builder
.SetIsOriginAllowed(origin => new Uri(origin).Host == "server name")
//.WithOrigins("http://server/fareg", "http://localhost:4200")
.AllowCredentials()
.AllowAnyHeader()
//.SetIsOriginAllowed(_ => true)
.AllowAnyMethod();
});
});
services.AddSignalR().AddMessagePackProtocol();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(_MyCors);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseSignalR(routes =>
{
routes.MapHub<Hubs.HubFA>("/signalr");
});
app.UseMvc();
}
}
you put the UseCors() in a wrong place. Try to use this syntax
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy(_MyCors,
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
.....
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
.....
// app.UseRouting();
app.UseCors(_MyCors);
// app.UseAuthorization();
// app.UseEndpoints(..
}
Make sure that UseCors should be in the end of Configure method but before UseAuthorizaton. In your case it should be just above UseMvc(). But AddCors should be moved to the top of Configure services.
If this syntax is working for you, only after this you can try to add useorigin.

AllowAnonymous doesn't work as expected in Web API

In an ASP.NET CORE 3.1 Server-Side Blazor app, I am not able to get the AllowAnonymous working for a post type of request web API. The get requests do not have any issues.
Along with the solution for it work, please advise me about the needed security. Perhaps I lowered the security in my trials to get the post request work.
These 3 logs appear for every post request:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
....
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddDefaultUI()
.AddEntityFrameworkStores<EpisodeContext>();
services.AddMvc(options=> {
options.RespectBrowserAcceptHeader = true; })
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddRazorPages();
services.AddServerSideBlazor().AddCircuitOptions(option => { option.DetailedErrors = true; });
services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<ApplicationUser>>();
services.AddHttpContextAccessor();
services.AddAuthorization(config =>
{
config.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.AddPolicy("RequireAdministratorRole",
policy => policy.RequireRole("admin"));
});
...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
API Controller:
[AllowAnonymous]
[Route("api/[controller]")]
[ApiController]
[Produces("application/json")]
public class DailyContentController : ControllerBase
{
[HttpPost("likeepisode"), AllowAnonymous]
public async Task<bool> LikeEpisode(string episodenumber)
{
bool result = await _CDService.LikeEpisode(episodenumber);
return result;
}
}
Plesk Hosting Settings:
Web Application Firewall
I have been able to stop the unintended redirect by setting the preferred domain to none in the hosting settings:

How can I solve the CORS error in this C# code?

I have CORS error in my .NETCore+React app. To solve that I've decided to add some configurations in my backend.
public Program(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddDefaultPolicy(builder => {
builder.WithOrigins("http://127.0.0.1:3000/");
});
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(x=> x
.AllowAnyHeader().AllowAnyMethod().SetIsOriginAllowed(origin=>true).AllowCredentials()
);
}
I wrote it on my Program.cs file. But i still have CORS error. Where did i go wrong?
PS: I am using .NET 2.1
This solved my issue with CORS
In ConfigureService method I used the below snippet to allow all origins
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options=>{
options.AddPolicy("CorsPolicy",HostBuilder=>HostBuilder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
});
}
In configure method just use
app.UseCors("CorsPolicy");
you can
add "proxy": "http://serverip:port" into package.jsonfile of react app
use nginx proxy your react app api
add code to Startup.cs of webapi
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options => {
options.AddPolicy("any", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors("any");
}
I recommend the first method
You need to add the Any-Methods in your builder
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddDefaultPolicy(builder => {
builder.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.WithOrigins("http://127.0.0.1:3000/");
});
});
}
In your Configure method you now only need to write
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
app.UseCors();
...
}
Keep in mind, this only allows cross origin requests from the specified origin, in this case http://127.0.0.1:3000, if you want to allow requests from anywhere, you can replace .WithOrigins(...) with .AllowAnyOrigin()
In case you don't want to override the default policy, you can also add a name
options.AddDefaultPolicy("MyPolicy", builder => {
builder.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.WithOrigins("http://127.0.0.1:3000/");
});
but now you would need to write
app.UseCors("MyPolicy");
You can apply this policy to your controller/actions with
[EnableCors("MyPolicy")]

Cors implementation in .Net Core 3.1 project with Oracle Database Host

Only one HOST can connect to the API, in this case it is an Oracle server.
I added Cors as per Microsoft docs, still other HOST can connect to my API. Has anyone tried to add an Oracle Database HOST? Is there something wrong with the configuration?
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddHttpClient();
services.AddCors(options =>
{
options.AddPolicy(name: "CorsPolicy",
builder =>
{
builder.WithOrigins("http://oraas1111.net:1001")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireCors("CorsPolicy");
});
}
Controller.cs
[EnableCors("CorsPolicy")]
[Route("[controller]")]
[ApiController]
public class Controller : ControllerBase
{
[HttpPost]
[Route("/Service/[action]")]
public async Task<ActionResult<Request>> Update(Request data)
{
}
[HttpGet]
[Route("/GET_Service/[action]")]
public ActionResult Test()
{
return Ok();
}
}
You have to move services.AddCors() to the top, before AddControllers()

How to add the "Access-Control-Allow-Credentials" request header to a POST request in ASP.NET?

So, I am trying to set the "Access-Control-Allow-Credentials", using the HttpContext.Request.Headers.Add("Access-Control-Allow-Credentials", "true"); , but it will only work for my GET requests, but not for my POST ones, and i don't know why.
I've also tried to set those in Startup.cs, as so:
services.AddCors(o => o.AddPolicy("ApiCorsPolicy", builder =>
{
builder
.WithOrigins("My_Web_App")
.AllowCredentials()
.AllowAnyMethod()
.AllowAnyHeader();
}));
And then use it in Configure with app.UseCors("ApiCorsPolicy");
That's the code from my controller, so nothing fancy in here, I think:
[ApiController]
[Route("[controller]")]
[EnableCors("ApiCorsPolicy")]
public class UserController : Controller
{
private readonly IUserService _userService;
public UserController(IUserService userService)
{
_userService = userService;
}
[HttpPost("RegisterUser")]
public void GetTournaments([FromBody] UserDTO user)
{
HttpContext.Request.Headers.Add("Access-Control-Allow-Credentials", "true");
_userService.RegisterUser(user);
}
}
My question is, why I can't put the "Access-Control-Allow-Credentials" header using the Headers.add method( Which works for my GET requests ) ? If that is not the correct approach to it, then how to do it ?
Thanks!
Edit:
I've added all my Startup file, as requested:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("ApiCorsPolicy", builder =>
{
builder
.WithOrigins("http://"MyIpAddressHere"/")
.AllowAnyMethod()
.AllowAnyHeader();
}));
var mapperConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingGeneral());
});
IMapper mapper = mapperConfig.CreateMapper();
services.AddSingleton(mapper);
services.AddSingleton<ITournamentService, TournamentService>();
services.AddSingleton<IUserService, UserService>();
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "my_app", Version = "v1" });
});
}
// 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.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "my_app v1"));
}
app.UseRouting();
app.UseCors("ApiCorsPolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Change
.WithOrigins("My_Web_App")
to
.WithOrigins("http://localhost....") //your web app url
//your Url shouldn't end with "/"
and remove from code:
//sometimes it interfers with token if you have
.AllowCredentials()
// you don't need this at all
HttpContext.Request.Headers.Add("Access-Control-Allow-Credentials", "true");
Your UseCors should be after UseRouting but before UseAuthorization.
and remove from your controller:
[EnableCors("ApiCorsPolicy")]
I highly suspect that the culprit is in this:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials
Credentials are not supported without a correct origin.

Categories

Resources