How To Set Up Cors With Spring Security And Spring Boot

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey friends welcome back to the channel if you are new here my name is Alex and today we're going to talk about cross origin resource sharing and making it work with spring Boot and especially with spring security so before we dive right into the code let's quickly talk about what course actually is and in a sense chorus is the opposite of the same origin policy that modern browsers usually enforce so the idea is that if you're if you're running an application at example.com and that application needs to fetch data from an API it usually should only be able to access it from the same domain which is example.com so what you usually don't want is an application go into another API or another party on a different domain such as your banking domain for example so this is why browsers prevent access to these apis unless those apis permit access using course so this is all based on HTTP headers and we'll get to that in a second so for this tutorial I want to show you how you can enable cores on individual endpoints how you can enable it globally and most importantly how you can make it work with Sprint security so with that said let's go [Music] alright let's check the ID as usual let's check the dependencies first um I'm using spring boot version 2.7.3 as usual and you can see there are two dependencies that I brought in the first one is a spring boot starter web which we need for the for the rest controllers and I also added the Springwood strata security already however I just commented it out for now because I don't want to have it on a class path um during the first part of this tutorial so let's get started by adding a controller and we call that the user controller um this is a rest controller pretty pre-default stuff here nope not this one this one and I just want to have one end point I have a gap mapping I use me and I just want to return so the idea is to return a current user I'm not adding a service or a data layer in this um tutorial all I'm doing is just returning um John Doe so this is really all and let's quickly start the application making sure it all works so that should be quite quick there are no arrows that's good let's go to the terminal and now let me just do a quick call to see how it works so um this is what we always do right this is a HTTP get request to slash meet returns an HTTP 200 nothing fancy at this point this is what it usually all looks however there's one thing right now course will be disabled um because it's kind of being it has to be explicitly set by the server using provisional headers that we will see in a second so right now I could tell cores is not enabled on on this endpoint so let's change that and add The annotation that will enable it so we can go to the to the get mapping directly and I can just add the cross origin annotation here and now it's enabled for this specific endpoint now how would I know we just rerun the application and let's quickly go to the terminal again and we just perform the same request again and now we can see the response has changed a little bit um you can see it's still 200 which is okay but there are three more headers that you used to not be there before and they say the response can actually differ based on these additional headers that I as a client could provide so the origin the access control request method and the access control request headers and we start with the origin this is usually what the browser sends to the server uh based on the the URL that you're on so um you can see there are only these three additional headers but what I can do now is use something like this I can specify An Origin again this is what the browser is doing but since there's no browser around here I'm doing it manually so I could just tell the server look the origin is HTTP colon slash slash localhost and we can send it off these headers are the same but there's a new header which is this one it says Access Control allow origin and the asterisk so this means actually the server allows any origin essentially so this is the default setting that you would use for a fully public API um but we get to see how we can restrict that in a second but right now you can see okay the server allows any origin to access that endpoint um which is nice right now we could do this and now it would also work in a browser so this is this is all there is to enabling cores already and while we are at this um let's also check um a different concept because usually what browsers will do before they perform the actual request is something that's called a pre-flight request which the browser is performing to figure out if it's allowed at all to access a certain endpoint so let's see what that looks like that's usually um so this here is a get request right but what browsers are doing is using the options method so it's asking for the options on that endpoint and now you will see that the server replies with okay you can perform a get which we've just done had and options on that resource and and this is the pre-flight request and we can see that has succeeded and we will see what it looks like if it doesn't succeed um in a second because what we're doing now is I could use the across origin annotation under a specific endpoint which is nice but I could also move it up here which makes it a little bit easier if I have multiple endpoints right and if the final stage is having a global config that we get to in a second but what I want to show you is that we could now provide specific Origins and that's an array so I could tell okay look um if you're coming from HTTP localhost you that you're allowed to access that resource so now with that origin in place let's quickly rerun the application um restarting it and then we go into the terminal and now if I just perform um the same get request right so I'm I'm performing the HTTP get request towards slash me and I'm providing um let's go with yeah example.com is just fine so this is a different origin than the one that is allowed here and now if I just run this um it says invalid course requests and I'm getting an HTTP 403 which means it's forbidden for me to access that so before we used um or we've seen the asterisk which means any Origins allowed to connect but now this is no longer the case so if I'm going back to localhost here and I performed the request I can see again it's working but now we also see that the access control allow origin response header has changed from the asterisk to the to the origin that I'm using so that would tell a browser okay you're accessing from HTTP colon slash slash localhost which is fine I permit that just go ahead um and this is all there is to it all right so now let's see how we can actually use a global configuration I'm removing that although I could use it still in as a supplement to the global configuration but I'm getting rid of it here for now and now we go to our spring boot application so that is also a configuration which means I can add beans to the spring context so let's call that course the name is not the best I have to admit because we need um to return a web MVC configurer the way we're doing this in kotlin is using the the object keyword to create a Singleton of that um like this one and now we override one of the methods which is at course mapping and this will provide us with a course registry and we can use that to now specify individual course mappings or Global course mapping as we're going to do so we can do registering and then I can say add a mapping that's how it starts so this means any mapping that exists right now and will exist in the future so that really is the white card mapping that we're in here and now I have to provide the origins now let's actually provide multiple so I'm saying okay localhost is fine and I could also say look http example.org is fine so I can have multiple explicit origin and this is also something that you have to configure in production applications the reason being that even a port makes a difference so if I have low cost colon 3000 that is a different origin than four thousand um so that has to be really explicitly specified here and that can be a pitfall for enabling cores for your for your single page applications if you have them so now I have to specify the methods that are allowed and I'm just again saying all the methods are allowed so this would be something that is close to a public API that can be used from from anywhere um using these these Origins and this is all there is to it so let's quickly rerun the application again and see if that still works so there should be nothing that has changed at this point so let me just try that so you can see that works I can still access the slash B resource and now I can also do it using example.org that also works um it says okay that origin is allowed now if I change something year2.com which is not allowed but I'm getting invalid course request which means that origin is not allowed to proceed okay so now finally let's add Spring Security to the mix um I'm just changing that here I have to resync and now spring boot has dragged in the starter security so that means it's on a class pass and by default spring boot will just lock down the application so but what does it actually mean um right now if I just restart the application um all of the requests are authenticated so that means we can see there's a password for the default user if I just now try to access the application it's blocked right you can see uh it's I'm not allowed to proceed I'm getting HTTP 401 and this unfortunately is even true for the for the option requests yeah that's an error message that is expected because it's not called option but options so you can see it says okay I have to authenticate using basic authentication which has been enabled by default but I'm no longer able to perform the pre-flight requests as well because that's now also getting the unauthorized error and this makes it hard for especially single page applications because usually you have endpoints that accept some sort of username password and return a JWT something like that so that should support pre-flight requests but the thing is that Spring Security kicks in first and doesn't even forward these requests to Spring web NBC so now we what we have to do is we have to make Spring Security aware of our current course configuration and we could do this like all by hand but the the best way to actually doing this is by adding a new beam and this is the security filter chain I just called chain that accepts the HTTP security to be this one I always say it's a security filter chain security filter Shing there we go um and we have to return HTTP build eventually but the way that we can make Spring Security aware of the existing configuration that we have here like this Global one is by just invoking HTTP cords and that's really all that we need to do so right now Spring Security will pick up the existing config and now okay if there are pre-flight requests I have to forward them to Spring web MVC which can reply and then I can still block the the other requests so let's rerun the application with this one and let's go over to the terminal now let's run the pre-flight request on slash me for um for this origin and we can see it's invalid course request which is good which means we have past Spring Security already but it still says it's invalid and why is it invalid well because I've been using um example.com whereas only example.org has been approved as an origin so I'm changing that back to example.org and we can see that has succeeded so it's an HTTP 200 it tells us still that these are the allowed methods that we can use it says that HTTP colon example.org is allowed as an origin and we can actually proceed without being blocked by Spring Security and there are more ways that we can make this work but this is for me uh the most straightforward that we can use especially with spring security so that wraps it up for this video let me know in the comments down below if you have any questions consider subscribing and I'll see you in the next one [Music] foreign
Info
Channel: Alex Gutjahr | Tech Tutorials
Views: 8,422
Rating: undefined out of 5
Keywords: Spring Boot, Spring Boot 2, Spring Framework, Spring Framework 5, Spring Boot Tutorial, Kotlin, Spring Boot Kotlin, Web Development, Learn to Code, Software Development, Software Engineering, Programming, CORS, Cross Origin Resource Sharing, Spring Security, Spring Web, Spring MVC, RESTful API, Spring Boot Interview Questions, Learn Spring Boot
Id: hZykPiUyn48
Channel Id: undefined
Length: 13min 4sec (784 seconds)
Published: Tue Oct 11 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.