What is CORS? | Fixing CORS errors in ASP.NET Core

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
has it happened to you that you have your modern front end ready to talk to your acnet core backend but on the first request all you get is a course policy error this has happened to me a few times and it's a common issue that confuses many of the net Developers luckily the liquid course is a very straightforward process so today I'm going to show you how to configure cores in an ESPN netcore application let's start before jumping into the code let's first understand what a cross origin request is let's imagine that the web server that is hosting our front end is also the server that holds the backend that provides data support to the front end in this scenario the browser initially navigates to the web server URL to load the front end which needs to render some weather data the browser makes a get request to the backend rest API to the same web server URL to which a server will reply with the Json representation of the weather data the address from which the browser calls a backend is known as the origin and is made of a combination of protocol host and Port which in this example is http localhost 5000. notice how the origin in the browser matches exactly the origin of the vacant server let's now move our backend to a different web server with a different address now when the weather page needs to get rendered in the front end the browser makes a get request to the backend at HTTP localhost 5007 a different origin since the port of the backend is different than the one in the browser this is known as acros origin request the back end will return the weather data just as before but by now the browser knows that this response comes from a different origin since it had set in the auditing header in the request therefore it rejects the response data with a course error this happens because browsers follow what is known as the same origin policy which states that a web application can only request resources from the same origin the application was loaded from browsers enforce this to prevent malicious websites from Reading configuration information from other websites unfortunately this is also preventing our front end from reaching the weather back end so how can we fix this here's what course can help course allows the server to indicate any other audience than its own from which a browser should permit loading of resources and here's how it works once again the browser has been asked to load weather information in the front end the browser sets a get request to the backend's rest API and since the backend is hosted in a different origin the browser appends the audience header the difference this time is that the rest API has been configured with the access control along origin header which indicates all the other Origins that are allowed to call the rest API in this case this header has been configured with the origin where the front end is hosted http localhost 5000. once the rest API sends the is data back to the browser it opens this header to the response the browser now compares the value in the ordering header it sends to the value in the received Access Control allow ordering header since they match the browser now allows the response data to reach the front end this works for simple requests like gets post put and other methods add a few more steps to this mechanism but as you can see the key to a successful cross origin request is in the appropriate course configuration on the backend that exposes the rest API since only the backend can declare the allowed Origins let's now jump into the code and learn how to configure course in an aspl Network application to demonstrate the typical course error and how to fix it I'm going to create both a client-side and a server-side application for the client I'll be using a Blazer webassembly app and for the server I'll create a web API app so here we are in Visual Studio code where I have prepared this hello course directory where we're going to be creating those two apps and let's start by creating our service site up first and for that let's use it.ncli and we can just do dot net new web API and just to keep things simple we're going to be using a minimal API right so I'm going to say minimal and then the name is going to be hello course dot server all right so as you can see on this on the left side we have our new hello course that server project get it right there and then just like that we're going to be creating our client side which is going to be net new base or wasm and then the name is going to be hello course dot client okay so now we have our client side also created on the left side and what we can do now is just verify what exactly we got from these initial applications so let me clean this and I'm going to switch to hello course dot server so let's start our server first so that then run let's see what we get so we have our URL right here we got localhost 5007 this is a random Port that you're getting and so I'm going to go to that location in my browser over here and I'm going to just append the Swagger endpoint and so here what you can see is that all we got is a very simple endpoint with a like a get endpoint for weather forecast and if we say try it out and we say execute we're going to get is a very simple Json response as you can see right here with some random weather information right so this is the typical um data that you get in a in an initial.net web API right it's a simple example so that is data that we want to consume on the client side right but first let's take a look at that client side very quickly see what we got so I'm going to click over here to bring in a brand new terminal and I'm going to switch to hello course.client so I'll do net run also here so it's going to build our client and it's going to start it and we got a brand new Port which is going to be 50 28 I'm going to just click on that one and that loads mic line over here as you can see this is at the typical initial Blazer a laser application and the part that we're mostly interested in is in this fetch data tap on the left side which as you can see right now it is showing some weather data but that data is not yet coming from the server side it's just going for that simple file that has been placed directly on the Blazer webassembly application so let's explore exactly where this data is coming from so if we go back into your code over here and I'm going to minimize this for a moment perhaps just close this completely and then uh if we go into pages into fetch data.racer you're going to see that this is the the the page that shows and yeah we're not going to using this and this as I click not now we don't need that and scroll down you're going to see that the the data is coming from this request here HTTP get from Json async that comes from sample data weather.json right and that is actually located in WW root sample data whether that Json is this file over here right so since this is all on the client in the hello Corsa client this means that this data is all just leaving on the client side right now so instead of that what we want is for the client to read data from the server side so let's take a quick look at that server-side a res API so if you go into hello course.server into program.cs and if we collapse this for a moment this is the entry point for the server for the service application and if you scroll down you're going to see that here's where we have our weather forecast endpoint and all it does is really create a as you can see five elements of type weather forecast where this weather forecast already has is a date uh temperature in in Centigrades and a summary those are the inputs for for that one right and all the data here is really random as you can see at least based on this is summaries array over there so how can we get our client to read data using this this recent point so if we show our Explorer once again and if we go into fetchdata.racer you're going to see that what the client is is doing is using this object HTTP HTTP client right so which is by the way injected at the very top over there is a bit injected via dependence injection um it is using that to do get from Json async and then of course it is using the sample data with a Json file that you saw so what we need to do is first let's change this so that it is going to read data from the server-side endpoint so what is that endpoint located if we go back here that endpoint is just called weather forecast right so I'm going to just copy this weather forecast endpoint I'm going to copy this copy and then back into fetchdata.racer so let's replace that where we have sample data.json right now replace that okay so that's the first thing and then the next thing is that of course we don't want this HTTP client to be looking at the a decline side anymore right we need to configure it so that it can use the remote server for that we have to look into the place where we actually register this HTTP client instance because it's injected over here but what is it registered that's actually registered on program.cs over here this brand.cs on the client side the entry point and if you collect this again for a moment you're going to see that this line here line nine is where we register a HTTP line instance but right now the Base address is going to be the Base address of the hosted host environment which is the Base address of the of the client so what we have to do is just change these others to be the others of the server side so I'm going to show my Explorer again I'm going to go this time into a hello core server properties launch settings.json and what you can see is that we have this profile section where the first profile is the one that is usually using a by default and over here we have our application URL which in this case is HTTP localhost 5007. so I'm going to copy that that URL and I'm going to go now back into program Cs on the client right this is the client and in the Base address we're just going to replace this with http localhost 5007. and that should be pretty much what we have to do to get our client to talk to our server and also notice that if we go back into this data eraser the model that the fish data eraser is using to render the information this weather forecast model it matches exactly the same values that we're using on the server side so it has date temperature C summary and temperature F which is kind of a computed property on the server as you can see we go back to the server if we go into weather forecast which is declared down here it's the same thing date temperature C summary and temperature F so things should work just just like that because the the shape of the data is exactly on the server on the client side now we go back into the client one more thing we're going to do is just get rid of this weather.json file because we don't want that data anymore so I'm going to right click Ensemble data I'll click on delete and now that data is gone so the data has to come from the server side this time so let me open up my terminals again what I'm going to do is just stop my client so I'm going to do Ctrl C to stop my client so client stopped and now I'm going to run it once again done it run so this time it has to read data from the server side so let's go back into our client over here and I'm going to just refresh this page and of course we are getting a an error here right as you can see we have an error right there and the layer has occurred so how do you debug this well what you do is you just hit F12 to open your developer console on the browser right and so on I'm going to close these for a moment and if you're in the console tab over here so you may be in welcome now but you want to switch to console what you're going to see is this let me show you this right there we can see the typical course error which is this one over here so it says access to fetch add localhost 5007 weather forecast from origin HTTP localhost 5028 has been blocked by course policy right so no access control or in header is present on the requested resource and in fact if we switch quickly into the network tab over here and perhaps we just refresh the page to see these things going on again yeah uh if we go uh over here you're going to see that we have this weather forecast invocation to the server side and you can see that the request URL over here right goes into localhost 5007 where forecast is a server side but the origin so let me scroll down a little bit the origin right here is our localhost 5028 right which which don't match right it won't match right so now is the time to go ahead and configure course to make sure that we notify the browser which is the additional origin that has to be allowed which is the origin of the client side so what it is what we want to do is just go back to visual studio code and this time we're going to go into the server terminal here and we're going to just stop this guy because we're going to make changes so we close this and let me collapse so here we are in the program CS of hello world.server this one over here and I'm going to close the other one to not get confused okay and so what we want to do is to configure the the course services and the course middleware so that we enable the additional header there that is needed for this so for that you can use this Builder object over here so this is the object that you can use to configure a bunch of services for your AC netcore application and so before we involve the line we actually build a build this this app this web application what we want to do is just configure one more service which is the course service for that all you have to do is just say Builder that services that add course just like this and that will make sure that it adds all the required core services to your web API now one more thing that you have to do here is to also configure the middleware to delete what is going to be exactly that origin that additional Orient that it has to support besides its own origin right so I'm going to use a code here and for that we're going to be using this web application object that configures the the request pipeline of asp.net core and we're just going to say app.use course and then we're going to be passing in this options object that we have to configure with this Arrow function over there and let me do semicolon over there and then all you have to do here is just say options dot with Origins and then you want to specify the origin of the client-side application right so once again if we go back to Explorer and we go this time let's go into hello Corsa client into properties launch settings.json in this case we look at the HTTP profile this one over here we're going to find that our application URL is right here right so it's localhost 5028 so I'm going to copy that and then into program Cs on the server side close that I'm going to just paste it over here okay and that will make sure to configure a ASP net core in the web API so that the additional header that is needed is going to be appended response that the server sends back into the client right so that the browser feels happy about a loading data from this remote additional origin right and so with that let's go back into the terminal over here where we had stopped our server so I'm going to start it once again server side starts and now let's go back into our client over here where perhaps I'm going to collapse this for a moment to see better and then I'm just going to go ahead and refresh this and as you can see right away the data is loaded without any troubles and in fact if we go now into our Network tab once again and if we look at the weather forecast call over here let me let me expand this a bit and so if we collapse this for a moment we can see that now we have of course we still have our origin over here but now we also have our Access Control allow origin header being appended by the server side right which is what the browser is looking for but now that it notices that that that new header is there and that it matches our origin that is why the browser feels happy about this and it it can properly load that data that is coming from a different origin just fine all right and so yeah that's how you configure course as you saw is here a few lines of code and that will allow your a modern single page application like appraisal webassembly or any other really the type of single page application to be able to load data from our remote origin I hope that helps gratify the course policy errors and how to deal with them in your spline core application if you want to know more about cores and many other related topics please check out my site for complete courses designing for dot-net developers ready to take the next steps in their careers and don't forget to subscribe to my channel so that you are the first to know whenever I publish new videos thanks for watching and see you next time
Info
Channel: Julio Casal
Views: 3,260
Rating: undefined out of 5
Keywords:
Id: zITff13XTvc
Channel Id: undefined
Length: 17min 3sec (1023 seconds)
Published: Tue Jan 24 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.