Can't make a cross origin request (CORS) - asp.net

I have enabled CORS in my ASP.NET MVC API, with this code:
public static void Configure(IApplicationBuilder app)
{
app.UseCors("CorsName");
}
public static void ConfigureServices(IServiceCollection services, IConfiguration config)
{
// Configuration and adding Cross-origin resource sharing
services.AddCors(options =>
{
options.DefaultPolicyName = "CorsName";
options.AddPolicy("CorsName", builder =>
{
builder
.WithOrigins(config["AppSettings:CorsOrigin"])
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.AllowAnyOrigin()
.Build();
});
});
}
I try to get data from API, opening the localhost:6320/api/users and it works, I get all the data. Now when I try to get data from Angular 7 app, the data is not loaded and there is an error
"Access to XMLHttpRequest at 'http://localhost:6320/api/users' from
origin 'http://localhost:4200' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource."
Why there is an error when trying to get data from Angular app if I have enabled CORS?
Here is the AppSettings
"AppSettings": {
"DashboardUrl": "http://127.0.0.1:4200",
"CorsOrigin": "http://localhost:4200"
}
Startup configuration from Startup.cs
public Startup(IHostingEnvironment env, IConfiguration configuration)
{
Configuration = configuration;
HostingEnvironment = env;
}
public void Configure(IApplicationBuilder app, IHostingEnvironment hEnv)
{
InitializeIdentityDbAsync(app.ApplicationServices).Wait();
DiagnosticsStartup.Configure(app, hEnv);
CorsStartup.Configure(app);
IdentityStartup.Configure(app, Configuration);
MVCStartup.Configure(app);
}
public void ConfigureServices(IServiceCollection services)
{
CorsStartup.ConfigureServices(services, Configuration);
services.AddAutoMapper();
services.AddSingleton<IConfiguration>(o => Configuration);
services.AddScoped<IAppContext, AppContext>();
services.AddSingleton<IEmailService, EmailService>();
services.AddScoped<AuthService>();
services.AddScoped<UserService>();
EFStartup.ConfigureServices(services, Configuration);
IdentityStartup.ConfigureServices(services, HostingEnvironment, Configuration);
MVCStartup.ConfigureServices(services);
AutoMapperConfig.RegisterMappings(services.BuildServiceProvider());
}

You're adding origins twice. First, through the .WithOrigins(config["AppSettings:CorsOrigin"]), then through .AllowAnyOrigin(). If only a specific origin is allowed(which I suppose is true considering your configuration), remove the .AllowAnyOrigin() call.
Try with:
services.AddCors(options =>
{
options.AddPolicy("CorsName", builder =>
{
builder
.WithOrigins(config["AppSettings:CorsOrigin"])
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
Check what you're getting from config["AppSettings:CorsOrigin"]. Do you have a key called AppSettings?
Futhermore, it might be(and most probably is) that you're calling app.UseMvc(); before app.UseCors();. Make sure your Configure method has the following order:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//...
app.UseCors("CorsName");
app.UseMvc();
}

Remove this from your startup class:
services.AddCors(options =>
{
options.AddPolicy("CorsName", builder =>
{
builder
.WithOrigins(config["AppSettings:CorsOrigin"])
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
and in the Configure method try this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//...
app.UseCors(builder => {
builder
.WithOrigins(config["AppSettings:CorsOrigin"])
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
app.UseMvc();
}
If works in this way so you have a problem with the Policy and their assignment to the UseCors method.

you have to enable CORS in front end also.Following is one of the many ways how you can enable CORS in angular .
step 1: Create proxyconfig.json file inside main project folder(beside src and node_modules).
step 2:
{
"/api": {
"target":"url to the server", (eg: "http://45.33.74.207:3000")
"secure": false,
"changeOrigin": true
}
}
save it inside proxyconfig.json file.
step 3:
add --proxy-config proxyconfig.json in start inside scripts object
"start": "ng serve --proxy-config proxyconfig.json"
inside package.json file.
step 4:
save and start the project with
npm start
note: if you start project with (ng serve) it will not work.

Related

CORS Issue in not allowing main domain in ASP.NET CORE

I am using the below code in ASP.NET Core
services.AddCors(policy => policy.AddPolicy(Constant.CorsPolicy, builder =>
{
var allowedDomain = configuration.GetValue<string>("AllowedDomains").Split(",");
services.AddCors(policy => policy.AddPolicy(Constant.CorsPolicy, builder =>
{
builder.WithOrigins(allowedDomain)
.SetIsOriginAllowedToAllowWildcardSubdomains()
.AllowAnyMethod()
.AllowAnyHeader();
}));
}));
to allow all subdomain and main domain, what this code does that it allow all subdomain, but it does not allow the main domain, I am reading values from configurations.
"AllowedDomains": "https://.test.dk, http://.test.dk, http://test.dk"
The following api is not allowed when its hit:
https://api.test.dk/api/v1/Product/Search
Try to simplify the CORS and write like this:
Within your ConfigureServices method
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
}
And within your Configure method
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors(options =>
options.WithOrigins("http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod());
}

Rollbar not globally handling errors at .NET Core 2.2 api project

I have set up Rollbar in my .NET Core 2.2 api project just like it described in official docs. But i can not get the middleware work. Explicitly sending error/information works fine. But when there is an unhandled exceptions in code this will not be logged by Rollbar. I have installed Rollbar and Rollbar.NetCore.AspNet packages. My Startup.cs file looks like this:
public void ConfigureServices(IServiceCollection services) {
RollbarLocator.RollbarInstance.Configure(new RollbarConfig("MYTOKENHERE") { Environment = "ENVNAME" });
services.AddRollbarLogger(loggerOptions =>
{
loggerOptions.Filter = (loggerName, loglevel) => loglevel >= LogLevel.Trace;
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseCors("MyLocalhostOrigin");
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseRollbarMiddleware();
}
Any idea how to get middleware part work, so that errors will be globally logged by Rollbar ?
Figured out that need to add CaptureUncaughtExceptions = true when configuring Rollbar.
RollbarLocator.RollbarInstance.Configure(
new RollbarConfig("MYTOKENHERE")
{
Environment = "ENVNAME",
CaptureUncaughtExceptions = true,
});

Can't call client method from server

I'm trying to use SignalR to broadcast a message from the server to the client without the client triggering the message. From tutorials that I've seen, defining a method in the client, like so:
signalRConnection.client.addNewMessage = function(message) {
console.log(message);
};
should allow the following hub code to be used on the server:
public async Task SendMessage(string message)
{
await Clients.All.addNewMessage("Hey from the server!");
}
However, the Clients.All.addNewMessage call causes an error in the C# compiler:
'IClientProxy' does not contain a definition for 'addNewMessage' and no accessible extension method 'addNewMessage' accepting a first argument of type 'IClientProxy' could be found (are you missing a using directive or an assembly reference?)
How do I fix this? The server code is contained within the hub.
This is because you are using ASP.NET Core SignalR but you are calling client method following ASP.NET MVC SignalR. In ASP.NET Core SignalR you have to call the client method as follows:
public async Task SendMessage(string message)
{
await Clients.All.SendAsync("AddNewMessage", message); // here `AddNewMessage` is the method name in the client side.
}
It showing your client side code is also for ASP.NET MVC SignalR. For ASP.NET Core SignalR it should be as follows:
"use strict";
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
connection.on("AddNewMessage", function (message) {
// do whatever you want to do with `message`
});
connection.start().catch(function (err) {
return console.error(err.toString());
});
And In the Startup class SignalR setup should be as follows:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
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.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSignalR(); // Must add this
}
// 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();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseSignalR(routes =>
{
routes.MapHub<ChatHub>("/chatHub"); // Here is configuring for `ChatHub`
});
app.UseMvc();
}
}
Please follow Get started with ASP.NET Core SignalR this tutorial if you face further problem.

Can't enable CORS in ASP.Net Core web api

I created an ASP.Net CORE web API project, with a single controller, and would now like to call it from a client (React) web app.
However, the call fails with "No 'Access-Control-Allow-Origin' header is present on the requested resource.".
When calling the same endpoint from Fiddler, the expected response headers are not present.
Thanks to ATerry, I have further insight: the headers are not present, because the React web app and the .Net Core web API are hosted on the same box. React populates the request Origin: header which is the same as the (API) box, thus the server (being really clever about it) does not add the Allow-... response headers. However, the React app rejects the response, because of the lack of those headers.
I'm using .Net Core v2.1 (latest as of this writing).
I built the code based on
https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.1
I checked these
https://weblog.west-wind.com/posts/2016/Sep/26/ASPNET-Core-and-CORS-Gotchas
CORS in .NET Core
How to enable CORS in ASP.NET Core
... but none of the suggestions worked.
Any ideas?
This is how I configure the .Net Core app (code changed from actual to try and allow anything):
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Enable CORS (Cross Origin Requests) so that the React app on a different URL can access it
// See https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.1
services.AddCors(options =>
{
options.AddPolicy(Global.CORS_ALLOW_ALL_POLICY_NAME, builder => builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials());
});
services.AddMvc();
}
// 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();
}
else
{
app.UseHsts();
}
app.UseCors(Global.CORS_ALLOW_ALL_POLICY_NAME);
app.UseHttpsRedirection();
app.UseMvc();
}
}
Having failed with just the above, I added the CORS attributes to the controller class and controller methods too:
[Route("api/[controller]")]
[ApiController]
[EnableCors(Global.CORS_ALLOW_ALL_POLICY_NAME)]
public class DealsController : ControllerBase
{
[...]
[HttpGet]
[EnableCors(Global.CORS_ALLOW_ALL_POLICY_NAME)]
public ActionResult<List<Deal>> GetAll()
{
return Store;
}
}
The response headers I get:
HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Server: Kestrel
X-Powered-By: ASP.NET
Date: Thu, 06 Sep 2018 12:23:27 GMT
The missing headers are:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:3000
I believe it should work fine with LOCALHOST hosting as well, just do below changes and remove and any extra changes/configurations.
Replace this:
// Enable CORS (Cross Origin Requests) so that the React app on a different URL can access it
// See https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.1
services.AddCors(options =>
{
options.AddPolicy(Global.CORS_ALLOW_ALL_POLICY_NAME, builder => builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials());
});
with this:
services.AddCors();
and Replace this:
app.UseCors(Global.CORS_ALLOW_ALL_POLICY_NAME);
with this:
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
NOTE:
Even if your Web Api and React app are configured on LOCALHOST doesn't mean they are from same origin, it is because they are hosted on different port like react app is hosted on LOCALHOST:3000 and Web Api is hosted on LOCALHOST:5000. Web api will complaint if client(react app) is requesting from different port.
Above Web Api code will allow ANY ORIGIN and in production applications this is not safe so you need to allow specific ORIGIN to CORS access.
Managed to solve it by changing the URL used to access the server from a localhost based one to an IP address based one (localhost/api to 192.168.1.96/api).
It seems that part of the filtering that ATerry mentioned is based on host name: IIS doesn't send the Allow-... headers if hostname is localhost. Trouble is that React requires them.
You could try something like below as explained here: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder.WithOrigins("http://example.com"));
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Shows UseCors with named policy.
app.UseCors("AllowSpecificOrigin");
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
In your scenario it could be changed to something like the code below.
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options => options.AddPolicy(Global.CORS_ALLOW_ALL_POLICY_NAME,
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
}));
services.AddMvc();
}
// 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();
}
else
{
app.UseHsts();
}
app.UseCors(Global.CORS_ALLOW_ALL_POLICY_NAME);
app.UseHttpsRedirection();
app.UseMvc();
}
}
This code might not look any different from yours however, there is a slight difference in the way the actions(what you call the builder) are defined. I hope that helps, good luck! :)
I got stuck with this same issue recently but doubted if mine was CORS related. So I went to deploy the app to my local IIS to check if that will get resolved somehow. Then checked the logs and found an issue pertaining to circular reference in data models - "Self referencing loop detected for property..". Applied an action in Startup.js to resolve the issue like so,
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddJsonOptions(options =>
{
options.SerializerSettings.Formatting = Formatting.Indented;
// this line
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});

Enabling CORS for Web API in AspNet.core 2.0

I've created a Web API using ASP.Net Core 2.0 wherein I've implemented code for enabling CORS as given below:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowFromAll",
builder => builder
.WithMethods("GET", "POST")
.AllowAnyOrigin()
.AllowAnyHeader());
}); ;
services.AddMvc();
}
// 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.UseCors("AllowFromAll");
app.UseMvc();
}
}
}
But still I'm getting status 401: UnAuthorized when tried consuming in fiddler.
Any solutions on this regards?

Resources