ASP.NET Core 3.1 CORS error in VS for Mac - asp.net-core

Initially, I started to develop my project on PC and now I'm trying to run it on Mac. When my front end tries to reach my web API endpoint, I'm getting the following error:
Failed to load resource: Origin https://localhost:3000 is not allowed by Access-Control-Allow-Origin
The thing is that it works perfectly on Windows, but doesn't work on Mac.
My code to enable CORS:
builder.UseCors(x => x
.WithOrigins(new string[] { "https://localhost:3000" })
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
How to solve this issue?

In "ConfigureServices" of your startup.cs add this (it is a different syntax from yours):
services.AddCors(o => o.AddPolicy("AllowSpecificOrigins", builder =>
{
builder..WithOrigins("https://localhost:3000")
.AllowAnyMethod()
.AllowAnyHeader();
}));
In "Config" change yours to this:
app.UseCors("AllowSpecificOrigins");
and place it after UseRouting but before UseAuthorization.
Also remove all Cors attributes from all controller actions.

Okay, it turned out that I had to "trust" the dev certificate created by dotnet core command. I opened my backend URL from browser (https://localhost:44372), clicked "Proceed" when the "site is unsafe" prompt appeared and only after that my front end (https://localhost:3000) was able to reach it.

Related

javascript xmlhttp error on signalr in asp.net core

In my application 2 projects and mvc client run at port(5002) and web api project run at port (5001). I have implemented signalr in mvc client. Now showing error log in console as below:
and i have also added configuration to my api project for core policy like:
services.AddCors(options =>
{
options.AddPolicy("signalr",
builder =>
{
builder.WithOrigins("https://localhost:5002")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
And now also showing same error. Please suggest.
You need to configure your CORS like this:
services.AddCors(options =>
{
options.AddPolicy("signalr", builder => builder.WithOrigins("https://localhost:5002")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.SetIsOriginAllowed((host) => true));
});
The lambda function that you pass to the .SetIsOriginAllowed() method returns true if an origin is allowed, so always returning true allows any origin to send requests to the api. The allow origin access control http header returned when using this method contains the origin that sent the request, not a wildcard, e.g. Access-Control-Allow-Origin: http://localhost:4200.

URL Rewrite exceptions for Blazor WebAssembly Hosted deployment

During development, i have used Swagger on the server side of my Blazor WebAssembly App. Always launching (debug) using kestrel instead of IIS Express.
Routing worked as expected, all my component routed properly and if i manually typed /swagger, i got to the swagger page. All good.
We have deployed under IIS on our pre-prod servers, the Server side and Blazor WebAssembly App (client) work as expected and are usable, however, my /swagger url gets rewritten (I assume) to go somewhere in my App instead of letting it go to Swagger, obviously there isn't any component that answers to /swagger.
My only guess is that, when hosted on IIS, the aspnet core app takes care of telling IIS what to rewrite and how (similar to the configs that could be provided thru a web.config for a "Standalone" deployment.)
I can't find how to specify exceptions, I've been following the doc at
https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/blazor/webassembly?view=aspnetcore-3.1#iis
Any idea how i could add an exception for /swagger ?
EDIT:
Turns out it works without issues in Chrome, only Firefox has the unwanted behavior. If i clear my cache, or use Incognito mode, the issue does not happen in Firefox. So, it seems that Firefox caches some stuff and tries to send my URL input to the Blazor Wasm instead of going thru to the server. I will debug some more with the dev tools and fiddler open to try and figure it out, will report back.
Turns out there this is part of the service-worker.js file that is published. It is different in dev than what gets published (which makes sense).
During my debugging i was able to reproduce the issue on all browsers (Edge, Chrome and Firefox), regardless of being in Incognito/Private mode or not.
Once the service-worker is running, it handles serving requests from cache/index.html of the Blazor WebAssembly app.
If you go into your Blazor WebAssembly Client "wwwroot" folder, you'll find a service-worker.js and a service-worker.published.js. In the service-worker.published.js, you will find a function that looks like this :
async function onFetch(event) {
let cachedResponse = null;
if (event.request.method === 'GET') {
// For all navigation requests, try to serve index.html from cache
// If you need some URLs to be server-rendered, edit the following check to exclude those URLs
const shouldServeIndexHtml = event.request.mode === 'navigate'
&& !event.request.url.includes('/connect/')
&& !event.request.url.includes('/Identity/');
const request = shouldServeIndexHtml ? 'index.html' : event.request;
const cache = await caches.open(cacheName);
cachedResponse = await cache.match(request);
}
return cachedResponse || fetch(event.request);
}
Simply following the instructions found in the code comments is gonna fix the issue. So we ended up adding an exclusion for "/swagger" like so :
&& !event.request.url.includes('/swagger')
Hopefully this post is useful for people who are gonna want to serve things outside of the service worker, not only Swagger.
Do you have UseSwagger first in your Startup.Configure method?
public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
c.SwaggerEndpoint("/swagger/v1/swagger.json", "YourAppName V1")
);
In Startup.ConfigureServices I have the Swagger code last.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSwaggerGen(c =>
c.SwaggerDoc(
name: "v1",
info: new OpenApiInfo
{
Title = "YourAppName",
Version = "V1",
}));
}
This is working just fine for us.
Note: You must navigate to https://yourdomain/swagger/index.html

.Net core - Can not upload file after deploy to IIS

I'm create an api can upload excel file with multipart/form-data. When I run on visual studo, it work normally. But, after deploy to IIS, it can not upload and throw error as below:
has been blocked by CORS policy: No 'Access-Control-Allow-Origin'
header is present on the requested resource.
I try setting with web.config but it still not work, event api POST, GET, DELETE with json context still working normally.
Have a look at the docs on CORS setup in .net core
In Startup you use services.AddCors() to specify a policy e.g.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("MyPolicy",
builder =>
{
builder.WithOrigins("http://example.com",
"http://www.contoso.com");
});
});
services.AddMvc();
}

How to implement cross domain request for Office 365 OAuth2 login authentication?

I have used Office 365 OAuth2 login authentication for an ASP.NET Core API. This is working fine when accessing this API directly from browser. But, when I am calling this API from ajax request / other another web application, below Cors policy error occurred.
Access to XMLHttpRequest at 'https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize?client_id=e0745314-9236-4fr2c-a2fg0-c19cjfsfrrrb6b&scope=api%3A%2F%2Fe0745314-9236-4fr2c-a2fg0-c19cjfsfrrrb6b%2Ftestapi&response_type=code&redirect_uri=https%3A%2F%2Flocalhost%3A44332%2Fsignin-oidc&state=CfDJ8Kp1w7Ui3OZMswaNrHvqNR2MF9qKa9w3PILEMBv8s_zxSa3sMK1pQLr2EuNexhz8eM6
iDdbO2ciuxInNPCtbO1KJ31O_zXvOA_sMXHbAhzzkXKN9QDmrHMUOiQQdjXjam4EqKlopDpcE2vUxcus
4WehJCUfCqdQZjMuzZS7ovrxslRX2ueRNFqpSDichJCf_iduXgFV1bNLRM8gK0TmjUrdkdYtyji7BNsNdPP
o9Fhad' (redirected from 'https://localhost:44332/api/login/account') **from origin 'null'** has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have tried to fix this issue using the following method in startup file. But, still I get this issue.
ConfigureServices:
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
Configure:
app.UseCors("CorsPolicy");
**Client Application** : http://localhost:5000
**API** : http://localhost:44332
**Login provider** : Office 365
Please suggest me the standard way to implement cross origin and redirect to respective client application (http://localhost:5000) URL after getting authorization from Office 365?
Note : While redirect from API to Microsoft login "origin" become "null".
The server must allow the credentials. To allow cross-origin credentials, call AllowCredentials:
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
}));

ASP.Net Core spa pre-rendering with angular universal works locally but not on server

I'm trying to set up angular universal on angular7 with asp.net core 2.1. The prerendering works perfectly on a local build but does not add code to the page source on a server in production with no errors or logs.
Due to the lack of logs I suspect this is because the server module is not loaded/ started but I have no idea why. Is this something that should be added into the web config?
I am using a windows shared plesk server which supports node.js and IIS Node. Here is a snippet from my Startup.cs
app.UseSpa(spa =>
{
spa.Options.StartupTimeout = new System.TimeSpan(0, 0, 1000);
spa.Options.SourcePath = "ClientApp";
spa.UseSpaPrerendering(options =>
{
options.BootModulePath = $"{spa.Options.SourcePath}/dist-server/main.js";
options.BootModuleBuilder = env.IsDevelopment() ? new
AngularCliBuilder(npmScript: "build:ssr") : null;
options.ExcludeUrls = new[] { "/sockjs-node" };
});
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
I eventually realised I had the line app.UseStaticFiles(); as well as app.UseSpaStaticFiles in Startup.cs. Removing app.UseStaticFiles(); solved this issue. However, I am still not sure why this wasn't causing issues on a local build.
I believe you are misusing the prerendering middleware.
About prerendering: Represents the ability to build a Single Page Application (SPA) on demand so that it can be prerendered. This is only intended to be used at development time. In production, a SPA should already have been built during publishing.
You should hide that piece of code behind:
env.IsDevelopment()
Read more here