.Net Core 3.1 CORS

Cross Origin Resource Sharing centers on the fact that modern browsers won’t accept data from foreign servers unless the server expressly allows it. The browser considers foreign servers to be any server except the one from which the page originally came. The difference can be in any part of the “origin,” or the first part of the URL, concluding with the port.

https vs. httpdomain or subdomain — sub.mydomain.com is different from www.mydomain.comport — mydomain.com:1000 is different from mydomain.com:1001

For example, when an Angular application served from https://mydomain.com wants to log into an authentication server at https://auth.mydomain.com, it has got to ask first. From the point of view of the Angular app, this is all done behind the scenes. Of course the server has to be ready to respond to the request for access.

The request for access starts with an http OPTIONS request (as opposed to GET, POST, etc.) that the browser sends automatically when it sees that the requested URL is for a different origin than the one from which the page was served. Below, you can see such a request. The requested URL is https://localhost:5001, but the origin of the request is http://localhost:4200.

You can see that the browser is announcing it is

from origin: http://localhost:4200requesting localhost:5001 on schema httpsrequesting permission to do a POST

The server responds with a message that either approves or rejects the request. Here, the request is approved:

If the request is not approved, an http error is thrown. Otherwise, the client code is free to make the POST request. (See below for the Angular code used to make the request.)

The .Net Core Server CORS Setup

You don’t have to do anything to get CORS working in the browser. Just make the request as you normally would. On the server, .Net Core has tried to make it easy to set up CORS — you just give the origins allowed to access the server. You do this in startup.cs, of course.

You can see in the Configure Services code below that the our CORS policy is given the name “authenticate” and is set up to allow requests from http://localhost:4200.

services.AddCors(options =>{ options.AddPolicy(name: "authenticate", builder => { builder.WithOrigins("http://localhost:4200") .AllowAnyHeader().AllowAnyMethod().AllowCredentials(); }); });There are other ways to set up CORS, such as using an attribute, but the above works for most circumstances.

Then, in the Configure method of startup.cs, invoke CORS after routing:

app.UseRouting();// CORS must go here! // app.UseCors("authenticate");The POST Request

In this example, we are authenticating the user from an Angular SPA by hitting an auth server. Note that the POST request must include a Content-Type header (application/json) which stops the server from throwing an Unsupported Media Type (415) error. In Angular, set up the headers like this

let httpHeaders = new HttpHeaders({ 'Content-Type': 'application/json' });

Then the login request is made like this:

// post returns an Observable.// The observable's "subscribe" method has 3 callbacks: next?, error?, and complete?// jsonToken is what we get back//// Note: httpHeaders.Content-Type tells the server the format of the data being sent,// which in this case is 'application/json' or a JSON object (model, below) converted// into a string with "stringify."// Without this header, the server returns a 415 errorthis.http.post(url, JSON.stringify(model), { headers: httpHeaders}).subscribe( (x: jwsToken) => { // next if (x.token != undefined && model.username != undefined) { var token: string = x.token; this.signalrService.setJWTtoken(token, model.username); this.router.navigateByUrl('/play'); }}, (error) => { // error console.log(error); }, () => { // complete console.log('Completed'); } );

 •  0 comments  •  flag
Share on Twitter
Published on March 21, 2021 21:50
No comments have been added yet.