SignalR, ASP.NET 5 and CORS - signalr

I'm trying to use SignalR with my MVC6 application, but I encounter problem with CORS.
First : If I host my index.html file on http://localhost:1234/index.html (same as my web app) it's working.
But when I host it elsewhere (for example in file:///C:/Users/me/Documents/index.html), I have this error :
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'null' is therefore not allowed access.
Of course, I try to enable CORS, this is my startup file :
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSignalR();
services.AddCors();
var policy = new Microsoft.AspNet.Cors.Core.CorsPolicy();
policy.Origins.Add("*");
policy.Headers.Add("*");
policy.Methods.Add("*");
services.ConfigureCors(x => x.AddPolicy("allowall", policy));
}
public void Configure(IApplicationBuilder app)
{
app.UseCors("allowall");
app.UseSignalR();
app.UseMvc();
}
}
But now, I have another error :
A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin'
header when the credentials flag is true. Origin 'null' is therefore
not allowed access.
Then I try with :
policy.SupportsCredentials = false;
but still getting same error.
What should I do ?

Seen with SignalR team, this is working on http://localhost:port but not on file:///C:/Users/me/Documents/index.html and this is normal.

Related

"No authenticationScheme was specified" when I deploy, but works fine on my machine

We're deploying our little intranet app for the first time (.net6, IIS8.5).
I'm surprised to see "No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action configureOptions)"
Surprised because I've specified the default authentication scheme exactly as the error suggests. Our startup is completely vanilla, and all this works fine on our dev machines. What could possibly be the problem? The relevant parts of our startup are as follows...
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(IISDefaults.AuthenticationScheme);
// Authorization always Yes for testing
if (!_env.IsProduction())
{
// Disable authentication and authorization.
services.RemoveAll<IPolicyEvaluator>();
services.AddSingleton<IPolicyEvaluator, DisableAuthenticationPolicyEvaluator>();
}
...
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSpaStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
...
}
Ok in my case this was hopelessly simple. I needed to turn on Windows Authentication in IIS for my website. It is off by default. Hope this can be useful.

Cannot hit AspNetCore 3.1 MVC API endpoints when published

AspNetCore 3.1 MVC API. Conventional startup
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
I can hit all endpoints when running on localhost. When I publish, all endpoints return 404.
To test I am publishing to the correct location, I added an endpoint that displays in the browser
public IActionResult Index()
{
return Content("Users Index");
}
When I browse to https://subweb.mainweb/users/api/users/indexI see Users Index returned in the browser, but all other endpoints return 404.
The controller is decorated
[Route("api/Users/[action]")]
public class UsersController : ControllerBase
All other endpoints are decorated eg
[HttpGet]
[ActionName(nameof(IsRegisteredUser))]
public IActionResult IsRegisteredUser()
But I don't see how this would make a difference between running locally and on the server.
How could it be that all endpoints are available in localhost, but only the test endpoint when published? Where do I begin to look?
When I browse to https://subweb.mainweb/users/api/users/indexI see Users Index returned in the browser, but all other endpoints return 404.
Based on your above example URL, it seems that you host your ASP.NET Core Web API app as an sub-application (sub-app) at /users on your server.
To access the endpoint(s), you should make sure you include the sub-app's pathbase in URL, otherwise it would result in a 404 - Not Found error.

Angular 6 App not working in IE11 when Dev Tools is close

I have read about this issue on some previous thread, however it is still not working, I have commented all console.log and still not working.
I am using Angular 6, may Web API is in .NET Core.
Thanks in Advance!
I finally found the answer after googling and trying different methods.
It may be a duplicated concern / issue, but I just want to share my experience doing a WebAPI using .Net Core.
I found out that my web app seems to disabled back and forward caching. (can be seen on Console F12 Dev Tools)
DOM7011: The code on this page disabled back and forward caching. For more information, see: http://go.microsoft.com/fwlink/?LinkID=291337
Add app.UseResponseCaching(); in Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Use Cross origin resource sharing
app.UseCors(
options => options.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
);
app.UseAuthentication();
//20180830
app.UseResponseCaching();
app.UseMvc();
}
Add services.AddResponseCaching(); in Startup.cs, ConfigureServices.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddResponseCaching();
...............
}
Finally add a response header on my Web API solves the issue.
[HttpGet("usraccessbk"), ResponseCache(Location = ResponseCacheLocation.None,
NoStore = true)]
public IActionResult GetWorkXXXXAccess(string user, string buXXXX) {
...........
}

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

ASP.NET 5: Azure web app CORS stop working after delay

I have ASP.NET 5 web site (dnx451) hosted in Azure.
It works fine for an hour or so after the deployment and then CORS feature stop working. Other services like DI, Authorization and MVC are still functioning.
Here is Startup.cs code:
public void ConfigureServices(IServiceCollection services)
{
configureCors(services);
services.AddMvc(options =>
{
options.Filters.Add(new ErrorFilter());
});
}
private static void configureCors(IServiceCollection services)
{
services.AddCors();
services.ConfigureCors(x => x.AddPolicy("allowAll", p=>p.AllowAnyOrigin().
AllowAnyHeader().AllowAnyMethod()));
}
App configuration:
public void Configure(IApplicationBuilder app, IApplicationEnvironment env, ILoggerFactory loggerFactory)
{
app.UseMiddleware<StaticFileMiddleware>(new StaticFileOptions());
app.UseErrorPage();
// Add MVC to the request pipeline.
app.UseMvc();
app.UseCors("allowAll");
}
Local version has CORS all the time but Azure web has it only in the first 1-2 hours (depending on the usage). I guess CORS disappears when Azure restarts the app.
It is strange. Does anyone have the same problem?
Thanks to Henk, I was able to fix the problem:
I had both [EnableCors] attribute and app.UseCors() startup call. After removing UseCors, the problem disappeared.
However it is still strange why Cors is working temporarily when both options are in place.
Update:
As for https://github.com/aspnet/CORS/issues/36
You need not call services.AddCors() here as AddMvc internally already does that.

Resources