Hi, Welcome to The Tech Mojo. This is Nilan and in today's video we will learn about creating and using interceptors in Spring Boot. This video is broken down into multiple chapters. In chapter 1, we will talk about the introduction to spring interceptors with some real-time use cases and in Chapter 2 we will talk about difference between the spring interceptors and servlet filters the chapter 3 will cover how to implement and register an interceptor in Springport in chapter 4 we'll discuss about the Interceptor execution order especially when you have multiple interceptors in chapter 5 we will create an Interceptor to perform the basic authentication checks for the incoming HTTP request now without a further delay let's get started spring interceptors are used to intercept the client request before they are handled by the controller they can also be used to intercept the response before the response is sent back to the client interceptors are part of spring web MBC framework and they provide a way to add free and post processing logic to your application request response lifecycle interceptors can be used to log the HTTP request and response and this can be useful for debugging or tracking the performance of your application interceptors can also be used to enforce the security policy for example you can write an Interceptor that would check the user is authenticated before allowing them access to the to the resources interceptors can be used to Cache the HTTP request and response and this can improve the performance of your application by reducing the number of times the request has to reach to the controller interceptors can also be used to transform your HTTP request and response for example an Interceptor could be used to convert the Json request to a XML response in a typical spring boot rest API whenever the client sends a HTTP request to a specific endpoint or to a specific rest API the request is first received by the web server and then the web server will forward the request to your spring boot application the dispatcher sublet is the entry point for all the incoming request in Spring boot application once the dispatchers oblit received the request it consult with the URL Handler mapping and the Handler mapping is responsible to determine which controller it should be passed to the request is then passed to the controller and it is passed to the controller based on the mapping that we Define similar to Interceptor there is also another concept called filters now the filters are part of servlet API and they are operating at a very lower level filters can also be used to intercept your request and response the only difference between the filter and Interceptor is filters are not specific to the spring framework they are basically a part of servlet API and they are operating at a very lower level the filters are are not specific to the spring framework however you can still use the servlet filter because the spring application or spring itself is built on top of servlet API so now basically in Spring boot application you have two options you can either use filters or you can use interceptors right so how do you decide which one to use for your use case if the task is specifically related to Spring MBC which requires a spring application context then you should go with the interceptor but if the task is more generic in nature and it does not require any spring MBC or spring context then you should do that in a servlet level and that can be done using the servlet filters now let's look into how sublet filters and interceptors are fitting within the application life cycle now whenever the request is made by the user the request is now first reaching to the servlet filter and then the request will be sent or forwarded to the dispatchers outlet and then dispatches oblet will send the request to the Interceptor and then after all the interceptors are executed then it passed to the controller in order to create an Interceptor in springboard or we typically have to create a class that implements the Handler Interceptor interface the Handler Interceptor interface has three methods the pre-handle post handle and after completion the pre-handle method is executed before the actual controller method is called it returns a Boolean value a Boolean true indicates that whether the request would continue to go to the controller or it should be stopped right here the post handle method is executed after the controller method is called but before the response is sent to the client so this is where you typically do any post processing logic like modifying your response header or modifying your response content the after completion method is called after the request has been completed and this method is called even if there is an exception was thrown during the processing of your request typically you can use the after computation method to perform any cleanup tasks that you need to do after the request has been completed now that we understand the basics about interceptors and how it works let's jump straight into our spring boot application and we will see it in action for the demonstration purpose I have created a simple spring boot rest API and this is a basic rest API which has a controller called Product controller and within the product controller we have like two methods the first method which is get products so the get products method is returning a hard-coded list of products again we have another endpoint called post endpoint so this post endpoint is mapped to the URL Slash new and here we're not doing anything complex again we just passing a product as a request body and we are returning the same object here now let's run this and see how this works in the postman now as you see the hard-coded list of products are returned here now let's check on the next endpoint which is the new endpoint new okay and this should be HTTP post and it takes a body which is a raw Json okay I mean we're not doing any validation or anything whatsoever right so you're passing the Json and that Json is sent back to us okay now as you see the the list method and the new method both are working now let's jump back to our springboot application and try to implement an Interceptor for intercepting or printing the logs Now to create an Interceptor all you need is you need to create a class so new Java class so let's call this as log Handler interceptor now your log Handler Interceptor need to implement the Handler interceptor now if you go inside the Handler Interceptor you can notice that there are three methods the pre-handle post handle and after competition the pre-handle method is returns a Boolean value true if it returns it true what it means is it will continue with your with your controller otherwise the the request flow will be stopped here now all these three methods are implemented within your interface and that implementation is done using the default keyword and this is a New Concept since Java 8 where you can have an implementation or method implementation within your interface what this means is you are not forced anymore to implement any of these methods within your class okay but however let's go back to our class and we'll try to override all the three methods here okay now here let's return true so that it will continue with our controller now here all we need to do is we want to print the logs we want to print the logs to identify or to understand the flow of execution now for that I'm going to use the logger slf4j let me just use log dot info here I'm printing the name of the class so I know where the request is coming from and prehandle okay let's do the similar things here for the Post handle and for after competition foreign the next thing we need is we need to register it with the spring boot application and the registration can be done using the webmbc configurer configuration now for that let's create another class new Java class and call this as web config now this web config must Implement your web MVC configurer and let's declare this as a configuration so that your spring boot application know about it now here we need to override the add interceptors method from the webmbc configurer okay so let's override here add interceptors okay now the add Interceptor method is provides you the Interceptor registry now we need to add our Interceptor to this registry okay so all I did is uh registry dot add Interceptor and then I'm creating an object of my interceptor okay let's run this again okay my application is started in port 8080 let's clear the logs go back here and hit the list now as you see the log Handler Interceptor prehandle method is executed before the controller and once the controller execution is complete then it calls the post handle and then finally the after computation method is called now this is how you add an Interceptor in springboot now let us extend this example to add in basic authentication check now in order to do that let's copy my log Handler Interceptor and I will paste it here and let's call this as basic auth Handler Interceptor okay and similarly I'll change these names as well let's call this as method right it makes it sounds bit weird do the same thing here okay so now we have created a basic auth Handler Interceptor but again we're not doing anything at the moment let's verify how this works and which one executed first now we need to add the basic auth Handler Interceptor to the registry again similar to what we did for log Handler interceptor now it is added to the registry let's run it again Now Products list so one thing to notice here is the first it prints the log Handler intercept of prehandle method and then it goes to the basic auth Handler interceptor once the all the interceptors are executed then it goes to the controller now when it is coming back from the controller the first it executes the basic authentication Handler and then it prints the log Handler interceptor okay and finally it prints the after competition method again uh in the same order as the post post handle now what if we want to change the order we want to execute the basic authentication before the log Handler and you can do that here by adding the order method here and let's give the order is one what it means is the basic auth Handler Interceptor will be executed before the log Handler interceptor okay so here we give order 2. now as you can see the basic authentication Handler Interceptor is called before the log Handler Interceptor okay and this is because we have specified the higher order for the basic authentication interceptor now what if you want to execute certain Interceptor for a specific endpoint of specific URL you don't want all your Interceptor to be executed for all the time right so now let's say if you want to do that you can do add path patterns and here we need to specify let's say products Slash new so what we want is whenever we are hitting this endpoint product Slash new endpoint then the basic authentication Interceptor should be executed okay let's run that again now you see product list when you hit that it is not going to that intercept at all it is only printing the log Handler Interceptor but but if I go to my new endpoint now you see the basic authentication Interceptor is printed and then it prints the log Handler Interceptor basically for the product Slash new endpoint both the interceptors are executed however for the list endpoint only the log Handler Interceptor is printed okay so now let's expand this uh into doing the basic authentication check now what we want to do next is uh when somebody hitting this product Slash new endpoint we want user to provide a username and password and if they don't provide that authorization username and password then they should not be allowed the service so for that you click on the authorization Tab and here go for basic auth and enter your username and password I'm adding admin and admin okay so when you do this okay so right now it uh the authorization headers has no impact or no effect because we haven't done anything yet now let's go back here on the code section so one thing you notice here is the username and password that we are passing here is getting converted into base64 and it has a specific four bit for it all we need to do within our basic authentication Interceptor is we need to extract this header and then we need to get this base64 string then convert that back into the username and password and then validate within our Java application okay so for me let's copy this and go back to my job application let's paste it here for our reference we can delete that later so the first thing we need is let's create a constant username and password okay so let's say private static final so I've created two constant so this will be the hard-coded username and password we will use to validate our user to keep this example simple I'm not having any database operations here so that's why we have created two constants and we will validate against these constants now the next thing we want is we want to extract this header the authorization header now to do that string auth header request dot get header and you pass the header key that's it and once you have the authorization header now the next thing you want to verify is the authentication header should not be empty and it should also be starting with a basic okay so once it starts with that the next thing we want is let's extract the base64 string which is this part okay now you can do that using substring method so basic stable credential equals to auth header Dot substring and here we can just give basic space this [Music] okay so the next thing we need is we need to convert this base64 into the plain text format and for that we can use the Java utils base64 package okay this is the decoded credentials okay now let's convert this byte credentials into a string format here you can optionally provide the encoding format which is utf-8 okay now what we will get at this point is we will get this getting converted into a plain text format but when it is converted by default it comes like this like admin colon admin so the first part is going to be your username and the second part is going to be your password now let's split that and split that into two parts and to do that let's use string but let's convert that into a string array string parts [Music] okay now these parts will have two values here one is the first item will be the username and the second item is going to be the password now let's here put the conditional check if username dot equals part Sub 0 okay password dot equals parts of one okay now if the username and password is correct we want to continue with the controller and that's why we will return true now here in all other cases it should return false that means the controller should not be invoked now here we can also return an error message and to return an error message let's do response Dot send error okay so here let's use http response.unauthorized okay so this is all you need to do uh to create your basic authentication check so so all we did is First we extracted the authorization header and then we are verifying that authorization header is not empty or it should start with the basic then we are extracting the basic and space here so it Returns the base64 credentials only then we are trying to convert the base64 credentials back to the plain text here and then we splitting getting the username and password into two parts and then we are validating the username and password provided by the user with the username and password we have hard coded here okay so we have created the basic authentication Interceptor and the Interceptor is also being added to the registry already so we don't have to do anything let's go and run it now go back again and try to hit new okay this is returning 200 okay because we are passing the username as admin and password is admin but let's change that to something else okay so as you see we are getting unauthorized error 401. now this is all for today's video if you have any questions about spring interceptors or any other related spring Concepts please write down in the comment section below and I'll try to respond as soon as possible if you like this video and if you want to see similar videos in future please like And subscribe my channel for more such contents thank you for watching and see you in the next one