Advanced Spring Security - How to create multiple Spring Security Configurations

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up Friends Dan Vega here and today we are talking about security we all know security is important so this is something we need to get right one of the things that I love about Spring Security is that it's secure by default what does that mean that means if you select it as a dependency over at start.spring.io or you include the dependency in your application when you go ahead and run the app it is going to generate a username and password for you and then lock everything down so if you want to get to something you have to open it up secure by default I love that approach it really helps us make sure that we are keeping a lid on our applications so that's great but as soon as you need to customize it for your application then you're going to need to override that configuration we do that in a new way we've talked about this on the channel in the past by creating a bean of type security filter chain as the requirements for your application and continue to grow this configuration can get convoluted so there comes a point where you might want to split this configuration out into multiple configurations and that's exactly what we're going to take a look at today so first we need to understand the why why would we want to have multiple configurations and we'll do that by taking a look at two examples so we'll head over to start.spring.io we'll create a brand new project we'll do a little setup and then we'll go into the Spring Security configuration and then we'll talk about creating multiple Spring Security configurations in this example we'll take a look at three and talk about why we did each one of those so I'm excited about this again security is such an important part of our application development Spring Security gives us a lot of power to do some amazing things so what are we waiting for let's head over to start.spring.io and create our app all right so we're going to create a new project here at start.spring.io I'm going to choose maven as my build tool I'm going to use Java we're going to use the latest version of spring Boot and I'm going to fill in some metadata here we'll call this multiple Spring Security configurations or mssc for short we're going to go ahead and use Java 17 and we're going to need a few dependencies so we're going to need web we are going to use Spring Security but I'm actually going to leave that off for a second because I want to show you just a little bit of what comes out of the box before we do anything with spring security so I'm also going to use a spring data jdbc with that I will need a database so I'm going to choose H2 and with that I think we have exactly what we need I'm going to go ahead and generate that project and we'll go ahead and open that up in IntelliJ you can open it up in whatever IDE you're most productive in all right so I'm going to get started here I'm going to to refactor this I just like to name this application I'm just crazy don't mind me so here in my project I'm going to start off by creating a new record so I'm going to create one called let's put it in a model package and I'll create a new Java class we'll create a new record called post and this is just because I need something in the application to model after we're going to annotate this ID with at ID so this is going to be integer ID string title and string content so I've used this domain a lot lately if you I'm just going to kind of Breeze through some of this because this isn't the security stuff I just want to kind of set something up so that we can go ahead and configure Spring Security now that I've done that I'm going to create a new repository we're going to put this in a repository package we're going to call this the post repository repository Dan and this is going to be an interface that extends the list oops list crud repository this is going to be post and integer okay so once that's there we can go ahead and close that now what I need to do is create a couple of controllers so I'm going to start with a home controller and we need to put this in a package called controller so let's say home controller and this home controller is going to be a rest controller and basically we're going to have two mappings one for our root and then one for private so let's do that public string home and that is going to return hello home and then this is going to return a string and we'll call this secure and this is going to return secured all right so now that we have a home controller we need one more controller and we're going to go ahead and create a Java class called post controller so this post controller is going to be a way for us to kind of list out all the posts in the application so we'll use slash API slash posts as the request mapping and to get all the posts in the system I will need to use that repository so I will say private final post repository repository we'll get a instance of this through Constructor injection and then what I'll do is I'll have a git mapping for API posts that returns a list of posts we'll call this find all and then we will return the repositories find all so there we go we have a good start here we probably need just two more little things inside of the resources folder we are going to need a schema we are using spring data jdbc we need to set up the schema for this so I'll create a new file called schema schema dot SQL and we'll just paste that in here so we're creating a table called posts with three columns ID title and content and we're just inserting one row there then we'll go into our application.properties and we will say that we don't want to generate a unique name for that database we're going to use a data source name of blog and we want to enable the H2 console so I want to do this because I want to take a look at something here if we go ahead and run this okay and we head over to localhost 8080 slash H2 Council we can visit the jdbc URL for our data source blog and connect to that and we can click on post and we can see that we have our single Post in there so so far so great now we need to introduce Spring Security so I'm going to add this dependency manually this is something we could have added from the spring initializer but I'm just going to add this manually so let's say we need a dependency of spring um spring boot starter security that will come from there we'll save we'll refresh Maven get our dependencies pulled in now if we go ahead and restart our application and we try to visit our H2 Council it's going to ask us for a username and password so if we look at our console we'll see that hey we do indeed have a randomly generated password here and we have a username of user everything in Spring Security is secure by default so that is why this is getting locked down so we're going to say user here's our password there's our blog let's connect to it oh no we have an error so I've done a video on this in the past and using the H2 console with Spring Security but we're going to take a little bit of a different approach today and this is where scenario one comes in what if we want to set up some Spring Security configuration for our H2 Council again in the past in another video I've kind of mixed it in with our normal configuration but this seems like a good thing to separate out into its own configuration right so cool so anytime that we need to override the defaults in spring so security we need to create our own configuration all right so we're going to start with creating a new Java class in a config package and we'll call this security config and what we need to start with is we're going to enable web security and we are going to add the add configuration annotation that just says hey we're going to go ahead and scan for beam definitions here so we are going to start with a bean so we're going to create a new Bean again I've covered this new component based configuration in the past I'll leave a link to those videos in the description below but I want to create a bean of type security filter chain and we're going to call this one the H2 console security filter chain and this is going to take in our HTTP security we'll call this HTTP and what we're going to return is http.build this will throw an exception so what we need to do is set up con set up our security configuration for the H2 console so what we want to do is we're going to use authorize HTTP requests this is the new Lambda DSL if you're interested I did a video on this as well and all we're doing here is we're going to say that hey when we run across something that looks like H2 console and we're going to use an ant path matcher here so let's say ant path request matcher and when it looks like this H2 console star star what we want to do is we want to go ahead and permit all so that's one step again I'm kind of covering a tutorial that I did in the past but this is just to get started so to make everything available there's also two other quick steps that we got to do so for sea surf we need to go ahead and say sea surf see surf dot ignore request matchers and we will say oh ignore we have to say ignore request matchers and this is going to take an ant path request matcher as well and we'll say ant matcher and then we'll also go ahead and say H2 Council and star star so that's one thing and then the other thing we need to do is we need to say for headers headers headers dot frame options dot disable so these three things will make it so that we can basically open up the H2 console and again this is probably something we'd only use for development mode so if you wanted to say stick a Pro app profile annotation on this you could but let's go ahead and see if this works uh what I want to do is go ahead and rerun the application and go back to our application here and go ahead and say H2 Council now you see we didn't have to log in there so that's a good start can we connect to this we can can we run something like this we can so if your configuration looks like this you should be able to do that as well so that is our H2 Council security filter change so that is like I said keeping everything uh revolving around the H2 Council in one configuration now I have another requirement I want to make sure that anything under slash API so that'll be slash API slash posts I want to make sure that they are authenticated and you can log in with something like HTTP basic right so how do we do that so we're going to Define another being here again this is just a security filter chain we're going to call this one the API security filter chain this is going to take in our HTTP security and we are going to return http.build and this is also going to throw an exception all right so now what we want to do is we want to kind of distinguish this one from this one so we'll come back to that in a second but what I want to do is just build this out and then we'll take a look at the problem and fix it so again we can say authorize HTTP request requests right we're using this new Lambda DSL and all we're saying here is hey anything that comes in under um let's say something like slash API slash slash I want you to make sure that it is authenticated right so if it's authenticated we also want to make sure that we turn session management off we are not using session management for this so I would say session a session Dot session create policy and we'll set this to stateless all right so now that we have that now we can say that we are going to protect this with something like HTTP basic so I'll say with defaults and I'll statically import that now this is just an example because in a real world you might lock this down with say something like the oauth 2 resource server using something like Json web tokens again I've done videos like this in the past but I want to keep this simple so I'm just going to kind of use HTTP basic here okay so we have that but if we were to run our application I mean we could check it out but if we were to run our application what do you think would happen it doesn't really know which one uh it should be used so let's go ahead and check this out so if we go ahead and run this and we go back over here and we visit the H2 Council hmm it's asking us to log in why is that that doesn't make a lot of sense right like hey we want to make sure these two council is available at everything why is this one running so when Spring Security sees this again the way Spring Security works is there's this filter chain this one has ended up getting running first and hey once it matches something it's match something so it is using HTTP basic as the login so there's one thing that we could do to this we could come in here and say order we can change the order now and say I want you to run this one first so let's go ahead and try that and if we run that we can see that we can now connect to that and everything is working so that's one thing I wanted to introduce here which is the add order annotation which allows you to kind of specify which order these configurations will run in but I'm going to remove that for now because I also want to introduce you to something else and that is the security matcher so let's look at the security matcher here so the security matcher allows configuring the HTTP security to only be invoked when matching the provided pattern so this method creates an MVC request matcher if spring MVC is in the class path or creates an ant path request matcher if not so MVC is on the class path so that's what's happening underneath the hood so in this case an NBC matcher is exactly what we want we can see say slash API star star and now down here instead of looking for something specific we already know we're there so we can say any request I want you to make sure that they are authenticated similarly down here I might want to say at security matcher now I don't want to just use the path because we we saw from the documentation that that's going to re that's going to create an NBC matcher and we actually want an ant path request matcher here and what we'll do is we'll say ant matcher and this is going to be H2 console star star so now when we're in here we can still do this we can permit all we can probably get rid of this I'll leave that for a second so now we have our two configurations but again we want to be very specific with what order they are running in so we want to say that this one is going to be first and then this one is going to be second so let's say order is two so now let's see if we can go ahead and run this and we'll copy this because I'm actually going to try and log in if everything works and so let's do the H2 console can we get to the H2 Council we can can we log can we just connect we can can we run our posts we can okay so now let's see if we can go ahead and go to API slash posts and it's asking us for an HTTP basic login I'm going to say user and that randomly generated password and cool I can sign in I can also go to um see if home is there and then let's see we have a secured or what do we call it private and I am indeed logged in so I can see that okay so so far so good now what I want to do is introduce you to another reason why you might want to have this so I might want to create now even a third configuration what if I wanted to say for um slash home I'm going to permit all like I want anybody to be able to get to the Home Route but if they visit anything else so that is our slash private I want to go ahead and make sure that they log in with a form login right so the form login versus the HTTP basic login is just the simplest ways that I can do this in this video without getting making this even longer but you can imagine a scenario where maybe you did have some form log in for some type of you know template driven application and then you had an API that is going to be secured using something like oauth2's resource server and using jwts or something like that so that is kind of the example that I'm clicking up here so now I need to consider a create a third security filter chain so I'm going to say Bean security filter chain and we're going to call this the just the normal security filter chain so again we're going to take an HTTP security HTTP we're going to return HTTP dot build and we will throw an exception so here what I'm going to do is I'm going to now authorize HTTP requests I'm going to take in that auth and we are going to set up a couple things so I am going to add the add order to this but I don't think it's that necessary because I think it would just fall down to this one but I may have to double check that so uh now that I have this I want to say that for let's set up a request matcher for our root endpoint go ahead and permit all I don't you don't need to be logged in to view that anybody can get to that I also want to say auth dot any request I want you to go ahead and be authenticated because that will tell us that hey when you go to slash private instead of logging in using HTTP basic as we did before it should now prevent present us with a form login so let's say form login with defaults and app build now before running this and seeing an error I will show you something that I kind of came up I came across as I Was preparing for this demo you are gonna run into an error if you don't fix this um and this is specifically with just this the way that we're doing something here I turned on um Trace logging for Spring Security and I found out that the slash error was coming up and then redirecting me so a quick fix for this is to just say hey if we come across a slash error I want you to go ahead and permit all for that as well okay so with that I'm going to rerun my application we have our password here let's start with um slash home we should not have to log in there great if we go ahead and go to private that is going to present us with a form login so we can say user and pass great we are at the secured now if we go to slash API slash posts it's going to present us with an HTTP basic login and we can log into that and then finally if we go to rh2 council and connect we can see the information in our database awesome so that was a lot to get around I know this isn't all of these together probably not something that's that common um but I could see it being used especially these two right here I would definitely do this um so that my developers didn't have to log in again I would probably add an app profile annotation here but I could definitely see you know two different types of logins and uh a larger monolithic application so this is how you do it I know I've gotten some questions around how I can create multiple security configurations so I hope that we were able to walk you through both the why and the how here all right thank you for sticking around to the end of this tutorial I really hope you learned something we had a lot of fun again spring security security is important we took a look at why we might want to have multiple configurations and we went through and implemented that so hey if you found that value in this do me a big favor friends go ahead and leave a thumbs up subscribe to the channel and as always happy coding [Music] very very
Info
Channel: Dan Vega
Views: 26,850
Rating: undefined out of 5
Keywords: dan vega, Spring Security, Spring Security Configuration, Spring Boot Security, Spring Security Multiple Configurations
Id: PczgM2L3w60
Channel Id: undefined
Length: 24min 25sec (1465 seconds)
Published: Thu Apr 20 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.