C Sharp - CORS

CORS

There’s an issue, you as a programmer create an API, that your websites will connect to to perform it’s business services.

The issue arrises of ‘what would happen if some hacker tries to break into your API?’ You could imagine a lot of havok would be created.

Thus the CORS, it’s built into many servers, if someone tries to access your API without your authorization, then they get a CORS error.

And how do you authorize? We’ll it’s a real hastle, here are a few of my efforst.

Implementation 1
In your startup.cs file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("LocalAngular4200",
builder =>
{
builder.WithOrigins("*", "http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin();
});

// posible
options.AddPolicy("wwwTheCoffeePlace",
builder =>
{
builder.WithOrigins("*", "https://www.thecoffeeplace.com")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin();
});

});

// 3.0 issue
// https://thecodebuzz.com/using-usemvc-configure-mvc-not-supported-endpoint-routing/
Services
.AddMvc(options => options.EnableEndpointRouting = false)
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

services.AddAutoMapper(typeof(Startup));

}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors("theCoffeePlace");
app.UseCors("LocalAngular4200");
app.UseMvc();
}
}
}

Here is a sample of the console log with random console writes
1. Navigated to https://www.thecoffeeplace.com/
2. main-es2015.976870cbdb767bba8357.js:1 Auth.Service.Constructor()
3. main-es2015.976870cbdb767bba8357.js:1 Auth.Service.handleAuthCallback() -
4. main-es2015.976870cbdb767bba8357.js:1 wiki-view - ngOnInit - home home
5. main-es2015.976870cbdb767bba8357.js:1 getWiki home home
6. main-es2015.976870cbdb767bba8357.js:1 getWikiPageByStackAndTopic - home - home
7. /wikiview/home/home:1 Access to XMLHttpRequest at ‘https://cpxxxx.com/api/api/v1/wikiPages/getByStackAndTopic/home/home‘ from origin ‘https://www.cpxxxx.com‘ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
8. main-es2015.976870cbdb767bba8357.js:1 getWiki error (in wiki-view.component)
9. main.js?attr=4MH-xxxxxxrg:1067 GET https://thecoffeeplace.com/api/api/v1/wikiPages/getByStackAndTopic/home/home net::ERR_FAILED

lines
1 – ok, this is good. Sometimes it was redirecting to http://…
7 – This is the error. Notice… one has https://cpxxxx, the other has https://www.cpxxxx. The lack of www changes the origin enough to trigger this error.
In this particular case, since my UI is written with the angular framework, I was able to correct this by tuning my environment.ts file.

References: