Understanding CORS with ASP.NET Core C#

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome to the recording YouTube channel my name is Anton and today we're going to be talking about course cross origin resource sharing this video is for those who don't understand anything about course or perhaps you know how to fix course in asp.net core but you just don't know anything about the details that are involved in fixing there's not much to say about course other than to show it to you so if you're enjoying the video don't forget to leave a like And subscribe if you have any questions make sure to leave in the comment section check out the description join the Discord server I have a course that is out I recommend that you get it if you want to know C sharp as I do it with that let's go ahead and get started here I have two applications an API and the other app the API will be the primary focus of interest for us so I'm gonna open up the program Cs and by the way both of these are MP templates and then we have the other app which is just gonna output other to the browser both of the applications are already running and all that I'm really using the other website for is to just have something on the the domain so I can actually interact with something that is on another domain through the console so let me show you an example if I type out Fetch and I start typing out the URL that is right over here so just like that execute and I encounter a course error now what I'm gonna do first is so you can actually find this information later on I will open a new tab I will try to Google for Access Control allow origin and here is the primary points of interest for us is this section these are the main headers that you need to be aware of and if you don't understand why we need to be aware of these headers don't worry about it just pay attention to these Access Control allow credentials headers methods origin and then Access Control request headers and request method the two in the middle here we will go over them but they're not so important the point is you should have some kind of feel for these headers after watching this video and then you should be able to find this documentation again and again and remind yourself of how this stuff works and basically be able to ReDiscover this information so we will leave the other tab open the API we don't really care about we're gonna close it and here we're gonna go ahead and read the error or actually it will be beneficial to understand first of all what is a cross origin request we have one origin we have another origin and one way that you can inspect Origins is if we go to the network Tab and we inspect the request we're making it to this origin the origin is generally denoted by the address of the URL here the address is localhost 5181 and the request headers will contain An Origin header and the origin here is localhost 5018 the origins are different hence cross origin request gets blocked and specifically this error is thrown by the browser if you have server to server or console application to server communication there is no course issues because this is a security feature of the browser the browser automatically attaches headers it automatically checks where the request is being sent from N2 and if the server is not configured to allow requests from a specific origin if somebody is using a browser the browser will be the last layer to protect the user even though that the application that the user is using has failed so now that we understand that it's a security feature of the browser we can actually read the error and see what it says so access to fetch at the origin that we're interested in from origin that we're at has been blocked by course policy okay so the course policy is inside the browser no access control allow origin header is present on the requested resource this is basically saying that in the network tab if we take a look at localhost the resource that we're getting is on the server side so the response is the resource the mentioned header in the air is not present here so again no access control allow origin header is present on the requested resource this is the requested resource the header is not there hence the error and then the last sentence doesn't really matter that much let's go ahead and take the header over here we're going to come back to our API we're going to close the other app and in addition to having this endpoint we're gonna add custom middleware so use We'll add our HTTP context and then the next we're gonna execute the next we will return it at the end and before we return the next we want to go to the response we want to go to the headers and then we want to attach this header so not sure why AC was missing at the beginning I have clearly copied the whole thing let's remove the last two characters over here and now what about the value that we want to place over here well I can just tell you what to put in there or you can actually go to the source go to the documentation and see what it says the access control allow origin response header and indicates whether the response can be shared with the requested code from the given origin you can either specify all Origins you can specify a specific one or you can say no and it says basically don't use null all right so here are some examples you can basically say that this is the origin that you are going to allow communication from okay cool let's go ahead just take the URL come back over here place it over here semicolon on the end wait for the application to restart let's come back execute the request again we still get the error however the error is slightly different it will say the access control allow origin header has a value of Slash that is not equal to the supplied origin if we take a look at the network localhost we're gonna see that again the request headers the origin and by the way this header is attached by the browser in the response header we have this origin right here we can see that there is a mismatch in the origin where appending a slash so that actually matters remove the trailing slash wait for it to refresh come back we're gonna go to the console and actually let me clear the network tab I'm going to re-execute the request and now it succeeds if we come back to the network tab we take a look at this everything works as expected and you're gonna get your hello world response in here all right so that's really the first layer is just saying this communication is allowed from this Source then you have these other more fine-grained controls which methods can you execute which headers can you attach and credentials basically says can you attach secure cookies or authorization tokens these two headers we will see what they look like in just a second and then expose headers we'll take a look at those in just a second as well or the methods and the headers let's take a look at this we'll come back over here Network localhost and by default the method that we're talking about here is get and then the headers of the request that we're talking about are the headers over here all of these headers are attached by the browser so the browser knows that these are sound these are secure if you go ahead and attach your own header that is when things will be problematic let's take a look at this we're gonna go to the console we're gonna bring up fetch again and let's actually clear the console I can add a second parameter to the fetch request over here which is configuration that can accept headers and headers is just a key value collection I will say that this is my header and this is going to hold some kind of value of a so just another key value pair if I execute this again course policy stops me I am not allowed to attach my own custom headers if we take a look at the network tab what is happening here if I close this we'll see that there was actually two requests that happened here the first request that happens is the options request and then the actual request if we take a closer look at the pre-flight request if you've ever were curious about what the flight request ever was it is the initial request that sends along two additional headers Access Controller request header and access request method so these two over here which basically give an instruction to the server that there's a request going out that is about to execute this method with these additional headers so if I come back to the console bring this up let's shorten the headers to something like my a header and then a second header that says my B header and then give it a value of B execute this we'll come back to the network close this off I know this is a little bit out of order but pre-flight happens first if we take a look at this now we will see that my a and my B are being supplied over here okay so the pre-flight request happens first and it says look server these things are about to be executed is it good or not if we take a look at this request this is basically executing an options method and one way that you can handle this is and actually the way that is handled by the app use course middleware is they have a HTTP methods class that can check is options and you just put CTX request method in here and if it is an options pre-flight request you can just return from here because we're about to make this asynchronous I will go to the CTX I will just take the response and I will complete the response so complete a sink away on here make this asynchronous I'll copy this line over here and I will say look we want to allow the following header so I'll go to access control allow headers I'll take this and here's the notation so you supply the header comma header or you say all headers all right let's come back let's Supply the following response header we will then say that my a and my B are allowed the browser is sending you the information about what is about to be requested you can place any logic that you want generally it is pretty simple in most cases where you're saying I have this app that is over there on a different domain it needs to make a request so just allow the following things from there it is never a case of browser is passing these headers remember let's execute tons of logic sometimes it is actually good if you're trying to make a change to the server cross origin and then you actually want to deal out a csrf token as a result of the options request that should be attached to the actual post request so that options request gets some really good utilization so anyway we have attached the following let's come back over here the application should restart in the background I'll clear here I will clear here let's bring up the previous fetch we'll execute it and everything is fine again coming back to the network tab we have the two requests so first the pre-flight request we can see in the response that we are allowing this origin and we are allowing these headers and again just to restate that the original PreFlight options method request is notifying the server what is about to be executed then on the second request which is actually happening to get the hello world doesn't need the verification that this header is allowed to be sent it is just sent along with the request right the validity of the header is checked with the initial PreFlight request okay so coming back to the documentation we basically take care of this of the allow headers method of these two methods the main ones that are left are these two and then the expose headers and Max H the methods as you can imagine is pretty self-explanatory if we go to the console I'll bring this up and I will say the method that we want to be executing is post instead of get i'll execute this and again this is aborted so first of all it's not allowed so let's just quickly add a endpoint to which we can post that should refresh but let's execute this that has allowed no problems if we then go to try to put that is now being blocked so get and post are the base tier requests and you can start saying that put is a special type of method and that will get blocked this is where again you will need to go to the pre-flight request you will need to grab the allow control methods header we'll place this over here and we're saying we are allowing put this is okay coming back to the documentation again we can specify that we are allowing multiples of these right so post get options put let this restart let's come back over here retrying the request this time I'm getting a 405 because I don't have an endpoint if I add an end point it's going to start working but hopefully you get the idea if we go to the network tab again we will see the pre-flight request and then the failing fetch so taking a look at the PreFlight this is the initial options that are going up we're saying yes this request is valid and then the next one asp.net core is saying that there's only a get and post on this route you don't have a put so you get a 405 going back around to the documentation to give you an idea about access control allow credentials this is where you would specify on your fetch request credentials include it would start including cookies cross origin so if you want to authenticate cross origin or if you are attaching authentication headers cross origin you need to specify Access Control allow credentials some limitations that I think asp.net core imposes of you on you is if you're using allow all credentials you cannot use all methods and all Origins and all headers you need to basically constrain things a little bit more clearly if you're passing credentials from this domain you need to be specifying exactly how you want that communication to work expose headers is slightly easier to demonstrate than is starting to have a whole cookie layer and putting cookies in the browser and sharing them closed domain for example if we come back over here but we'll duplicate this we will say some custom header secret exclamation mark this header is not going to be visible to the response over here we'll all wait on this store this in a result and let's actually change this to get just like that execute we have our headers and on headers we can have entries and then we use object from entries just to enumerate this a little bit Italy but there we go oh my God I missed out an r and there we have it okay so these are all the headers that we have managed to get from the response okay if we go over here and we say these are the headers that we want to expose across cross origin requests we'll put this over here we will say this is a header that we want to expose right over here come back go back over here I'll just clear everything I will re-execute this request I'll bring up the entries and now this custom header is here okay now with the usb.net core obviously you don't want to be building up your own middleware that allows you to do all of this stuff here we basically say you want to use course and then how the logic is going to happen over here you actually go to the Builder you say services and you say add course and then you have your course options just like that course options you say add policy you give it a name you say I want to execute this name policy right so this has to match and then you have a policy Builder on the policy Builder you say things like with Origins with method so for example we would move this over here you're allowing things with these Origins with these methods so let's say put place it over here right as it's a string array so you can specify multiple ones of these you cannot just put a string directly you can say allow credentials or you can say any origin any method and basically now you can see how what you're writing over here how that is going to reflect like in the middleware and how that is actually structured against a standard that is working across multiple browsers now if you have a course issue and you basically just want to solve it you're not too interested about specifying the constraints you basically say allow any origin any method any header and you're done if you are including allow credentials you basically have to say Okay only from this specific origin allow any header any method and then you should be good this will be it for this video thank you very much for watching if you enjoyed it don't forget to leave a like And subscribe if you have any questions make sure to leave them in the comment section if you would like the source code for this video as well as my other videos please come support me on patreon your help will be very much appreciated a very very big special thank you goes out to all of my current patreon supporters you helped me make these videos as always thank you for watching and have a good day
Info
Channel: Raw Coding
Views: 8,057
Rating: undefined out of 5
Keywords: c#, aspnetcore, dotnet, .net, asp.net core, cors, Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Access-Control-Allow-Credentials, Cross Origin Resource Sharing
Id: w3fGpP6_a-A
Channel Id: undefined
Length: 17min 44sec (1064 seconds)
Published: Sun Apr 30 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.