Complete Spring Security with JWT Authentication | Spring Security 6 | Securing Spring Boot

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
so before we move any further I want to tell you that I'm doing a massive giveaway on this channel yes this is the first giveaway that we are doing here and it's all because like uh because of the love and support that I've got from you all in the past few weeks uh and I'm super happy to see this channel grow and I thought of giving it back to my audience so what is the giveaway so I'm giving away one year free complimentary access to any jet brains ID of your choice yes the paid version of any jet brains ID is what you will get for free for one year okay and right now I'm here on the jet brains website so jet brains uh if you are if you have been developing for a while you would be aware of Chet PRS it it's a company behind a lot of stuff okay so like intellig they have things like py charm these tools are really popular right and they have a lot more tools like PHP strong and all if you're a PHP developer so this is a prizing and the winner will get any one ID of their choice for one year okay and this will be a free compliment access they can make use of the pro version for their development needs now of course uh I believe like this would be really valuable to my audience because my audience is mostly developers and a good ID when you are doing software development is all what makes the difference right and uh the pro version of jet brains ID like intellig idea ultimate or py Charm pro version they all come with a lot more features uh that developer can use it for okay and it makes your life really easy so I would be giving away this to One winner okay there will be one winner I'll be picking the winner randomly okay and uh I will be reaching out to them and I'll be helping out with the next steps as to how they can redeem it okay now one thing I would like to mention or one thing you would ask of course how would you participate in this giveaway so yes you need to head over to the description and you will find a link uh which will enable you it's it's a link of a form where I collect like a few details uh so that I can reach out to you and you need to fill in that form and that form will Mark your participation in this giveaway so so be sure to uh enroll in okay and uh be sure to participate and leverage this opportunity okay also I would be announcing the winners in the telegram Channel and also on the YouTube so I would request you all that you should hit subscribe and turn on the Bell notification icon if you're liking this okay also be sure to join our telegram Community is something that I would mention okay uh because telegram is where I stay connected to uh people and uh telegram is where I will be also Al putting in the names of the winner okay so so be sure to subscribe to telegram as well that would help a lot okay and subscribing is really important people uh that means a lot uh and it helps me bring more such amazing content for you all right and of course these these kind of giveaways as well so subscribers motivate me and uh they uh motivate me enough to create so much free so much for free and also host uh such giveaways all right so so yeah what do you think about this giveaway let me know in the comment okay I'll be reading all the comments let me know in the comment of the video as to what do you think about this giveaway all right so if I I'll take a look at the entries and if I decide to extend the date or prepone the closure of the giveaway I would be putting all these details on my telegram channel so be sure to uh follow there as well okay to uh to get further updates all right so so yeah that's that's about it and I won't take much time let's move forward what's going on everybody welcome to this video and I'm back with an amazing course on the most requested topic Spring Security Yes you heard it right A lot of people a lot of viewers who are watching my videos they used to comment repeatedly that hey when are you making a playlist or a course on Spring Security I received quite a few emails as well and uh I thought okay let's let's do it okay so this is that course that will teach you everything about spring security from scratch and yes in my style very Hands-On way okay so I like if you're watching my videos uh you would know like I don't make use of a lot of ppts okay so in programming it's I believe like it's important to learn things Hands-On and uh Hands-On learning is the best learning that you as a software engineer can have okay so so I believe in Hands-On learning and that's what uh I I do to my students as well okay so so this is going to be a very Hands-On course we are going to cover Spring Security like I said from scratch and when I say from scratch we are going to cover everything like what happens when you add dependencies to your project okay so there's a behavior change in the application we are going to explore that okay what is form based authentication and how can you make use of it then how can you write your own Custom Security filters well if you're not aware of what security filters are don't worry I have all of this covered uh we also talk about how Spring Security works like how the entire mechanism I explain this to you with a with the help of a nice diagram we also uh then switch our application to inmemory authentication right so inmemory authentication is a way when we start creating our users in memory and uh then we switch to database back to authentication wherein our users move from inmemory to database so so that's uh that's something we cover because these days database is a very common right you would find an app that does not make use of database and uh when it comes to securing your application it's important that you store all your user credentials in the database we are going to cover security aspects like hashing and uh how can you store uh your passwords or dat users password in in an encrypted format and not in plain text format so how can you encrypt them into a non-readable format all of that I'm going to cover and lastly we are going to talk about JWT so JWT authentication what it is and uh how can you make use of it I'm going to explain everything to you in a step by-step manner line by line coding okay that's what everybody says line by line coding so so that's that's how this uh course is designed and yes uh we write code majority of the time okay so every line that I write everything that happens in the app I explain it to you that's how this uh stuff will go okay so if if this sounds exciting okay then you should hit the like button and if you haven't subscribed or turned on the Bell notification icon you should hit that subscribe button turn on the Bell notification icon because that's how you can stay updated with the future courses or the upcoming courses that I'm going to post on this channel there's a lot of awesome stuff cooking in I'll tell you and uh I'll be posting a lot in the next weeks uh like the coming weeks I should say coming weeks coming months a lot of content is coming in okay so be sure to subscribe stay updated your subscription also means like a support to me so the number of subscribers like comments I get impact my ability to bring in more such amazing free content to you all on this platform for free so subscribe and like if is uh the least you can do to support creators like me okay so so yeah that's about uh subscribing and liking also if uh you're watching this far then I would want to know you more so who you are where are you logging in uh where are you watching this video from basically and what do you do currently and what sort of courses would you want to see on this channel so be sure to leave all this information in comment I would love to read them and uh let me tell you like what whoever whatever comments you people leave uh right I read them personally and I have a list of upcoming courses on this channel or I would be working on so that list is influenced by your comments so you have a chance uh literally over here to influence that list okay so if many people request a course like the Spring Security course a lot of people requested so I thought okay let's uh make a course on this and uh yeah so so yeah be sure to leave a comment I would would love to read your comments okay so that's about uh this video and everything that uh we'll be talking without a further Ado let's Jump Right In and let's get started well I know most of you want me to go Hands-On directly and uh show some code right but to implement Spring Security into production grade applications you need to understand some Concepts that are important and I'm going to talk about those Concepts because once you understand these Concepts then you will be ready to implement Spring Security into any of your springbot applications so please bear with me for a while I'm also excited to teach you in a Hands-On way this is a Hands-On course of course but yes some Concepts we need to touch upon and for that we need to touch the slides okay so first thing I want you to know that security is important of course you understand this and that is why you are here watching this okay now what is security so security is securing something okay and you have a house right you have doors windows you lock your door if you're out right Spring Security does something similar for your web application it's like a sophisticated security system that you implement in your application and that system ensures that only the right people can access certain parts of your application and this helps you keep your data safe and sound okay so in case of your home why would you lock your door and windows when you're going out of course so that no one can come in and access your personal things right similar way it works with your web application okay and Spring Security helps you with that all right now if I have to talk about the importance of security number one important thing is privacy protection so just like you don't want strangers speaking through your windows your users don't want unauthorized people seeing their personal information as well okay so protecting user data prevents identity thefts and fraud this is something that you need to understand trust so if your house is known to be easily breakable people will be wary of leaving their valuables with you right in a similar way if an application is known to be insecure users and client will not trust trust it with their data okay so if you're building something then having that credibility having that trust is really important in the market Integrity imagine someone sneaks into your house and replaces your important documents with the fake ones okay so in the digital world application security ensures that the data remains unchanged and trustworthy preventing from unauthorized modification okay compliance the this is also important so there are laws and regulations about building Security in real world okay and there are also legal requirements for data protection in digital world so security helps ensure compliance with these laws avoiding legal consequences okay so this is the importance of security now let's talk about role of Spring Security within the spring ecosystem so we have spring framework it it's like a foundation like the structure of your house then you have spring Boot and it's a module that makes easy to set up and run spring applications it's kind of like having house built with all the utilities connected and ready to go right so there are a lot of features of springboard like Auto configuration and all that make your life lot easier okay then you have spring data that help you manage data access okay and then you have Spring Security okay now Spring Security is a key player in the spring ecosystem it's a collection of tools and Frameworks for building Java applications and using Spring Security means that you're protecting your applications data like you would protect assets in a company safe or anything personal okay so there are two important things that you need to understand when it comes to security and when also it comes to Spring Security so number one is authentication we will take a look at what authentication is okay and then we'll talk about authorization so most of the people I speak to they get confused about these two terms okay so I want some clarity around this first and then when we head over to implementation you will have a clear understanding as to what we are doing and why we are doing okay so talking about authentication and authorization authentication what is authentication authentication is proving who you are okay so if you are going into a restaurant or if you're going into a hotel okay you'll have a security person or someone at the reception whoever who will ask you for your membership card or how you are entering any sort of authentication that authenticates that you're allowed to enter okay and showing that thing proves that you are a member and uh that's the authentication that you do right in your computer when you log in you're entering your password your username and password or you if you're using Mac or any other laptop which has a fingerprint scanner you will scan your fingerprint right and it authenticates that it's you who are supposed to use the system and you are using the system that's authentication what is authorization authorization is about what you're allowed to do after you have proven who you are right so you have proven who you are now if you enter a hotel okay you enter as a as someone right you show the identity card and you are allowed to enter you enter but now you might not be allowed to enter every place of the hotel right you might be allowed to access certain rooms or certain facilities and there will be specific permissions that will be with you okay you cannot enter for example a security Zone you cannot enter a particular area or you cannot enter someone else's room you are not authorized to go there right you're authorized to use your own room so that is nothing but authorization okay and in a computer system authorization decides what actions you can take after you log 10 okay so let me reiterate over here okay what is authentication authentication is like you are entering your username and password okay you enter your username and password you get access to the system okay what is authorization with authorization okay so if you are having an application you're going to have roles right so user a will be allowed to do a certain thing user B will be allowed to do a certain thing okay user C cannot delete a certain thing okay so this authorization so you authenticate user a okay user a will enter username and password and he'll say all right I'm user a so he's given access to the system now after getting the access he cannot delete a particular record that's authorization okay so stopping him to delete a particular record is authorization okay so there are two aspects of security over here that you need to understand authentication authentication is gaining access and it's proving who you are authorization is about what you are allowed to do after you have proven who you are okay so in a sense as a developer you need to implement authentication in your application and you also need to control the authorization okay so if you are implementing something if you're building a simple application and if you don't need authorization like everybody's allowed to access everything that's absolutely fine authentication is what you need to deal with but Norm in every application that at least I have seen authorization is really important okay so there will be an admin so if you're building an e-commerce store there will be an admin right who can create products who can view orders who can view customers phone number there will be a customer support executive who cannot view the revenue who cannot like create a product right he can view the support tickets right so that's authorization all right so this is something that you need to understand now let's talk about some key security principles okay first principle is least privilege okay so users and processes should have the minimum level of access or permissions that you should assign to perform the necessary task okay so whenever you are assigning something to anyone make sure you give them the least level of privilege to complete the task okay secure by Design now what does this mean so security consideration should be integrated into the design design phase of software development rather than adding it as an off thought okay so what happens is I'll tell you normally we developers we get requirements from someone in the company like let's say a manager or a product owner someone depending on how your hierarchy is designed okay security is not given a thought at that time okay so whatever requirements you're getting from the client or whoever okay he's going to give you all the functionality he wishes to have right right people normally don't mention security as an aspect okay it has to be considered by default by you as a developer okay and you have to think of security into the design phase itself so when you're designing your application thinking about different components you have to think of security that's the best approach okay normally what happens is developers build the system and then they implement the security and then they start thinking about security Okay so so this is not good but it has to be secure by Design okay fail safe defaults so system should be designed with secure defaults meaning they should operate securely out of the box without requiring additional configuration secure communication so whatever communication you're doing transmitting data over the network it should be encrypted and you should prevent any interception over there okay and uh it's essential that you protect all the secure information that you are transmitting input validation so all the input data from the external apis and everything should be validated to prevent any sort of attacks like SQL injection and so on okay this is also important auditing and logging so you should have logging and auditing mechanisms to record the events related to security and all the actions that are being performed in your system so normally what happens is there is a separate logging module that is built in you you see or you work in a production grade environment so logging model what logging model will do is who is doing what in the system that is being logged into a separate table okay so for example if you are an admin and if you're creating a product changing access R so all of that is being logged okay that this user at this time he did these these things so that whenever there are any security incidents later on or any sort of breaches so team can then investigate as to what happened and what led to this breach okay so this is one aspect regular updates and Patch management this is important so you need to keep software dependencies libraries Frameworks up to date with latest security patches and fixes because in the latest updates normally uh the latest vulnerabilities or the new vulnerabilities have been fixed so that is something that you need to keep in mind all right so this is about some of the key security principles that you should be aware of hey there welcome to this video and in this particular video we are going to talk about how Spring Security works now if you're new to this Channel and if you're not aware this video is a part of a complete series on Spring Security well it's a series wherein I cover Spring Security in a very Hands-On way okay you can find the link to the entire playlist in the description below where you'll find the videos before this video and after this video okay so you can watch the entire playlist also if you new I would highly encourage you all to subscribe to this particular Channel and turn on the Bell notification icons because that's the way using which you can stay connected with me and you can get notified as to when I upload or bring in any such new course or any such new video okay so be sure to do that also talking about this video now in this particular video we are going to talk talk about how Spring Security works now if you integrate Spring Security into your project there are a lot of things that happen in the hindsight okay there are a lot of components that Spring Security has okay and all of these components work together to secure your application and it's really important that you understand what these components are how you can make use of them and what does each component do in the entire process okay so all these things are really important okay and uh do watch this video till the very end because there is lots of valuable knowledge that you going to gain from this all right so yeah that's about what we are going to cover also if you're watching this video so do leave a comment right now and let me know where you're joining in from what's your good name what do you do currently and let me know what sort of videos I should be bringing in for you all okay so that's something that I would be expecting and I would be reading the comments personally okay so without a further Ado let's Jump Right In thank you hey there so it's time that we talk about how Spring Security works so in a normal spring boot application you will have your controllers over here and you will have requests coming in and response going out okay so this is the entire diagram that explain the working of Spring Security don't get overwhelmed by the diagram it's actually simple I'll break it down for you okay so like I was saying you have controllers here okay and you have request and response going out okay request coming in response going out now when your request comes in it first goes through a series of filters over here okay so here you have filters this is one filter second filter third filter so on there are many filters okay depending on what you have configured okay and your request has to go through this series of filters known as filter chain and then it reaches the controller okay and controller is where your actual application code resides okay now these filters have a specific job related to their own configuration okay and if you have Spring Security configured then you will have a filter called as authentication filter okay so without security you will also have filters exist in your application but these won't be the security related filters okay but when you configure security you will have some filters added which will be the security related filters okay and one of these security related filters like I said is authentication filter over here okay now what is authentication filter so authentication filter will be intercepting the requests that are meant to do login okay so that are login requests and these requests will contain username and password or any sort of authentication information that needs to be validated all right so so far what are filters filters are nothing but a some code okay that reside before the controller and your request has to pass through it okay they will intercept your request for some sort of processing and you have authentication filter if you have Spring Security configured in your project okay what does authentication filter do authentication filter will intercept the authentication request and what it will do is it will grab the username and password and create authentication object from them okay and this object is basically a way to package the credentials okay so first the authentication object is created okay because everything within security works in the form of the authentication object so that object is important first okay and that is being created here once the object is being created the object is being handed over to the authentication manager over here okay now authentication manager is someone who decides what to do with these credentials okay so what this authentication manager will do is it will delegate this task okay of authenticating the user to some someone else okay so authentication manager like I said it decides what to do with these credentials okay and it'll say that hey what should I do with the credential I should authenticate now to authenticate Whoever has sent this request I need a authentication provider okay so authentication manager decides that hey he needs to authenticate and for that he'll need a authentication provider now authentication provider what is authentication provider so Authentication provider is someone who is responsible for checking whether the given username and password or whether the given credentials are correct or not okay and for authentication provider to validate the credentials it needs two things one is password encoder and then it needs user details service so we'll talk about each one of them so we'll talk about password encoder first okay what is password encoder so what happens is whenever the password is passed in or whenever the user credentials are passed in okay they are always encoded right they will be encoded using some form of encryption right and to decrypt the password you need to do some sort of like processing over there and that is what password encoder helps you with okay so it helps you encode the entered password and it will help authentication provider with the same so that authentication provider can take care of the rest okay so this is about password encoder okay and what is user Detail Service so this is called by the authentication provider to load the user details and it can call methods like load by username and all and it will load the details like username password and what all roles does this user have in the system okay and it will load it from a source of data okay so if your data is being stored in the database it will load it from there okay and what happens is this particular service will load the user information okay and it will return this particular information which includes everything that system needs to know about the user including the store passwords roles and all okay it will get this user object and it will convert this object into user detail object okay so the object that is returned by user Detail Service is user detail object all right and then this particular thing over here authentication provider will have the user details so authentication provider will confirm if the username and password are correct okay and uh once it is validated that the username password are correct it will create a complete authentication object okay so authentication object earlier that existed which was created by the authentication filter that might not have some information like roles and all okay so once the authentication is successful and it's confirmed by the authentication provider the authentication object is populated with more details like roles and all okay and then this object is handed over back to the authentication manager here that hey this is the object updated object and uh this is the user that you wish to authenticate and this user has been authenticated okay then this object is returned to authentication filter and then the security context is set okay so what is security context so security context is a sort of context that is available throughout the duration of the request okay so it's a context wherein the information about the authentication is stored so where does the detail of the authenticated object reside now it resides in the authentication object right right so this authentication object was created by filter and the details more details were populated by authentication provider so then this object is set into security context and it will be available throughout the request okay and throughout the request this object is referred as to what the user is allowed to do in the system and what it's not allowed to do in the system okay so like I mentioned that uh when the authentication is being done the authentication object is being populated with what with roles right and these roles are being used by the application to dictate as to what the user is allowed to do and what the user is not allowed to do okay so this is how the entire flow works okay here how the flow works is if I have to reiterate user you as a user enter the username and password okay and uh it it goes through a series of filter chains over here okay filters over here and one filter will be authentication filter okay and then an authentication object is created here okay authentication manager takes this object and asks authentication provider to verify it okay then authentication provider will use user Detail Service and password encoder to fetch your details and password encoder will compare the passwords and everything if everything matches okay the authentication provider will confirm and your details are saved in the authentication object like the authentication object is updated with the rules and all and the security context will be populated with the authentication object and then you are allowed to access the controller and the code executes and during the request this context is referred as to what you're allowed to do and what you are not allowed to do okay so I hope this is making sense now when we talk about authentication provider here I've mentioned Dow authentication provider okay so this is one of the common authentication providers used and this is used when you wish to validate the users against the database okay so normally you have a database where the user details are stored and if you want to do that you can make use of Dow authentication provider okay and it relies on this particular service here user details service to fetch the user details and then compare it with the provided credentials against these details okay so this is one kind of Provider but there are many providers like inmemory authentication provider is one of the providers okay so if you're storing your data into memory and not in the database okay then you can make use of inmemory authentication provider there is ldap authentication provider okay ldap if you're aware of lightweight directory access protocol okay so if you wish to uh integrate ldap security then you have to make use of that provider you have jdbc authentication provider okay so there are a few authentication providers that exist so depending on where your user details are coming from or where they are stored you will use the appropriate authentication provider okay and you can see the methods over here so authentication manager will call the authenticate method okay you have matches method to match the password load by username these are all methods find by username okay these are all methods that exist that are called by the respective components okay so this is about the overview of Spring Security One crucial thing to remember over here is the concept of filters over here so you're going to see filter authentication filter authentication manager authentication provider password encoder user Detail Service all of this in the code okay so it's important that you understand these and the roles and if you still have any confusion don't worry uh everything will be clear once we start coding things okay but it's important that you understand the concepts at a high level so that's about the working of Spring Security I hope this was useful hello everyone welcome to this video and in this particular video we are going to take our Spring Security playlist one step further so what are we going to cover we are going to get started and we are going to configure a project with Spring Security we are going to understand the default behavior of Spring Security and how the autoconfiguration magic comes into place and we are going to explore form based authentication so if you're new to this Channel and if you're watching my video for the first time then head over to the description because this video is a part of a complete playlist on Spring Security and we are learning about Spring Security right from scratch till the very end okay so be sure to check out the playlist to get access to the earlier videos and also the videos that are coming after this one okay that's something that you should do if you are new and also if you have not subscribed to this channel then hit the Subscribe button and turn on the Bell notification icon because that's how you'll stay updated as to what I am up to on this channel okay so there are lot of free stuff and lot of videos that are coming up and uh if you like to stay updated then you should subscribe talking about this video now so like I said we are going to configure a project with Spring Security and we are going to see the auto configuration mechanism of spring boot in action so you'll see how the auto configuration mechanism coming into place and how there are lot of default stuff that are already built in basically you will see all the entire magic of autoconfiguration and the benefit of using spring boot okay so we'll explore the default stuff and how we get a lot of things without even writing a single piece of code okay so it's going to be really exciting and this is completely Hands-On all right and also we are going to explore the form based authentication in Spring Security okay we are going to understand what it is and how it works and how you can make use of it okay so this is something that we are going to cover and stick till the very end because there is a lot of knowledge that is packed into this video okay and uh be sure to follow along as well also if you have watched this video so far then I would want you all to comment below and let me know who you are what's your name what are you doing currently where are you joining from and what kind of videos you wish to see on this particular Channel for free so so there are lots of courses that are planned on this channel and I plan to upload them sequentially but uh yeah do comment and you have an opportunity to influence my upcoming set of videos over there okay because I'll tell you I read all the comments personally and all the feedback or request is taken into consideration okay and the next set of videos are planned based on user request as well okay you have a chance over here to influence that list that has the upcoming set of videos all right so yeah I won't take much time without a further Ado let's Jump Right In and let's get started so now it's finally time that we go handson with Spring Security and to go handson we need to head over where we need to head over to our favorite website which is start. spring.io I'll select Maven I'll select the required spring boot version and we can have security added over here security demo something like this okay and this I'll call Basic com dot or I'll say example okay I'll just keep it example okay you can keep it whatever you want all right I'll add a dependency I'll add web dependency okay and uh I'll just generate the source code so download the source code and open it in intellig so so I have this project open here in intellig okay and uh here I have the entire project structure loaded and I have the web dependency in the for.xml okay so far so good now what I will do is I will quickly come over here I'll create a Java class and I'll create a controller very simple controller greatings controller okay and uh here I'm going to have this defined as a rest controller okay and uh here I'm going to say public void or I don't need void I'll say string and I'll say say hello here okay and what this is going to do is this is going to return Hollow over here okay a very simple endpoint okay people and here what I can do is I need to add a Endo over here right so what I can do is let me add a hello endpoint so I'll say get this has to be get and I'll say slash hello okay we are done let me run this application so I'll run this okay and uh you can see the application is up and running okay now what I will do is I will switch over to my browser okay here okay and I'll say Local Host 80 80 and I'm going to say hello here you can see Hello as the response so this is a default Behavior right now let us add security into our project and let us see what happens so so far we are able to access our endpoint from the browser right there are no issues as such now here I'll say add dependencies I'll say security so you can see this dependency over here okay you can see like this is uh the official one okay and you can read about this it's highly customizable okay authentication and access control framework for spring based applications okay it integrates seamlessly with spring boot okay and it enables you to add security features into your spring boot application very easily also there's a great deal of autoconfiguration involved okay this is something that you're just going to experience in minutes okay so you can head over to like explore and here you're going to see this particular dependency here okay you can see like spring boot starter security and here you can see spring boot security test so this is the same actually pm. XML here what I can do is I can actually copy this pm. XML and uh I can come here and I can actually replace it over here something like this okay now if there are any changes into p. XML what are you supposed to do you're supposed to reload the maven changes okay because you need all the fresh dependencies com in and you should see some security related dependencies coming over here okay so okay here you can see security security security so all this has come in okay so it's done now let me rerun the application so our application is running okay you can see up and running and now let us try to access the API let me hit refresh okay I had zoomed in so it just showed me this big login page so this is a login page and it's asking me to login I didn't go to login I had just typed in my endpoint here hello you can see it's redirecting me to login all right so this is the default behavior that happens when you integrate Spring Security into your project okay so this is the default behavior of Spring Security okay this is something that we have not configured we have just configured Spring Security and we see this so now it's time that we talk about the default behavior and understand what it is so if we access the endpoint over here so I'm entering hello you'll be automatically taken to a login form and this is a form that is asking me to sign in now where do I get this credential ials for okay so I'm understanding one thing that after integrating Spring Security so integrating as in I have just added the dependencies and after doing that I'm straight away being shown this particular form so the end points are protected or secure I should say which earlier they were not they were open and anybody on the internet could have access those URLs and now we are being presented with a form and the best part about this form is we have not built it okay this is an inbuilt form that is coming in all right and uh what we need to do is we need to figure out how we log in so I'll come over to intellig I'll open my run console and let us take a look over here okay so here if you scroll up you'll see something called as using generated security password and this is a password that is being printed onto the console okay so you can see this password is being generated for development use only and uh if you're pushing this code to production your security configuration must be updated so I'll copy this password over here okay and this is a password that you will make use of to login into the form over here okay and uh if you scroll up a little bit okay you'll see a lot of other logs over here which we'll talk about shortly okay so let's come over here what I'll say is I'll enter a username now what is a username username is user by default over here okay this is an default user that has been created for us and I'll paste the password over here and let me say sign in now the moment I say sign in you'll see Hello being printed and now we have the API working okay so you can see how this was this was protected behind a login wall okay and if you come over here okay so if you go through the logs over here there is a lot happening okay so we started the application okay you see the application has been started until here and here you'll see default security filter chain okay will secure any request with so you can see all of this filter chain over here you can see different filters log out filter csrf filter so these are all different filters that are coming into play okay and you are seeing some logs around them and this indicates that there are some filters that have been made available by default okay and they are coming in from the security dependency that we have added so you can see security everywhere right so that is what is happening right now okay and uh we also have a default user to whom we have access and this is what the password for the same is okay now if I restart the application I'll show you something if you scroll up over here okay this password changes okay so this password changes with every restart okay okay and this is something that you are supposed to know over here okay now a question you might ask is here I have locked in right now if I wish to unauthenticated myself what do I do okay so first of all let me do a refresh I'll be presented with the form again because I restarted the application and the password has changed okay I'll come over here and I'll paste it I'll say sign in oops I got an error so probably it's not getting copied properly here I'll say you user and I'll paste the password okay so this worked all right now if I want to log out I have an access to a log out page as well okay which is like very awesome okay so if you just go to your local host like your url SL log out you're going to be presented with this form are you sure you want to log out and you can say log out over here and you will be signed out of the application okay so so this is what something that you need to understand okay and and there are few observations that you need to remember over here or you need to make okay number one is all the end points or everything is authenticated so if you add more endpoints to your application if you have just added Spring Security and you have multiple endpoints everything is secure okay everything is authenticated this is observation number one okay the default authentication is form based authentication so this is a default authentication that is in place okay and as you can see this is a form based authentication which means that this authentication works with the help of a form and this form is an inbuilt form this is something that we have not created okay so this is observation number two observation number three is that we have been given access to inbuilt forms like this one the login one and the log out one this is something that we have not created okay so this is observation number three observation number four over here is we also have access to a default user or a test user I should say which is created by default with a default username and password like this okay so this is observation number four and uh observation number five is you get access to a default password on the console as well okay and this is autogenerated password over here okay and if you try to access the URL over here you're being presented with this form wherein you need to enter the credentials that you have and you get get access to the application okay also if you inspect the headers so if you right click if you say inspect so right now I'm on Chrome and I'm making use of chrome developer tools if you go to network over here you should be able to see all the requests that are happening okay so let me show this to you so I'll copy the password again here this one I'll come over here I'll say user and I'll paste the password and here you should see the request that is happening with all the details so if I sign in you'll see okay so okay I should access hello over here okay but what happened is I just went to login and there was no redirect so that is why I'm getting this error okay which is fine we'll ignore this but we just want to see the login request over here okay so you can see over here you have slash login but the status code is 302 okay so I wanted to show you the status code of uh 200 but uh no problem let me show this to you again so I'll just go to log out I'll say log out all right I'll just go to hello again over here okay so just go to Hello and you'll be presented with this login page okay I'll clear everything over here on the console by hitting this button and I'll say user and the password and I'll say sign in you should see Hello over here okay and you can see login over here okay so this is 302 because we are being redirected okay so you won't get 200 over here this 302 all right and here if you scroll down you can see everything okay you can see the response over here okay here there is no response okay because um you were redirected over here okay but you can see over here this is the login request okay and you are seeing post over here and if you scroll down here you're going to see few response headers as well over here okay some headers which says X content type options no SNF so these are all the security related options that have been set by default for you okay and of course if you go to Hello API call over here okay you will see 200 okay so on login you'll get 302 redirect and over here you'll see 200 okay all right so this is about the default Behavior okay and this is how Spring Security dependency or adding Spring Security into your application this is what the impact you see in your application so I hope this was useful so we do have access to a automatic generated user password over here all right and we using this for our login over here right but this password is not static it changes on every application restart so one way to fix this particular password so you don't want to have a new password every time you rerun your application so to fix it you can add a property so what you can do is you can head over to system uh you can head over to application properties not system properties and here you can add a property you can say spring. security so since this is related to Spring Security you can say user dot password something like this okay and here you can add the password so I can say demo at 1 2 3 something like this okay and now when I restart let me see so you can see there is no default password that is being printed right now you can see over here okay there's no default password all right and this is because we have added a password ourselves okay so what I would do is I would head over to hello here something like this and I will say user and I'll say demo atate 1 2 3 and I'll say sign in and you can see this is the password that we used to login so this way you can like fix your password okay and uh you can even add a username if you wish to okay so you can come over here you can say spring. security do username something like this and you can say username is admin all right and uh you can rerun the application and you can come over here you can like head over to hello and you'll be asked for login information you can say admin and you can say demo atate 1 23 you can see so this way you can configure one username and one password from the application properties please note this is not the production ready way to do things this is good for development purpose okay because here you are hardcoding the password of the users you're hardcoding the username in the codebase itself which is not actually what you would want to do in a production grade environments but this is how you can save yourself from copying the automatic generated password every time all right hey there everyone welcome to this video and this video is a step forward in our Spring Security playlist that we have been doing on this channel okay so the goal here is to learn Spring Security right from scratch in a very Hands-On and a practical way okay and that's what we are doing and if you're watching my video for the first time or if you're new to this particular Channel then you should be aware that there are a few videos that are uploaded just before this one and you can get access to all of them right in the description so head over to the description and there you'll find a link to the playlist okay and uh that playlist has all the videos like a set of videos before this one and after this one so be sure to access that okay and also if you wish to stay updated with more such amazing content from myself you should hit the subscribe button there and you should also turn on the Bell notification icon okay uh so that's how you can stay updated and of course that's how you can support me or creators like me that's the least you can do okay because number of subscribers is what impacts my ability to bring in more such amazing free content for you all and also to continue uploading videos on this platform okay if you wish to see more videos coming up or if you wish to motivate me to upload free stuff you should hit subscribe okay so talking about this video we are going to cover basic authentication okay uh so what we going to do is we are going to learn how you can write your own set of security filters yes I'll take you step by step okay and don't worry when I say we're going to write our own security filters it sounds overwhelming but it's actually not I'll take you step by step as to how you can write your own security filter and we'll understand everything line by line okay and we are going to understand and experience what is basic authentication how is it different from form based authentication we also going to see how you can access secure apis using Postman like tools like Postman and all which you always use when you work with apis Okay so all of this we are going to cover in this video be sure to stick till the very end because there is lot of stuff that's packed in okay and everything is hand on okay very minimal user slides like always okay so yeah that's about this video also if you have been watching this video so far be sure to leave a comment below let me know who you are where you are joining in from what are you doing currently and what sort of videos you wish to see on my channel okay uh because uh whatever videos I plan I normally take a look at the user requests or the comments that I get and what viewers want to see so you have an opportunity here to influence my upcoming list of videos there okay so be sure to comment and yeah without a further Ado let's Jump Right In and let's get started with this video so right now we have a form based authentication enabled by default and what I mean by Form based authentication is we have a form in place that is being used to authenticate the users all right but if you're working with rest API form is not what would work for you right so in rest API you don't have an interface and you would typically be making use of tools like Postman right so there is one more way of authenticating users that is different from form based authentication it is known as basic authentication okay basic as the name suggest is the basic way of authenticating users with the help of username and password so let us see how can we configure a spring root project to enable basic authentication so what we will be doing is we will be first checking the code for our default authentication method okay so what I'm going to do is here on intellig I'm going to enter shift two times and I'm going to search over here for a file spring boot web security configuration so you will see this this particular class over here okay web security configuration okay this is an inbuilt class that is coming in from you can see spring framework boot autoconfigure security. serlet okay and if you're not able to see this over here like the internal inbuilt classes okay what I would request you all is you should go over here in file you should select settings and uh over here so we will have to go to build over here and there is a option for Maven so Maven option you'll find under build tools and over here you can select Maven and uh here you you select importing so here if you select importing you're going to see these three options so you can enable these three okay so what this will do is it will automatically download the sources documentation and annotations for all the libraries or dependencies that you are adding okay so if you're not seeing for some reason you should be able to see after you enable this option all right so this is there and I was anyway seeing this information here you can head over to this particular class okay so this is an inbuilt class all right and uh this is where you will find some source code written and this is the class that has the method which has the source code for the default authentication method so you can see over here this is the default configuration and this is how we are authenticated in a default way so you can see over here we have HTTP form login by default we have the basic authentication enabled over here okay so over here for some reason I'm not seeing the comments appear over here what I will do is I'll do a maven reload one more time okay and let us see if we see the comments appear over here okay so you can see over here it's downloading Maven Library sources and documentation this will take a little bit of time okay but it will automatically be downloaded and it will automatically index it and show it to you okay but if for some reason we are not able to see we are good then do okay but you can see over here I'm able to see this over here so after changing that setting in the preferences I have the documentation also being added over here okay and code is much more readable now right so you can see over here here you have access to the documentation so it says this configuration that you're seeing here this over here okay this is a default configuration for web security okay and it relies on the spring Securities content negotiation strategies to determine what sort of authentication to use okay so here you as a user you can see over here you as a user can specify your own security filter chain Bean okay so we know the concept of security filters so you as a user have the ability to Define your own security filter right and how you have to do it you have to create your own Bean over here okay and uh once you define that this particular code won't be used this is a default one because if the user has not defined his own Bean or his own way to authenticate users then this one will be used so it says clearly over here this will be completely backed off and users should specify all the bits that they want to configure as the part of Custom Security conf configuration so I hope this is clear okay let me explain this code over here so this is a short code that is written here okay and as you can see here this is the default security filter chain it is taking in HTTP security as a parameter over here okay and what it is doing over here is first line if you see it is saying authorize HTTP request okay and here as a parameter it says authenticate any request that is coming to the application so any request that comes to the application is authenticated by default okay this is a default Behavior right and this is what we saw any API or any endpoint you try to access it is authenticated by default right second thing says that there is a form based login that is enabled with default configuration here all right and then there is also basic authentication that is enabled with default okay so form login is for web so like we were accessing the API right from the web by entering the URL over here right so we were seeing the form based authentication here but if you try to access it from somewhere where there is no interface like for example tools like Postman Postman does not have an interface to see the UI right you have to just call the API so in that particular case HTTP basic authentication will be used okay that is something that will be used okay and here what we are doing is we are returning the HTTP build object all right so this is the default configuration and as you can see this is a be over here okay so what we are going to do is we are going to enable HTTP basic authentication only we don't need form authentication let's take a look at what basic authentication looks like okay so what I'm going to do is we need to write our own filter because we don't want the default security filter okay we wish to use our own filter because we are now customizing it right so what I'm going to do is I'm simply going to copy this code here like this okay and here if you scroll up you'll see few annotations like configuration this is a configuration thing okay what I'll do is I'll come over here in my project okay here I'm going to see security config something like this okay and I'll close this and here what we need to do is we need to paste the code that we have copied okay so I'll paste this here the moment you past this you'll see all the inputs also coming over here okay this is done now what we need to do is we need to mark this thing as a b okay because if you read over here if the user specifies their own security filter chain Bean so you need to like create your own security filter chain Bean so this is our Bean okay and we need to have a couple of annotations on this class as well so first is you need to say that this is a configuration class because you are specifying security configurations over here Custom Security configuration so you need to treat this as a configuration class and then over here you're going to say enable web security okay this is another annotation that you will be making use of okay and uh this annotation is being used to spef spe ify that here you have like security being enabled over here okay and what I will do is let us run this and let us see what the behavior looks like or wait a minute let me cancel this I said we are going to enable basic authentication only right so we don't need this line form authentication okay so I'll just disable this let us see what basic authentication looks like okay and this is our Custom Security config this is done if you come over here here let me go to Hello here you can see the form is gone now and you are now being shown an alert box okay you're now being shown an alert box and you can enter your same credentials admin and demo atate 1 23 and you can say sign in and you should be able to sign in you can see over here you can log out let us see you cannot there is no way for you to log out okay so what you will have to do is you'll have to close this session here you'll have to restart the browser here something like this and you'll have to go over here again and you'll be presented with this okay so what I would do is I'll go over to inspect over here and you can see everything in the network tab so I'll refresh you can say admin and here you can say demo atate 1 123 you're seeing hello over here you can see and uh this is done over here right so you can see how this particular thing worked okay and these are the headers you can even see a header over here called authorization okay this is something that will be understanding but for now yes this is working perfectly fine and what we have done is we have created our own Custom Security filter over here let me explain this code to you all line by line okay so the first line is is about an annotation configuration so this annotation tells spring that this class provides configuration to the application context okay we have enable web security this annotation tells spring boot to enable web security features in the application okay and uh it gives us the liberty where in using this particular class we are able to customize the security configuration so that is what this annotation does we have bean annotation to mark this as Bean okay and uh this annotation will make sure that this is available as a p provider okay so if you go inside okay here you have this first line okay which says that any object or sorry not any object any request that the application gets is authenticated by default so we have not modified this this is the default behavior and this is what you are also taking it Forward okay then you have this line when you saying HTTP basic with defaults and this line configures basic authentication and it specifies that Spring Security should use HTTP basic authentication with default settings okay and then we are returning the you can see over here we are returning the HTTP security object so if you over on this you should see the object over here okay one second so security filter chain is is the object type so we are returning the object of type security filter chain as you can see over here okay so this is what the code looks like and here is how you can customize the spring boot security all right uh you can see how easy it was we just took the default mechanism and we modified the code upit to enable basic authentication into our application so now it's time that we talk about form based versus based basic authentication all right so right now we have basic authentication enabled and if you like access the URL you're going to see this output so the first difference is between basic and form is if you try to access login over here okay you're not going to see the default login page over here because we have said goodbye to form based authentication right so there's no by default form that is incorporated okay there is no log out as well okay so there's no okay there's no log out over here no log out you'll get an error so how do you log out so if you want to access the API you can access okay and if I want to log out I have to just close the session okay I close the browser I restart the browser and I try to access the browser again I'll be presented with the login form or not the login form I should say login popup over here which is like an in browser alert over here all right now let us take a look at uh basic authentication okay so I'll say cancel over here okay I'll go to inspect and I'll go to network over here and we'll observe what happens when you login via a basic authentication method so I'll say refresh you'll be asked for credentials I'll enter my credentials okay the moment I enter I get hello over here okay so this is the request that went through and you can see this is the request I get 200 okay if you scroll down over here okay you have some headers being set over here security related you scroll over here you have the authorization information being encoded in the header you can see this encoding over here okay it says authorization coolon basic and then you have some encrypted value over here so this is the authorization information that is going through the request over here right then you have some cookie related information okay so what happens is you will be seeing j session ID cookie that is being set in the browser so if you click on the cookie tab you see J session ID and it has this value so this is the cookie that is being set because our server is making use of cookies for session management okay and that is why you seeing this over here okay and uh yeah that is what the information you should know about basic authentication okay so you're making use of authorization headers over here first thing okay there are no inbuilt forms like you saw okay everything works on the basis of alert popups in the browser and it is making use of J session ID as of now which you have an option to disable via the source code but for now it is being tracked using cookies the session is being managed using cookies okay now let us see the form based authentication so if I like disable the basic one here if I enable the form based and if I restart this okay so the application has restarted if you come over here okay let me come over here I'll keep the headers selected and uh let me go to hello again so you'll be presented with the login form again okay and uh what you need to do is I'll just clear everything off okay so this is the clear button and I need to say admin and I need to enter my password which is demo atate 123 I log in okay log is done now you'll see login over here okay you can see headers over here okay this is the response headers okay you can see the cookie information over here so this is also making use of J session ID cookie okay and uh J session ID is being sent back and forth between the client and server with each request to identify the user session over here okay so you can see that happen you have the authorization information over here as well okay and you have the explicit cookie tab like the request tab cookie and also the response cookie okay and that is what you are seeing also you're seeing the payload over here okay so this is how the information is being sent when you do the form based authentication so you have the username and password being sent like this okay and you have the csrf ID over here like this okay now when you are making use of form based Authentication you are submitting credentials by an HTTP or or by an HTML form not HTTP form it's an HTML form and once the user is authenticated there is a session being maintained between the client and the server okay but there was no payload tab when we were making use of basic authentication okay so this is something that you need to know okay so that's the difference between form and basic authentication so what I would do is I would switch over to the basic authentication again I'll restart the server okay and uh if you take a look over here in the basic authentication okay so let me head over here okay and let me open the network tab at least okay so if I go to network tab you'll see even though we are making use of the basic authentication we still have access to the cookies tab over here right which means cookies being maintained so which means this is not a stateless API yet so you can disable the statefulness and you can make your API stateless by just adding a line of code over here okay so what I can do over here is I can come over here and uh here just before this line here okay so I can add a code over here I can say HTTP dot session management all right and I'm going to say say session over here and uh I'm going to say over here session dot session creation policy so I'll say session creation policy over here and here we have an option okay so let me take this to new line something like this and here session one second so this has to be Capital session creation policy and you can see over here session creation policy always never if required and stateless so select stateless from here okay so this will make sure that our requests are now stateless so I'll rerun this okay and let us see what this looks like okay so if you come over here you have the cookies tab cookie being set if you refresh let me see okay we are still getting the cookies right now I've restarted the app let me like clu the browser and open it again okay so I'll come over here I'll say admin or wait a minute let me open the network tab first here okay and if I head over to here I'll say admin demo atate 1 23 okay let us see if we have cookie we don't have cookies now you can see the cookies tab itself is gone and we don't see anything like cookies so this is now completely stateless we have made our apis stateless okay and we have done this with the help of single line of code okay we have just added one line which says that hey I want my session over here so you can see the session management should be sightless over here and this has got us a sightless working API all right so I hope this was useful normally when you are building a rest API you would not be accessing the apis like this from the browser right so this is not how would you access your API so this is get request and that is why we are able to access it right from the web browser but normally for post requests browsers won't work and usually when you're doing API development you make use of tools such as Postman right so what I'm going to do is I'm going to switch over to postman over here I have it installed already I've created a new workspace as well over here okay and a new collection called security okay so I'll just rename this instead of security I'll call this security course over here okay so what we are going to do is we are going to see how this request behaves in Postman okay so I'm going to add a new request over here and I'm going to say or instead of saying let me just copy this request here okay and I'll come over here I'll paste it now if you send this request you're of course going to get 401 unauthorized this is obviously because we are not authenticating it now now the question is how do you pass authentication information from postmen so for that you need to head over to or over here and you need to click over here on the drop- down and you need to select basic or over here okay now if I minimize this you are going to be shown a form over here okay now what is this form this form is the form where you can enter the username and password so I'll enter my username as admin and password as demo at1 23 okay and with this information if I say send over here you are going to see 200 okay all right and this is working absolutely fine now all right so this is how you can get uh this particular thing work in Postman if you want to see how your request was sent you can click on Console over here at the bottom the moment I click on Console I'll see two requests now these are the two requests that I triggered the first one you'll see is 401 which means that this was the one that failed initially okay and if you go to the second one this was the one that passed okay it's 200 okay and here you will see the headers so this is how the authentication information is being passed so what happens is I'll tell you here in the authorization you are entering your username and password over here right so this is a username and password that you are entering over here now this username and password is being converted into this authorization header over here and the authentication information is encoded in this authorization header okay and uh it is being encoded in B 64 okay so what b 64 is so let me explain what base 64 is so if I open notepad here base 64 is a format where the username and password is encoded in this format so the format is it's user colon password okay or username colon password so in our case our username is what is our username admin colon demo at 1 23 something like this this is what our username and password is right so it is being sent in this particular form and I'll show it to you so I'll copy this hashed string over here encoded string I'll copy this we can go over to browser and on Google you can search for B 64 decode over here okay so this is a base 64 encoder decoder you'll find a lot of Base 64 encoder decoder you can select on any one okay and if you paste it over here the copied string and if I say decode you'll see admin colon demo at1 123 right so this is what the decoding is right so you can see this particular string over here that you saw is nothing but the base 64 version of our username and password okay so it's being encoded over here to transform it into some other form rather than hardcoding it in a raw way okay so this is about uh the base 64 thing and how you can get authentication work in Postman okay and remember you have to select basic or from over here Hello everybody welcome back to this video and this series on Spring Security so if you're new to this Channel or if you're watching this video for the first time let me tell you like this video is a part of a entire series that we are doing on Spring Security where we are learning Spring Security right from scratch and uh you can find the playlist in the description below okay so be sure to access the playlist and also subscribe to this Channel and turn on the Bell notification icon that's how you can stay updated and motivated me to upload more such free content on this platform okay so talking about this video in this video we are going to explore something called as inmemory authentication so we have come very far with Spring Security okay or we have a working secure API right now which is asking for user authentication okay and uh what we have done I would also like to mention is limited okay in a way like we have only one user right now in our system but in real world production grid applications you will have multiple users who would want to access your system and you might want to give or create multiple usernames and passwords okay and uh we are going to take a step in that direction so we are going to see how you can create multiple users along with unique passwords in memory okay so we are not making use of a persistent system like a database yet okay it's still all going to be in memory don't worry we are going to transition to databases as well but for this video we are going to stick to inmemory authentication where we create users and passwords in memory we'll assign them roles as well okay and and yeah you going to see multiple user based authentication that's what we are going to cover so we'll take we'll go step by step okay I won't overwhelm you with a lot of stuff but in this video this is what we are going to cover and yes we are going to cover this in in a very Hands-On way okay everything is Hands-On so be sure to stick till the very end because there is a lot of stuff that's packed in okay and also if you are watching this video until now okay you should comment below and let me know who you are where are you joining from what's your name what are you doing right now and what sort of videos you want to see on this particular Channel okay I have a list of courses that I wish to upload on this channel and uh you your request or your comments will influence that list so you have an opportunity to request something a request a course or something that you would like to see on this channel okay and if many people request the same thing I normally create a course on that particular topic okay so yeah be sure to leave a comment and let me know okay so I go through my comment personally by the way let me tell you that as well I read everything that you all are posting on my videos okay so yeah I won't take much time without a further Ado let's Jump Right In and let's get started so right now we are making use of basic authentication where we have one user configured in our application using which we are able to access the apis all right now one user might not be enough your security requirements would be complex like in future you might need to have rules so basically on the basis of different roles that is being assigned to the users the users should be able to access and perform different actions in your system right and also you might have different users that you want to keep track of here as of now we have only one user okay so this method that we are using right now is very limited okay we have one user who is hardcoded okay and uh also like you can add role over here but things can go beyond the capabilities of the basic authentication over here okay so what I would do is I'll will'll do away with basic authentication and we'll talk about something called as inmemory authentication so if you take a look at the diagram over here right here you can see we have the user details stored in the database and user details service is fetching in the data from the database so typically what happens is you have a database wherein you have a table called users and uh normally whenever user name and password is to be validated it is validated against that particular table but right now we have not configured the database so what we are going to do is we are going to make use of inmemory users so we are going to create users within the memory okay they won't persist so there would be users that exist within the memory we'll configure our application to work with such in memory users and this is known as inmemory authentication okay so let us switch over so this entire flow will work as it is okay but we won't have the database this is something that we'll bring in a bit later okay so what I would do is I will switch over to Security config over here okay and to configure inmemory authentication what we would be doing is we would be adding a bean over here okay so let me add a bean I'm going to say Bean here okay and this Bean is going to be public using user details service so this is what it's going to return so you can see user details service which is a part of spring framework security core user details okay and I'm going to call user details service over here okay and uh here I'm going to return new in memory user details manager over here okay and this is going to have the credential of users so for example it is going to have user one it will have admin credentials and so on okay so right now these are not defined we'll be defining them but if you head over to in memory user details manager okay if you scroll up over here okay you would see this is a class okay and it is a implementation of you can see over here user details manager and user details password service so if you go over here user details manager you can see it extends user details service over here okay so this is an interface over here okay and if you come over here we are returning user details service so in memory user details manager is an implementation of user details service okay and uh what inmemory user detail manager does is it manages user details in the memory and hence its name is in memory user details managers if you have any documentation over here okay so you can see over here non-persistent implementation of user details manager which is backed by inmemory map and it is mainly intented for testing and demonstration purpose where a full-blown persistence system isn't required okay and this is the entire class over here as you can see okay there are several methods one of the methods over here is uh user so if you go over here okay one second let me go down there will be a method which is with okay so not method but a Constructor over here okay so this is a Constructor which accepts the type of user details over here so you can pass in the user details over here okay and you need to First create the user details object you pass in the user details over here and those users will be created with the help of this method create user okay so what we would do is here we are passing the user details okay you can see this is a Constructor we are calling and we are passing in the user details so these two objects have to be of type user details okay so what I need to do here is I'll come over here I'll say user details okay you can see this is also an inbuilt class that we are making use of okay so if you go over here it's an interface actually okay and what it does is you can see it provides the core user information over here okay so what I would do is I would come over here I'll say user one over here I'll say user Dot and I'll say with user details over here okay now what we will do over here is I'll say user is user one something like this I'll say password so what is the password I can set password as password one over here just for demonstration purposes okay I'll go over here I'll add the rules as well so I'll add the rule as normal user and here I'll say dot build okay so I'm making use of build over here and what this is going to do is it is going to give me the object of user details type okay so what we are doing over here is we are actually constructing a object of user details type and we have all these details now we getting a red mark over here if you overover on this okay it you'll see that uh it's a red mark So required type is user details okay but provided string okay so what I need to do here is I need to add a prefix I need to say okay okay I realized like I'm using a different method here so it was not with user details it was with username this is the one okay so we are creating a user with this username this password this role and build over here okay now I'll explain you what is noop over here okay so if I remove this okay it still works but what happens is normally you would encode your passwords okay so passwords are passwords and usernames are not stored this way so not username but here we have to add it to password okay so passwords are not stored this way in a hardcoded text format in memory or in the database so you have something called as a prefix so you have to add this prefix n o o p which tells uh spring that hey this particular password should be saved as plain text okay I'll tell you that this is not a production grade practice we will be learning about password encoders and we'll understand how you can encode the passwords so that they cannot be read by anyone else okay but for now we are making use of noop over here until we understand how you can make use of password encoders all right so this is what it is what I will do is I have this user created over here okay I can create one more user if I want to okay or uh let me add one more user I'll add one more okay I can say admin over here okay and this one I can give admin here okay and uh I can call this as admin here and this one can be admin pass something like this all right so two users have been created and uh now let me run the application so let us run the application and let us see how this works okay so the application is up and running I'll just close this if you hit refresh over here you're being asked for password you can see user one and here you can see password one password one and you can see sign in and you can see this works over here okay even with the other user it will work okay and even it will work from the postman so if I say admin and I if I say admin pass over here and if I say send you should see 200 okay appear here over here okay so this absolutely works and this is working perfectly fine all right so what we have done is we have made use of inmemory authentication to create multiple users and we are managing this in the memory okay so the information is right now not persistent in the database okay we are straight away making use of memory to create and store the user information you can create as many users as you want okay just remember in memory user details manager will need an object of type user details like we saw in the interface or like we saw in its implementation over there okay so this is a class and we saw it in the implementation and here you can construct the user details object in this way all right and we're making use of NOP over here which is not a good production practice but since we are learning we are using it and we'll do over with this soon all right so this is about how you can manage your users in memory welcome to this video in this video we are going to discuss role based authentication with Spring Security if you new to this Channel and if you're watching my video for the first time I would highly recommend that you check out the entire playlist the link for the entire playlist can be found in the description of this video and it's a playlist about Spring Security where we cover Spring Security right from scratch from very Basics till the very Advanced features such as gwd so talking about this video in this video we are going to cover role based authentication are you excited immediately hit the like button and show some love people show some support over here also if you are new to this Channel and if you are liking my work if you think uh that uh this content is good then you should immediately subscribe and hit the Bell notification icon over there okay uh this will enable us to stay connected and you would be updated with all the future updates that I'm posting in this series okay so we are talking about role-based authentication and uh it's a very common feature normally wherein if you're building an production grid application you will have some parts of your application accessible to certain users and then other parts of the application would be accessible to some other kinds of users and then some parts of the application would be open for all right so that's what role-based authentication is for example if you're building an e-commerce website you might have an administrator or admin who would be allowed to perform operations such as delete create products he would be allowed to change the price of any particular product item or something like that run discounts and uh any normal user who is not an administrator he can only like view the product information he can probably do some other reading stuff he cannot modify uh something which he's not allowed to okay so that's what role-based authentication is so once the user is authenticated okay you need to essentially assess as to what he's allowed to do and on the basis of that whatever ever he's trying to do you grant him access to that action okay so that is what role-based authentication is all about and we are going to learn exactly how you can do that in your spring good application so it's going to be very exciting we are going to cover some new annotations and in the process we are going to learn a lot I'm so excited as to and I'm so happy as well as to how far we have come with this entire playlist okay we started from the very Basics very Basics like how to add Spring Security into our application and right now we are talking about role-based authentication and I'm going to make it really a cake walk for you okay and if you have not liked like the video okay if you have not liked after hearing this like what we are going to cover you should absolutely like and even subscribe okay because I normally see uh the analytics over here the analytics dashboard most of my viewers like majority of the views I get from uh people who have not subscribed to my channel I don't know why and there is a good uh repeat rate as well like people who watch my videos come back again to uh watch my videos again so of course they're finding value that's why they're coming back but uh yeah I don't know why people are not subscribing so you should uh absolutely hit the Subscribe button okay I won't take much time but one last thing I would want you all to comment below as well and introduce yourself as to who you are where you are joining in from what you do currently and what sort of videos you want to see on this channel okay and uh I normally check the comments of my viewers to like plan out the next set of videos okay so you have a chance to influence that list people comment okay so I won't take much time without a further Ado let's Jump Right In right now how our API is working is we have this endpoint which is secured and anyone in our application like any user can access this endpoint so I can access it using this admin credentials from here I can even access it using the user credentials so I can say user one and password one okay this is good but there will be scenarios in your application like if you're building a complex production create application it's common to have a functionality where you want to control access to different parts of your application based on the roles assigned to the users for example you might only want to allow administrators to delete any data or update anything while regular users can only view the data right there might be teams in the organization who is using your product and they might want to have customer support specialist for example want to only view the data and they want to hide the phone numbers from the customer support specialist right and uh administrators like the uh store managers or someone like that or someone at the admin level can only edit and modify the data view the phone numbers and all okay so you could face this scenario where in certain apis are restricted to people with certain roles okay and this is often implemented with the help of annotations to make it easy to manage okay and spring makes it really easy what we are going to do is we are going to add one more API over here okay and we are going to talk about how we can get role based access okay so what I'm going to do is I'm going to add a couple of more apis over here okay I'm going to say say hello here and here you can say user endpoint something like this okay and this can be slash user here and I can say hello and I can say user something like this okay and then I can even have the admin end points so I can just copy this come down and this can be the admin end point right and this can be admin something like this right and here instead of user I can say hello admin now if I run this everybody is going to be able to access this okay so if I say hello and if I say user for example over here okay so this is going to work admin is also going to work right so right now we are signing in from user credentials and we are also able to access this admin API right but let's say I want to restrict the access level of these apis to users with certain roles okay so I can make use of annotations over here so first thing what I need to do is I'll add a annotation here okay I'll say pre-authorized here okay so by using this anation you are telling Spring Security that hey I want only users with a specific role to access this particular thing okay so what pre-authorize will do is pre-authorize is used to check authorization before executing a method okay and you can specify conditions that need to be true for the method to execute okay so for example here I can specify a condition I can say has role and I can and say over here okay user something like this okay so this is The pre-authorized annotation and for this to work what I should also do is I should go to my security config here and I should enable method security okay so if I add this annotation okay this thing will start working all right so let me run this all right right so what we are doing is we want only user to access the user endpoint okay and if I come over here and if I say admin and here if I say admin CL he can access the admin API but if I go to user let us see if this works you can see 500 internal server error okay interesting this is not what we expected wait a minute so if I go over here now if you see the error over here cannot find terminating like code for the string so here we missed this closing code Okay small mistake but if I rerun the application okay this should work as expected no issues as such so if I come over here and if I try to access this you should see 403 Forbidden okay now we are not getting 41 on authorized over here okay because if you're logging in with the credentials that are ized okay and those credentials do not include the permission to access a specific resource the Spring Security will issue a 43 forbidden okay this is because authentication is successful so what this means is the request is authenticated but accessing this resource is forbidden okay so Spring Security understands the request understands the credentials but it is not able to give you access to this particular thing okay and it says the request was a legal request but the server is refusing to respond to it okay and this is unlike 401 because authenticating will make no difference okay so I hope this makes sense and we are not able to or we are not allowed to access this resource but we can access hello over here so this would work as it is okay so you can see how this is getting uh to work over here okay so here hello is working but we have just blocked the access to this particular endpoint over here okay and we have blocked it for user okay so here you can update this for admin so let's say only admin can access this and no one else so if you try to log in over here with the help of users you are going to get an error okay so here if I say admin okay and if I say send you'll see this works and if I say user one and password one over here okay so if I say password one and if you say submit you'll get 43 forbidden again because this is the admin end point okay so this is how you can enable role based access so it's it becomes pretty easy when it comes to Spring boot when uh enabling role base access and this is because of the wonderful annotations that you get access to okay now there is one more annotation in fact that I should talk about which is post authorized so here what happens is if you see this code pre-authorized is running before executing the method there is post authorized which is used to enforce security after method has executed okay and that allows you to take decisions based on the result of the method okay so there is post authorized as well okay but we are using pre-authorized over here because we want to block the execution of this method and uh we want to allow this with a specific role only okay and if your question is where we are setting this role so we are setting this role in security config over here so if you come over here you have user admin these are the rules that you are setting over here okay so if you switch the rules the behavior will also be switched okay so this is how you can Implement role based Security in your apis so I hope this was useful welcome people and in this particular video and in this particular Series in fact uh we are taking one step further with this video and we are going to cover H2 database with Spring Security okay so we are going to understand how you can make use of H2 database with Spring Security uh it's not that straightforward of course you can add H2 database but how would you access H2 console and all so all of that we are going to see what all issues we face normally when you're trying to make use of this amazing inmemory database okay so if you're new to this Channel and if you have not watched my previous video or any of my videos so I would like to tell you that this video is a part of a complete spring security series that I'm doing here and the link for the series or the playlist you'll find in the description below okay and uh be sure to check out earlier videos If you want to get some context otherwise it's completely fine you can watch this video as well okay uh but yeah this series is all about Spring Security where we cover Spring Security right from Basics okay like how can you add Spring Security into your project literally that we are covering and then we go up to the advanced stuff okay which is like jwd authentication database authentication all of that okay so yeah that's about this video that's about the playlist in fact and about this video we are going to work with H2 database like I mentioned okay so we'll be H2 database and this is a step towards gdbc authentication or database backed authentication okay so right now the authentication is in memory which is pretty much in memory you know uh so we need our user details to persist into the database right so we need to do that and uh yeah it's a step forward so if you like the video I would highly encourage you all to hit that like button right now okay and show some support support uh to this particular series that I'm doing and also hit the Subscribe button and turn on the Bell notification ion that's really important to stay connected and also to uh get the updates to you all okay because I'm posting a lot of content now I'm working on a lot of content that's coming in and if you wish to stay updated you should subscribe and even turn on the Bell notification icon so yeah that's about uh uh this also be sure to com and introduce yourself as to what you're doing where you are from and also if you have any video requests or any sort of course you want to see on this channel you should post that over there all right so without a further Ado let's Jump Right In and let's start working with H2 database and let's see what happens if you add it uh with a project that is configured to work with Spring Security so far we have an inmemory authentication in place where we are authenticating users with the help of the user information that is being managed in memory all right now we need to configure H2 database so that we can move this information that we are managing in memory as of now to a database right so we'll begin the configuration for H2 database and for that we'll head over to our favorite website which is spring initializer I'll make sure I select Maven here I'll head over to dependencies and I'll select a couple of dependencies over here which is H2 and GPA okay and I'll go to explore and uh we'll scroll down over here and we'll copy these two dependencies that we need okay so these are the two dependencies that we will add to our project which is pom.xml all right we'll keep rest of the things as it is and we'll hit Maven refresh okay so what is happening over here is we got the dependencies now what we need to do is we need to enable the console over here right and to enable console we'll add just a couple of properties over here okay so I'll say spring dot I'll say H2 do console do enabled is equal to I'll say true over here and I'll also add the data source so I'll say spring data source. URL over here is equal to jdbc colon H2 coolon mem Coolin test okay and I'll reun the application okay now let us see what the behavior is when you try to access H2 console okay so if you come over here if you head over to this URL Local Host 880 H2 console you'll be presented with a login alert okay of course because we have basic authentication enabled for all the endpoints and H2 console is a part of our application so I can say user one and I can enter let's say password one over here I'll be taken to this page here I'll say connect I'm being presented with this again okay so I'll say user one and password one so this H2 console page okay again this popup comes so this H2 console page is already authenticated right H2 has its own authentication form from where it is authenticating the users what we can do is if we want to disable uh the login on that particular page the Spring Security login you have an option to do that okay and for that we can switch over here okay and we'll head over to our config here I'll scroll up and here we are saying request. any request right so what I would do is I would take this any request to the next line and I would also add one more line over here tot I'll say request matches okay so I'll try to match the request with a pattern in the URL okay so you can see string patterns is what you can pass in so I'll say SL H2 hyphen console over here and then I'll have two stars over here okay and if it match matches this I'll say permit all okay so if the request that I'm getting if it's matching this URL pattern then I'm permitting without Spring Security authentication and apart from this any request I'm marking it as authenticated so I'll rerun this let us see what the things look like okay and uh if you come over here let me go to H2 console now okay so you can see we were not asked for any sort of authentication now and if I say connect now okay we are being asked for this authentication still okay and uh let me see what is the reason over here okay so we are seeing request matcher and do permit all okay which is absolutely fine okay so I just restarted the application and uh I tried testing it and it seemed to be working now so if I connect you see that I'm not getting that alert popup okay but I'm getting something else so you are seeing Over Here Local Host refuse to connect okay but if you're getting the alert popup again and again despite disabling this from request matches over here okay then restart your application and even like close the browser and start it again in incognito mode so there there's a possibility that some session information must be stored in the cashier or something and that is the reason why it's showing you authentication popups again and again okay but yeah since that is gone now you can see over here we have a new issue okay here nothing is loading so if you right click and if you say inspect over here okay you'll see that everything is a frame over here you can see this is a frame this is a frame this is a frame right everything is frame and by default the frames are disabled okay so you need to enable this for this to work okay and how can you enable this there is a configuration for that as well okay so you can over here I can say HTTP do headers and I can say headers I'll have Lambda over here headers dot I'll say frame options okay and uh let me take this to new line frame options and uh I can say frame options and I'll say over here frame options do same origin something like this so this is a line of code that you we need to add all right what we are doing is for HTTP headers we are saying headers and within headers for frame options we are allowing the frame options from the same origin so once you use this okay there is also a suggestion over here if you over on this you can replace Lambda with a method reference this is also doable okay and uh if you refresh this okay you can restart the application and now if you refresh Let me refresh okay so I'll come over here again and I'll say connect okay it's asking me for the popup again okay so this is because probably we have the csrf enabled and we have not disabled it okay so what I would do over here is right now I will come over here okay and I'll have HTTP do csrf and I'll see csrf and like this csrf do disabled okay so this is disabled and I can run this again let us see what the output looks like this is working and let me like hit refresh connect and you can see this works now okay so there's no issue as such okay you can like log out from here disconnect test connection and all the end points all the URLs will work starting from H2 console Okay so so what we have done over here is okay first of all we have like allowed all the requests coming into H2 console we have allowed them bypass the security okay we have also enabled the frames over here from the same origin okay so we have allowed the frames for H2 console and then we disabled the csrf to get it to work okay all right so with these settings we have the H2 console enabled you can over on this and you can replace Lambda with a method reference okay and I can run this again okay so if you come over here and if you refresh and if you say test connection connect you can see that it's working absolutely fine okay so what we can do is we can get this information now into H2 database and we don't need to make use of in memory user details manager all right so I hope uh this was useful hey there welcome back everybody and in this particular video we are going to talk about database backed authentication with Spring Security yes so we are going to cover how you can actually secure your application using a database so using a database meaning you can store all your user credentials information their roles and everything in a database right so there is a persistent storage in the hindsight that's uh giving your user information okay so far what we have done is we have inmemory authentication and uh our users details are being stored in memory okay but all modern day application will have databases and databases are pretty common these days right so yeah it's important that we see the database part of Spring Security as well and that's what we are going to cover from scratch step by step okay I'm also going to explain you things like hashing and password encoding now when it comes to database authentication it's important that you don't store your passwords like your user passwords in a plain text format right otherwise anyone can see it or if your database gets hacked uh hackers can see it or developers can see it so it's best to store in such a way that they are encrypted and in in non-readable format right so so that's where we are going to make use of hashing and password encoding we are going to make use of inbuilt password encoders and we are going to see how they can secure your application even more okay we're going to understand the concepts of hashing and all as well so it's going to be a very useful video if you're watching my video for the first time or if you're new to this channel I would highly encourage you to check out the description for the link to the earlier videos uh so the description has the link to the entire playlist okay so you can get access to the earlier videos and the video afterwards okay so that's going to help you get some context as to what we are doing so just to tell you we are covering Spring Security from scratch uh from Basics to the advanced level okay so be sure to take the benefit of the playlist also if you haven't liked this video yet be sure to hit the like button and also you should subscribe to my channel and turn on the Bell notification icon because that is going to motivate me to bring more such amazing free content for you all so number of likes subscribes comments all these metrics impact my ability to bring such content on this platform okay so be sure to support me and uh get benefit of the content that I'm posting here also I would love to know more about you like who you are where you're joining from uh what do you do currently what sort of videos you would want to see on this channel so be sure to leave all this information in the comment below okay I'll be reading your comments personally sure so yeah that's about the video there is a lot of information packed in there do watch it till the very end let's Jump Right In so far what is happening is we are making use of inmemory user details manager to create users in memory which means that these users are not getting created in the tdps we already have a data source or a database configured with our application and right now we are making use of of H2 database right so it's time that we start moving these users instead of inmemory to the data source or the database that we have configured so tomorrow it might be like you might have instead of H2 you might have postris SQL or MySQL or any other database configured and what would happen is with the changes that we are going to do you would be able to create users over there all right so here in the security config what we we need to do is we need to make use of something called as jdbc user details manager okay so here I'll just type in okay jdpc and you can say user details manager you can see like this is also a user manager okay it's a if you go over here you can see over here it's a user detail manager it's a implementation of the same okay and if you go over here in memory detail manager it is also a implementation of this okay user details manager but the purpose is different this is used to create users in memory this is used to create users in a database okay so what we are going to do is we are going to make use of jdbc user details manager and I'm going to create an object over here so I'm going to say user details manager is equal to new jdbc user details manager okay now what happens is this jdbc user details manager needs a data source so if you go to the class here you will see so this is a default Constructor with no uh parameters but it also accepts parameters this is another Constructor where you can pass in a data source and data source is nothing but actually its source of data okay so wherever you are uh storing the data in your application and right now in our application we have a data source configured so here if you see here we have these properties and and these properties indicate that there is a data source configured called H2 okay which is H2 database so what I would do is I would make use of data source over here okay so I'll say data source data source and I'll get this autowired where do I get this uh bean from so actually if I specify something like this what I'm saying is uh that inject the dependency called data source into this particular object okay and how does this happen so what would happen is spring boot will automatically make use of Auto configuration to set up a data source Bean for us and you will ask hey how spring boot would automatically do this so it has all the configurations of your project okay it knows that in pom.xml you are making use of H2 database GPA okay and in application. properties you are specifying these two properties So based on this configuration that you have provided to Spring boot it will automatically have a data source Bean available for you and it will automatically set up this bean and it will auto wire over here because here you are asking for it okay so we'll have this we don't need to Define this because this is automatically taken care by whom like I said spring boo okay so I have this Bean created here and what I would do is I would come over here to user details manager and I would pass in this object okay now this is done all right and uh here instead of sending this to inmemory user details manager what I would do is here I would say user details manager dot create user you can see this create user uh method here and I can say over here user one I'll duplicate this I'll say create user as admin as well okay this is done and here I can say return user details manager something like this so this is done okay and this is taken care of okay so what we have done is we have just replaced the implementation of inmemory user details manager with the help of jdbc user details manager that is it and this will make sure that our data is being stored in the database okay there are a few things still pending but let me run this and show this to you okay so it will throw an exception or an error I should warn you in advance but we'll see that error and we'll learn something okay so you get an error so I'm purposely generating this error you can see this error now it's telling you that table users is not found okay if you scroll up okay is it the same error here okay user details you can see users not found so it's trying to run this and it's getting an error okay users not found here it's all about the schema being non-existent over here okay so you can see if you take a look at if you read errors this quer is again failing so we got same error twice because we are trying to create two users okay so let me tell you in order to save details of user into the database you first need a schema now what is a schema schema is nothing but a structure of the dat database okay like you need some tables already created inside which you are going to store the user details right and here what we are doing is we're making use of user details that is inbuilt right so we can make use of some default schema that exist with spring boot so what we are going to do is we are going to head over to GitHub okay so for that we are going to head over to browser and I'm going to search for spring security GitHub okay so you'll find the official source code of Spring Security on GitHub over here under spring projects okay and here we can search for users. dtl okay if you search for this you should see this location core SRC main resources or spring framework security so under security it's under core user details gdbc and users dll okay so if you come over here and if you go to this file user details okay you'll find or do springframework security okay so you'll find over here aug. springframework security then core user details okay so you can see core user details okay so this is a path okay and within core user details it will go further calling jdbc and users ddl so you will go to this particular file let's go to this file and you can see this file with some uh schema over here like the schema definition okay so this is the schema definition that we need in order to uh like have the tables and everything created where our users can be stored okay and uh what we can do is I'll just copy this like just copy this thing over here just come back to your project and just go over here so what we need to do is we need to make sure that uh H2 picks up this particular schema and when the application starts it is created automatically okay so what I'm going to do is I'm going to create a new file over here which is going to be schema.sql file under resources and here I'm going to paste that schema that I copied okay so this is an SQL file okay and uh this is saved okay yeah this is done and uh yeah what would happen is I'll tell you so since you're making use of H2 which is an inmemory database the data gets cleared and hence we need to get the table created when the application starts so if you're using some other type of database like MySQL and po SQL which are nonmemory database then in that case the schema will persist okay so in that case what you can do is you can copy these SQL commands and you can run it in the respective tables or respective database over there but for this what we need to do is for every application start we need to make sure that this schema is loaded into the database okay so to load an SQL file on application start in springboard application especially for setting up security or initializing any sort of database table you can make use of spring boots automatic schema initialization feature and this feature automatically runs SQL script during the startup which is particularly handy for creating schemas like this if you want to insert any default data you can do that or you can configure any sort of tables or anything for that and the process is you just need to create a schema.sql file under resources folder over here and it will automatically be picked up by springboot okay and since you're making use of everything default right we don't have our own own custom user details or our own user structure we can make use of default schema which exists with Spring Security and where did we get the schema from we got the schema from the official uh source code of Spring Security as I've shown you okay and what we will do is we'll run this code again let us run this code and let us see what happens so earlier we were getting an error now we are not getting an error as you can see okay so the error is gone and it indicates that schema has been created and to confirm what I would do is I would just head over to H2 database I'll connect and you can see two tables automatically appear over here one is users and one is authorities so if you take a look at this schema definition or the queries over here you're creating two tables okay now let me take you to the tables okay if I say select start from users you can see your users are also created isn't this amazing okay your users are also created you can clear this authorities you have some Authority as well so admin has the role of admin user has the role of user okay and this is something you like just got created with few changes in the code okay so you just added schema.sql and you updated this thing to work with user details manager okay and now you if you test your application it is going to work with these credentials okay so if you come over here okay and here if I say user one and password one here in the basic o okay and if I say send over here okay we got an error okay so I'm trying to access the admin API okay so I'm saying slash admin so let me head over to the controller okay so if you go to admin I can say slash user over here okay so if I say slash user here if I I say send you can see Hello user or if I go to Hello this should work okay this should work you can see perfectly working and it's amazing okay so so this is how you can move everything onto the database without making use of in memory stuff okay still we are making use of as database which is right now in memory but if you have any sort of database like a Amazon RDS for example remote datab base if you have a project that is making use of SQL if you have a project that is making use of my SQL POG SQL any sort of other database you can do things this way and in that case if it's not an in-memory database you don't need to add schema.sql like this okay we have added this because like I explained we making use of in-memory database because the data is being cleared on every application restart so you need to have schema that is loaded every time the application starts starts and this is the simplest way of setting things up okay so yeah this is working absolutely fine still you will be able to see the password in the database and this is not a good practice right now we're not making use of any encryption mechanism right now but but yeah we are getting there okay so we are taking one step at a time but uh but yeah things are working and from in memory we have graduated I should say graduated okay because we come so far so from in memory we have graduated to the database backed authentication and that's amazing pat yourself on the back so that's about uh the database authentication and I hope this was useful so now it's time that we talk about hashing and understand what it is so what is hashing now hashing is a process wherein if you have a message that needs to be transmitted okay or sent over the network then in that case you can hash the message which means that you can take it through a process where the message looks something different than the original message so I should say not something but it looks a lot different than the original message okay so if you come over here let's say as an example I have this message or a string I wish to send to the server over a network and uh the string is programming okay now I can make use of hashing and I can convert it into something called as this or something like this you can see the string this string looks very different than that of programming okay and this process of converting programming like a normal string to something that is that looks like encrypted message it's called hashing and this is what hashing is in simple terms okay so hashing it's oneway process okay and uh you can't turn it back into like the original string that you have okay and once the other side receives this string it will decrypt it and convert it into original message okay so this is what hashing is and how this hashing works is it involves making use of algorithms so there are different algorithms that exist and uh these algorithms are used to work on the message or the string whatever data you're willing to transmit and you get the hashed value okay now there is one such algorithm called bcrypt okay and it has a feature called salting which is something that we'll talk about but bcrypt is an algorithm that is often used and it is considered as secure algorithm wherein using bcrypt you can take a message you can pass it through the algorithm and you'll get a encrypted message okay and bcrypt is one of the most popular algorithm that is used widely okay so if you read about hashing online it's unlikely you won't come across a b Crypt okay and it has a process called salting okay so so let me tell you what is salting so salting helps increase security how so what happens is normally you would hash this particular value right so you have programming and you would hash it into something using a using the algorithm called bcrypt okay now what salting would do is it would add an additional layer of security which means like you have this string okay so you would add a random string over here randomly generated string or any data which is known as salt okay and then together these two will be used to convert into hashed value okay so password or so this can be a password as well or any sort of data okay normally passwords are encrypted okay that is where encryption is used hashing is used okay all of that so any sensitive data but if you're working on any sort of application like for example banking application where like a lot of stuff is Hash you may Hash a phone number okay of a user if you you are working on a security grid application something like that okay so programming here let's say is a password you would add some salt to it and then these two would be hashed together using pickt okay and uh this process is known as salting and uh this thing makes this algorithm even more secure okay because for every hashing that happens the salt changes so you cannot predict what the salt is the message can be same but if you add different salt the output would be different so here you have programming plus this salt which is xw z78 okay if you add some other salt over here like this okay then you get you'll get a different value so you can see over here this value is different okay that is how the entire process works of uh salting and uh this is how it processes the or this is how it makes sending data easy and in a secure way so if you are storing this let's say or if you're transmitting this data over a network you can transmit the hash value or if you're storing this password let's say programming is a password if you store this as a raw text it would be readable but if you hash it and encrypt it or something like this wherein you add salt and then you convert it into hash value then this is not readable right nobody can tell what your password is Right unless and until it's reverse engineered so this is much more secure way of storing passwords and uh this is even used to send some data which you don't want others to understand over a network okay so that's hashing and that's about bcrypt and the process of salting so I hope this was useful now it's time that we Implement encoding or encrypting into our application so right now I have this application up and running I have the users being created over here so these are the users that are being created into the database using jdbc user details manager now if you come over to the H2 database okay or H2 console I should say and if you log in to the H2 console and then if you query the users table here you will see users table uh having this data so the passwords are stored in this way now this is not actually a good way to store passwords because these passwords are readable and anyone who has access to the database can access this information which is not good so passwords need to be encrypted and there has to be one more layer of security that we need to add to as a best practice essentially and uh it it's not good to have passwords being stored in plain text format okay so what we are going to do is we are going to encode our passwords and uh we are going to make use of password encoder okay so here what we are going to do is we are going to say public and I'm going to make use of password encoder over here okay so if you overun this this is an interface if you go over here and uh this is a service interface for encoding password okay and you can see the most preferred implementation is bcrypt password encoder okay and uh yeah so that is what it is and if you see control B over here okay so I'm not getting okay here you can see password encoder okay bcrypt password encoder so if you press contrl B and here this is a class which is making use of password encoder and you can see over here this is an implementation of password encoder that uses bcrypt strong hashing function okay and uh yeah so this is what we are going to use over here so I'm going to say password encoder here and we can name the method whatever we need okay so I can say password encode over here okay because that's what people normally name it and I'm returning the instance of this interface of so the instance has to be of type password encoder okay okay and I'm going to say return new bcrypt encoder right bcrypt password encoder so I'm just getting it like this and what I also need to do is I need to mark this as a pin okay like so okay so this is done and we have an instance of password encoder okay now in future if you need to change the encoding algorithm you have to just come to this beIN and uh give that particular instance if you have your own algorithm so so this is inbuilt right this is inbuilt and within the security uh framework okay Spring Security over here you can see it's coming in from this package okay so this is pre-built but if you have your own algorithm or anything you can instantiate it over here all right and what we are going to do is we are going to make use of this when saving password okay so understand this here what we did is earlier on we made use of this prefix over here this prefix stands for noop okay and what is noop so the noop prefix that we are using in our password is a way to tell spring security password encoder that no encoding has been done okay and the password should be used as it is okay this is useful if you're building a demo application where you don't want to encode stuff okay but normally you would get rid of this okay and what we would do is we would say over here within this we would say password encoder and you'll say dot encode and within this you'll pass in the password that you wish to encode something like this okay this is done and I would copy this okay and I would come over here and I would paste it over here I would remove noop from here and I would add a closing bracket over here so this is done all right and uh let us see how this works okay so we'll rerun our application and we'll check how how the values are being stored in the database so we did not get any error you can see now if you come over here this is how we were seeing the password currently and if I say refresh and if I connect again and if I go to users table you can see this is the password now okay so yeah this is not readable now and anyone who is having access to the database cannot read what the password is okay so this is really helpful over here okay and uh you can imagine as to how so you must have seen a lot of applications doing this right and in spring or in Spring boot this is how you do it okay so you hardly like made use of inbuilt classes that you had inbuilt implementations and you just made use of a method over here to get this encoding done okay and this is automatically making use of salt and everything okay so you don't need to worry about that all right so yeah this is about password encoding I hope this was useful [Music] welcome to this video and in this particular video we are going to cover the most requested topic okay any guesses okay you must have read the video title but I'll tell you it's going to be about JWT yes JWT authentication with spring boot so a lot of my students reached out to me a lot of my viewers and they were like hey you should create a video on Spring Security you should create a video on jwd when are you doing it so I thought I'll bring it okay so that's what this video is going to be all about so we are going to cover JWT from scratch okay we're going to understand what JW is why it exists and what limitations of the current Security in our project GWT covers okay so all that stuff along with we are going to do a Hands-On implementation into our project that we are building and I'm going to explain you everything line by line so we are going to write our own custom FS or we are going to write JWT helpers and everything so all of this I'm going to cover in this video also if you're new to this channel then you should head over to description to check out the link to the entire playlist so this video is a part of a playlist on Spring Security where we cover Spring Security right from scratch to the advanced topics so be sure to take the benefit of the entire course over here okay that's about uh this video like I said this video is going to be about jwd and if that sounds exciting to you you should immediately hit the like button of this video and support my work also you should subscribe and turn on the Bell notification icons to to like stay updated of course from stay updated about what I'm posting next and all the updates I usually do on the channel okay so let me tell you there are some awesome courses awesome stuff packed in and I'm actually working on them right now so I'll be posting them soon once they are ready so be sure to subscribe and turn on the Bell notification icon okay so yeah that's what uh this video is going to be about and uh if you're watching this far then you should leave a comment introducing yourself who you are where are you joining from what do you do currently and uh what sort of videos you would like to see on this channel so I read all the comments that uh you all post and uh many people request a lot of courses and I have a list actually of the upcoming courses that I am supposed to work on for on this particular channel so that list is influenced by all your comments so if you're commenting and leaving a request then you are actually influencing that list so leaving a comment actually is an opportunity for you to influence the list of upcoming courses coming on this channel okay so be sure to leave a comment I would be happy to know you more okay so yeah without a further Ado let's Jump Right In and let's talk about gwd so now it's time that we start talking about GWT or chart authentication and before talking about this concept it's best that we talk about how things work without gwd and we'll understand uh how things work and and this will also help us clarify as to why this concept of gwd is needed so first point current authentication that we have essentially or normal authentication that we have in Spring boot like in memory or jdbc authentication it does not have advanced feature so one of the advanced feature like that I can talk about is expiration time okay so if you have authorized someone to your system there is no expiry of that authorization right so let's say if you want to expire the or if you want to take away the authorization like in a day or so there's no way to do that unless and until you customize it okay and uh without like the normal authentication or the normal hashing encryption that happens it can be decoded okay and uh there are ways to do that also if uh you want to have a secure system one way is I like to have your own token system system okay now what token system means is if you have a user let's say and uh that user has access to the system okay you have authorized that user so instead of asking for username password always what you would do is you would give that user a token it's like a ticket essentially and whenever that user presents that ticket you're going to give him access to your application features okay so that is what known as token system okay now if if you create something like a token system and why would you create token system so that he or she or the user does not have to share the username and password every time he tries to access a system so he'll share it once he'll get the token and then next time for any sort of API request he'll just present the token right and if you want to have advanced feature in this token system like the expiration time and all and also with a strong encryption or strong hashing then in that case you will have to implement a custom token system now the problem with custom token system is it's custom to you right like the world isn't a there's no standard in this okay and uh this is where jot comes into picture Okay so jot or JWT so I I'll refer to this as jwd okay jwd stands for Json web token and what is Json web token it's a sort of token mechanism using which you give authorization or you authorize your users as say ially okay and uh Json web tokens are open and Industry standards okay it's a industry standard and anyone can implement it in their application okay that's something that you need to understand let us talk about how GWT works so there are two uh things in the system like one is the user and another one is the server where your code resides now user is a user who wants to access your system right so what user would do is it will send a request along with uh like it will try to login it will send the request along with username and password to the server okay and this would be on a specific endpoint so for example a signin endpoint you can have a signin endpoint and user will send the username and password to the server what server will do is it will take a look at the username and password it will authenticate it using Spring Security and it will generate a token this token is the ticket that I was talking about so this ticket or token is issued to the user as a response if it is a valid user okay now what user does is it has sent the username password and it got the token from the server now with every request or any sort of request that it wants to do to the server it is going to send that particular token to the server right what server will do is server will take a look at the token it will validate the token whether the request is valid and if it's valid then it is going to authorize the user and it is going to send the response and if there is uh the token is not valid if that's the case then it will raise an error okay this is how this entire process of GWT works so first if you are trying to access the aps you have to first get the token you have to and server will generate the token it will issue it to you you have to take the token and you have to send it in the apis like every API so you don't need to enter your username and password always okay it's just a token that you have to present to the server to tell server that hey I'm a valid user all right so this is how JWT works and uh this is how the entire process takes place okay now let's talk about how token is sent okay so how is token sent token is normally sent using the HTTP authorization header so in the HTTP request so request is normally trans ited over the HTTP protocol right and there is something called as headers so you can add your own header with the key and the key name is you can see the key name is authorization and the value would be Bearer space token this is what the value would be okay so this is how the token is sent to the server and uh server will basically read this entire thing in the format and it will validate it okay this is about JWT and how it works and here is an example of a gwd token so this is a token that uh I have and uh you can see over here there are three color codes okay so this part is a red color this this is purple and this is blue now talking about individual Parts this red part is a header okay and header typically consists of two parts the type of the token which is JWT and the signing algorithm used so you can have chart 256 or RSA different algorithm which is being used to sign this particular token okay then you have the payload okay so payload contains the claims and uh this will include specific information about the users like user ID username permissions and any sort of metadata that can be added in this particular part which is payload okay third part is a signature okay and uh signature is like a secret okay and it's appended in the end of the entire token okay so this is what a token looks like okay and uh you can see this is how it is so you have this token on the left hand side and here you have the decoded version so this is the encoded version of the token and here you have the decoded version you can see like this particular token has uh or is being uh signed using this algorithm uh the authorization for this or the username is admin over here okay you have the expiration time okay this is all in Unix time format okay then you have some signature related information over here okay so this is what gwd is all about let me take you to the website so now here on the website like on Google itself you can search for gwd and you will be landing on this website gw. you can see Json web token this is what gwd is and these are open industry standard okay and they are used for representing claims between two secure parties okay and this particular website allows you to decode and verify and generate jwd okay and if you scroll down you can see like different algorithms that can be used for signing okay you have like the encoded part which is the token so if you paste a token here you can see the decoded version of token so you can see the uh type over here okay so one second this is the algorithm and the type then you have the payload which is the uh name you can see the name is John do so this is the subject to whom the to token refers to okay and all of that you have uh what is this so this is the time time stamp issued at okay which is I at and this is the time format okay then you have the signature related information okay so all of this is here and uh you can see this is how token is and this is what it looks like okay so I hope you have a clear understanding of GWT and and how it works so let's talk about the implementation of jwd and understand how we would be implementing it okay so implementing involves quite a few files okay I would say like we'll be creating at least three files to implement and write code okay and normally people get overwhelmed so this is one of my attempt to break it down into simple steps and try to explain you as to why we we would be creating this file why would be creating that and all of that okay so here this is what we are going to do okay so there are three main files that we are going to need one is jwd utils this is a file or token filter this is another file Au entry point JWT okay so these are the different classes that we'll be creating okay and of course there is security config file as well where we would be managing the configuration so that I have highlighted separately okay let's talk about each file and let's understand the importance of each so the first file JWT utils this particular file is going to have the utility methods for generating parsing and validating gwts okay so of course you'll be doing a lot of operations with like you you would want to generate you jwd tokens pass them you might want to validate them okay so if if any user is sending in a token in a request how do you know that's valid or not right so you need to validate it and this is where you would need this particular class created when you would have these helper methods or utility methods you can say okay and uh you'll have all these methods defined in this class okay and this would also include like generating a token from the username and extracting the username from the token okay so if you remember we would be sending JWT as the authorization header right and we are going to have Bearer space and the token right so you need to remove Bearer and the space uh to get the token itself right so that you can validated so this extraction will also be happening in this particular utils class okay then you are going to have all token filter now what is or token filter so of course if there is a request coming in it goes through a series of filters right and you need to add your own custom filter over here so we'll be writing our own custom filter to intercept the request and do the validation with the help of gwd utils that we have created okay and if the request is valid we would be setting the authentication context as well okay so this file is going to have like uh operations such as validation and it is going to essentially be a filter that uh will be intercepting the request and it will help us get the Tok and then set the context as well okay so this is the custom filter that we'll be making and then you have or entry point JWT okay now this would provide a custom handling for unauthorized requests so there is a possibility like if you are getting request lot of requests using tokens then there is a possibility like some token might have expired or some token might not be valid how do you handle those requests so this is the Handler that is going to be there and whenever the authentication information is not valid you will be defining the logic as to how that is supposed to be handled okay and uh if there is an issue in the authentication and if it's not valid then you can lck the error and return the Json response with the error message status code and even the uh and even the URL endpoint or the path that was attempted to access okay so this is what it's going to be about the these are three files then we have security config okay so security config we are going to have security config file that is going to configure the filters and the rules of the application so like I said we are going to have a custom filter right or token filter is a custom filter okay we need to tell Spring Security that hey this is a custom filter that you need to consider and here is how and here is when you need to execute it so you need to essentially set up the security filter chain okay and you need to also have the configuration as to how the authentication would work there is there is some configuration work that we'll be doing in this particular config file okay so these are the changes that we'll be working on and this is the importance of each and every file that we are going to write so let's talk about how can you set up the project to work with JWT and uh this would involve adding all the dependencies that you would need so right now here we are in the pom.xml okay so in pom.xml we don't have the dependencies added for gwd so what I'm going to do is I'm going to head over to the browser and uh you can search for GWT GitHub Maven okay so the moment you search for this you'll see this Java GWT which is like a Json web token for Java and Android okay so this is the repository the official repository on GitHub you can even search for this official repository on the github.com okay you can see this is the name of it okay so if you scroll down over here you're going to see a lot of documentation over here okay you can see and uh there are a lot of things and uh you can read if you want to but uh I'm going to quickly go to installation and here you can see jdk projects Maven you can select installation and under jdk projects you have Maven and uh here you can see these dependencies that exist okay what I'm going to do is I'm going to copy these dependencies okay this is done and then you can come over here and you can add these dependencies onto your project okay something like this the moment you add this of course uh Gradle sync is or sorry Maven sync is important and necessary and you should see like some processing happening and all the the corresponding dependencies would be added into your project you can see over here okay you can see like all the these are all gwd related dependencies so this is how you can add the dependencies okay uh if you go to start. spring.io you won't see GWT over here okay so that's why we have to go to the official repo or GitHub and uh you have to get it from there okay so yeah do remember the repo name over here okay it's jjwd you can see okay and this is the URL over here you you can also search on github.com okay so so yeah this is about how you can configure your project to work with jwd so right now what we have done is we have configured the jwd dependencies into our project and as a Next Step what we need to do is we need to add a helper class okay and that helper class is going to be jwd utils this is going to have all the utility methods for generating and managing and working with jwd tokens all right so I'm going to come over here I'm going to like add a package over here so it's best that you have all the jwd related code in a separate package called gwd okay so I'm going to have that here and uh then I can like create a new Java class I'll call this class as GWT utils okay I'll add it to the tracking system and over here what I would do is I would switch over to this notepad and in this notepad I have the entire source code as you can see okay and what I'm going to do is I'll copy this entire thing okay I'll copy this and I'll paste it over here something like this okay so this is the entire source for JWT utils now we will go through the entire source code over here so the file Begins by like this is a logger that I'm creating okay so that's absolutely fine but over here you can see this is defined as a component okay and if you scroll down here here you are creating two variables one is jwd expiration millisecond and here you have the secret for gwd and this is a secret that will be used for signing the tokens okay so we'll go through every method okay and uh this is fetching in so these values are being fetched in from the application properties file so you need to configure this as well okay so we'll scroll down we'll talk about the first method and uh this particular method right now is for getting the jwd token from the HTTP header okay so what we get doing over here is we we have the request as the parameter which is HTTP seret request and from the request we are getting the header and the header name is authorization so to explain you I'll switch over to postman here okay so here we have this hello request what we are going to do is we are going to pass in token here under header and we're going to add this authorization as key over here and we going to check this and we are going to have the token over here so we are going to SA beer space and here we are going to have the token okay so this is how it's going to pass so you need to get this authorization from the header and that is what we are doing over here with the help of this particular like line over here okay so we are getting the header from the request and uh the header name is authorization right and then here what we are doing is we are checking if the bearer token is not equal to null and the bearer token starts with Bearer space okay so if these both the values are true then what we are doing is we are getting the substring okay we are getting the substring and uh we are getting it from the index 7 so we are excluding this Bearer space from the entire string okay and we are returning just a token okay otherwise we are returning null over here okay so this logic is clear I hope what we are doing is we are simply getting the JWT from the header so we are extracting the jwd token from the header and that is what this entire method is for okay if you scroll down you have a method over here which is going to generate the token from the username okay so what we doing is we have a parameter over here which is user details okay this is an object user details we are getting the username from the user details and then we're making use of the this particular thing over here so this line of code okay we are making use of J jots okay J WTS so if you over on this okay this is a class okay and it's coming in from io. Json web token package and it's coming in from our dependency so we are building a token and we are setting different things over here so we are setting in the subject okay then we are setting in the issue time we are setting in the expiration as well so what we are doing over here is with this line we are getting the current date and time and then we are adding in the expiration that we had defined over here in milliseconds okay and that is the expiry that we are setting over here and then we are signing it with a key and this is a method that we have defined over here at the bottom okay we signing it with key and we are saying do compact okay so what this will do is this will actually build the JWT and serialize it to compact URL save string according to the serialization standards over here or rules over here that is what this method does okay so this is what we are going to do if you scroll down over here you're going to see get username from gwd token okay so this is a method that will be used over here to get the username from the token so here we are generating the token from the username and here we are getting the username from the token okay so we are extracting the username in a way and like you can say we are decoding okay so whenever we are creating the JWT you are actually setting the subject as username and what we are doing over here is we are saying JWT dop parer do verify with and then you're saying build over here okay so one second let me format this better so that it's much more readable okay you will see build over here okay and and uh then you are like getting the payload and then the subject okay so this is what you are doing over here okay so you're saying gwd dopara okay you are verifying it with the key You're Building you're doing this over here and then you are getting the payload and the subject over here okay so you can you are actually making use of this okay so these are all inbuilt methods you can see okay it it is passing the jws argument expected uh so essentially this is actually building and then enabling you to get the payload and from within the payload you are getting this subject okay so that's what it is doing over here if you scroll down this is the key okay and you are setting up the key for signing gwd okay so that is what you doing over here and here there's a method where we are validating the gwd token okay so we have system print statements over here and if you don't want you can get rid of them that's absolutely fine but here we are verifying it so you are you are making use of parser verifying it with the secret key and then you're building it and then you're making use of token over here okay something like this and you have different exceptions set up over here and if it's not validated or verified you return false simply okay so this is what you are doing over here and these are all the methods that you need to work with jwd so you're going to make use of the these Methods at different point in time okay and now it's time what we should do is we would set up these configuration properties so these are the couple of configuration properties like secret and expiration M second okay now we would be needing both these parameters or configuration properties so what I would do is I would copy these and I would go to application properties here okay and over here I would add both these okay something like this okay so here and here all right and here I need to define the secret over here okay so secret can be any sort of secret so I can say my secret key 1 2 3 exclamation hash and I can have some random numbers okay so you can have a secret key of your choice here which is secret to you and here you can have the expiration Mill second so expiration millisecond uh you can like actually I I'll just have a very large number over here because I don't want my GWT key to expire quickly right since we are doing development but when you move this to production be sure to have valid values over here okay and this should be the actual expiration that you want to set in your application and this is actually in milliseconds Ms okay so keep this in mind we have these two properties defined and with the help of at the rate value over here what we are doing is we are fetching it from the properties we can even initialize it over here but I believe that is not the best way to do things right you should have properties over here uh when you're doing development and when you're deploying it you should ideally Supply it with the help of environmental variables okay that is really important all right so so yeah that's our helper class for working with JWT uh this is like the main class I I should say it has a lot of stuff and all these methods are important okay so I hope this was useful also I should highlight one thing all these methods have been like worked uh or have been modified and taken care to work with the latest versions of gwd so let me tell you there's a lot of code you will find on the internet okay and the latest version of GWT that is available today there have been lot of methods that have been deprecated okay and lot of better stuff has come in so you can you are not seeing any sort of errors or Warnings over here in this code okay and that is because I have done research and uh like updated like or I have worked on this and made sure that everything works with the latest versions of the code so that is something that you need to also understand because uh this will work with the latest version and all the methods that I'm using are are the latest ones and I'm not making use of any deprecated stuff over here okay so something for you to know all right so that's about this uh class and I hope this was useful so now it's time that we talk about this filter which is the or token filter okay and this will be a custom filter that we'll be building that will be specific to jwd okay and what it will do is it will intercept the incoming request to check for a valid JWT token and if the token is valid only then it will allow the request to proceed okay so this is something uh that we are building very custom okay and to implement this what I'm going to do is I'm going to have this source code over here or this file over here okay so I'm going to copy this entire thing come over here and I'm going to go to the jwd package here I'm going to call this as Au token filter over here okay and I'll just paste it over here okay so so yeah this is done and uh let us go through the entire file over here okay so yeah these are all the import statements like we know okay then this is where the definition of this class starts okay and this is where we are seeing the class extends one request per fil okay sorry it's not one request per filter I'm sorry it's once per request filter okay so what this means is this is class provided by Spring Security if you overun this okay so you can see this is a class provided by Spring Security itself it is coming in from or. springframework web filter okay and this is a class that makes sure that this particular filter executes only once per request okay and this filter is typically used when you want to perform certain actions or apply logic only once per HTTP request you can read more about this from the documentation over here okay you can see over here this this entire piece of documentation here but that is what essentially it means okay so we are executing this once per request okay and uh make a note over here this is a component okay so this is a spring manage component allowing spring to handle its life cycle okay here we are Auto wiring a couple of things okay we are doing field injections over here and we are automatically Auto wirring the instances of GWT UTS and user details service over here okay and uh what is happening over here is so this is actually marked as a component over here so this is actually spring managed okay so this will be Auto wired and user details service is inbuilt okay it's coming in from Aug spring framework security core okay and uh it it is actually an interface okay over here is what you can see okay uh this is a logger okay it's not mandatory you can skip this if you wish to but here we have the actual uh implementation over here okay so this is the two filter in internal this is the this is the method that is being overridden okay and this is coming in from this once per request filter over here okay so we are overriding this okay and what we're doing over here we are getting request we getting response and we getting the filter chain over here okay and if you see over here here we have a try cat block to begin with okay a try catch block now within the try what we doing is we are first passing the gwd token okay uh or I should say we are extract in the GWT over here okay pars is the method we are actually calling pars GWT to extract the GWT token now if you scroll down this method is something that we have defined in this class itself okay what this method does is you can see there is there are a couple of operations it it calls get JWT from header and it is passing the request object over here okay what is get jwd from header it is this method me that we have in JWT UTS and the job of this method is to extract the token and return it in the string format you can see it's returning in the string format it is return removing the pair of prefix over here okay so here if you see we getting the JWT over here we are logging it and then we are returning the JWT okay and then we have JWT in this particular method here okay so far so good okay now we begin the validation process over here so here we are seeing if if JWT is not equal to null okay and if it's a valid token so this method is again coming in from this class over here validate token okay so if this is true only then what you do is get username from JWT okay we getting the username from JWT and this is a method again defined in JWT utils here okay so if you scroll up get username from JWT we get get the username as string okay and what we are doing is we are loading the user details okay so if you see over here okay if you see over here we are loading the user details based on the username that we have extracted from JWT all right and then if you scroll down over here okay we are making use of authentication token over here so username password authentication token okay and we cre creating the authentication over here which authentication is the object name okay and we are passing in the user details along with the authorities now what does authority mean Authority means like what sort of rules does this user have like for example if you go to config over here we have set the authorities over here like for example rule is user rule is admin and so on right we've done this so that Authority we are getting over here we're passing in over here credentials are null and we are passing in the user detail object over here okay I'm simply logging in the rules from the JWT over here just for uh debugging purpose but if you don't want you can get rid of this okay this is just for debugging okay so we are getting the authentication token created and then what we are doing is we are setting the details over here so with this line over here what we doing is we are actually enhancing the authentication op object I should say okay so we have this authentication object created with user details and the authorities okay uh with this is like the token essentially username password authentication token okay so we are enhancing this token over here with additional details that we are getting from the request okay like for example session ID and all so all of that we are setting into the authentication token okay and then we are setting the security context over here okay so we are taking the uh object and we are setting the security context if effectively authenticating the user for the duration of the request and if you scroll up and if you hold control and if you go into this class username password authentication token you'll know that this is an implementation that is designed so there an implementation of authentication over here you can see that is designed for simple presentation of username and password okay and uh this is actually the authentication object is what you can say over here okay and once the user is validated okay once the validation is done we are creating this object and we are setting this in the security context okay so this is how it is being set okay and uh and yeah this is this is what it happens and then we have a catch block to catch any sort of of exception over here okay and then we have this particular line okay so this line says filter chain do do filter request and response so what we did over here is this was a custom filter that we added in between right we added a custom filter so what this line will do is it will say continue the filter chain and this is a request and this is a response object okay so it is essentially telling that this is the last sorry this is not the last filter but this is telling like you continue this filter chain because this was added somewhere in between right this was a custom filter that we have added and this is something that we'll be configuring the addition of filter in the security config we have not yet done this but we are adding this somewhere in the filter chain and we are instructing with this line that hey continue the filter chain as usual okay that is what we are doing and then if you come over here this method is just to pass GWT okay so this is actually the method or the filter I would say uh that enables you to work with uh the or to intercept the request that is coming in and it intercepts every request to check if it if it is authenticated okay and you can see this filter chain is coming in as a parameter over here okay this is response is also coming in over here along with request okay so so yeah this is about the or token filter and I hope uh this is used and I hope this is clear as to how this is working so now it's time that we talk about another class which is or entry point gwd okay so this is a class that we are going to use and it is going to provide us with some custom handling for unauthorized requests and uh this class will be invoked typically when authentication is required but the authentication that is not that is supplied is either not valid or it is not supplied at all so whenever there is an unauthorized request detected that is when this class method is going to be invoked okay so what I'm going to do is I'm going to come over here and here in fact in notepad I have this class ready here I'm going to copy this and I'm going to add this class over here okay and I'm going to call this as Au entry point GWT I'm going to paste it over here something like this okay so this is done okay and uh what you can do is uh you can add something like this and we'll go through every line okay so it starts with component okay which means it's a spring manage component now okay we have the class definition here okay we have logger being created here now we have this commence method which we are overriding okay where are we overwriting it from so so we are actually implementing the authentication entry point and uh this indicates that this particular class will provide custom handling for authentication related error so that is what it it tells so if you're implementing or if you want to provide custom handling for authentication related errors you need to implement this interface okay and you can see over here there's not much in the documentation but yeah it has commments method over here that will have request response and authentication exception as well okay so what you would do over here is once the exception has occurred okay you would overwrite this okay and uh this particular method will be invoked okay and uh if you scroll over here here first thing what we are doing is we are setting up the response okay so we are setting up the content type so I'm actually Printing and logging few things over here okay this is this is not mandatory so I'll I'll I'll just get rid of this okay we are actually setting the response over here okay we are setting up the uh content type and the authorization over here sorry not the authorization uh this is status okay the status over here and you can see this is SC unauthorized right this 41 and then we are creating a hashmap over here where we are putting in a few things like status error error message and the ACT message and the path over here okay so path means the URL that the user was trying to access okay so this is custom that we are creating and we are going to send this as a response over here okay so that is what we are doing and that is how we are handling you can add your own uh handling mechanism over here specific to your project okay but we are handling it this way we are simply returning a hashmap over here okay and you can see this body is being sent or it's being mapped actually to uh it's it's actually being mapped into Json format and it's being written to the response output stream over here okay that is what is happening and this is what this method or sorry not this method this class actually helps with okay so I hope uh this is clear and I hope you understand the significance of this uh class here so now it's time that we begin talking about the the signin flow okay so what happens normally is user would try to log in and this is the flow wherein user would call the signin endpoint okay and uh typically what happens is he passes in the username and password through a endpoint normally it's the/ signin endpoint and then once the user is authorized the token is generated okay and the token is issued to the user so this Endo we need to create to get the token okay and that can be slash signin and what I'm going to do is here in the project I am going to create an endpoint in the greatings controller here this point here okay and uh I have some code already written for this okay we'll go through the entire thing line by line okay and of course we also have login request so this is the dto you can say or the request structure you can say over here okay of course we are making use of Getters and Setters over here we can make use of lombok if you wish to and if you're aware of what lombok is that's absolutely fine you can make use of lombok but I have like used the gets and sets that's absolutely okay important is you learn what is being taught okay you can actually modify this code to get lombok into picture Okay so login request here and login response here so this is the login response so in request you can see we are getting the username and password okay so user will pass in the username and the password and in the response we give jwd token as the response along with username and the list of roles okay so this is the response structure that we have okay and these are the gets and Setters for the same okay so let's go through each and everything and let's move this code into our application so I would copy this entire thing okay this entire piece of code here I'll head over to the greetings controller and what I'm going to do is I'm going to actually paste it over here okay here in the end okay we see a lot of red marks that that's absolutely fine we need to import a lot of stuff here so I'll I'll just go ahead and uh import everything okay so here you can see request body here you have authentication I'll import this class okay and you can see this there are multiple authentications here but you need to get the security core one okay authentication manager so this is the local variable that we need to create this is something we'll be creating shortly okay username password authentication token I'll import this authentication exception import this uh this will come in from security core okay hashmap import HTTP status also import okay hashmap is coming in from okay I guess let me do control Z okay and hashmap is we need to import it from so I'll I'll import it from utel okay and then I need to even get the map over here okay from util HTTP status is something that will import security context holder import user details okay we need to create a parameter of type user details okay but I'll just import this for now jwd utils so this is the class that we have and we need to create an object of the same okay I'll get this list imported collectors imported login response is something that we'll create okay so these things are done okay now here at the top what we need to do is uh are quite a few inputs that we have added okay now what we need to do is here at the top I will add some variables so we need authentication manager okay so what I need to do is I I need to come at the top of the class okay and uh I need to add a authentication manager so I'm going to say here so it's authentication manager uh you can see this one over here okay and something like okay it will be Authentication manager something like this okay and uh then you'll have GWT utils okay like this and you'll create an object of the same okay something like this okay and you'll Mark these two as private okay private okay and you can autowire them Auto wire I'll autowire this thing as well okay you can even do a construct injection if you wish to but I'll just get them Auto add okay and you can see jwd utils okay what happened okay it's it's named as utils so it should be JWT utils and uh authentication manager I guess is so we were getting an error over here so yeah this is Con so now there are two errors left one is login request and other is login response okay so what I would do is I will create a class called login request here I'll see login request something like this and what I would do is I would come over here I would get this code okay login request and I'll paste it over here this is done this is login request and then now you can get the login response so I'll I'll go over here and I can go away login response okay and you can import this from util okay so this is done now coming back to the controller you just need to import these two classes okay so request is imported and the response is also imported okay so yeah this is done okay and let us go through what we just did okay so I'll tell you first login request over here okay there is uh so let me get rid of this here if you see okay login request is something that I closed I guess okay here so what is login request this is the format of the request that we get for logging in from the users okay and this is the class that represents the request that you get okay so you can see username password and like I said we have Getters and Setters you can make use of Longo that that's absolutely fine login response you have jwd token so in the response you'll send the username with jwd token and you will send the list of roles okay you can customize this depending on yourself okay now you'll come to greetings controller okay so here what we doing is uh this particular uh controller method is mapped to the signin API okay and first thing uh what we are doing is we have this uh structure over here like the method structures so we are making use of post request and uh we have login request as the input so the request body is is supposed to be in the form of login request over here okay and uh then over here we have the authentication object created okay now authentication object is created and if you overover on this this is coming in from the security core package okay so this is the core uh authentication object that exist in Spring Security and here what we are doing is we are making use of authentication manager to authenticate this user okay and what is happening is using username password authentication token a token is created okay and uh this is created with the help of the username and password okay so you create a token first and then you authenticate the users okay and there is a possibility of you getting the authentication exception and in that case you are throwing this error or you're sending this response that not found bad credentials okay so this is this is something that you are doing if you're not getting an error and if you happen to go through this Tri block then in that case you are setting the authentication in the security context so you have the authentication object being set in the security context holder to establish the security context for the session okay and this is crucial as it officially marks that the user is authenticated in the Spring Security context and context is what is referred every time okay then you have user details over here okay what we do over here is we retrieve the user details and we generate the JWT okay so from the authentication object we are getting the principle okay and we are casting it to user details object what is user details it is the part of sorry security core package here in security and then we making use of JWT utils to generate a JWT token from the username okay so if you talk about the flow we are authenticating first if the authentication is valid we set the context and then with the help of user details we are generating the jwd token so jwd token is only generated if the user is authenticated and then what we do is we get the list of rules because we need to pass this rules in the response right so if you take a look at the respon on structure you are giving rules and if you are removing this or if you don't want to give rules then you can get rid of this line okay then what we do is we have the response crafted so we have the rules in our hand we have the uh jwd token and we have the user details from where we can get the username and if you take a look at the response you need jwd token you need username and you need roles and all these things we have now and then what we do is we create a login response uh object object you can see with these parameters and we send the response status as okay along with this response okay so I hope uh this is making sense now okay so this entire method is fundamental in a way like it uh helps you set the authentication flow from initial authentication to issuing jwd token to setting up the security context and to send back the feedback on authentication to the user okay so so this is what uh it is and this is how the entire method works okay and here you you are doing a really good job of having a dto created or a response structure and a login uh structure like a request structure created okay and uh you can directly like create a string over here and return it as well okay but I won't say that's a good practice it's best to have a separate uh request and response classes and D set up so yeah I hope this is making sense now okay and this was the first step over here user tries to log in token generation token is issued to the user okay and then in the subsequent request the token has to be sent by the user okay so I hope this was useful and you were able to follow along so now it's time that we make some changes into our security configuration and uh we get whatever we have built to work okay so what I'm going to do is I'll switch over to my notepad here and here I have some code that will be making changes with so first thing is we are going to expose the bean of our token filter over here okay which is like authentication JWT token filter and uh we we'll make use of that method over here okay we'll also expose the authentication manager and we have some changes here in the filter chain so what I would do is I will copy this filter chain method here this entire method here until this okay I'll come over here okay and uh here I have this filter chain so I'll just copy this entire piece of code something like this and I'll paste it okay now you'll see few red marks okay and that's completely fine okay we are getting red marks because we don't have these objects created yet okay unauthorized Handler and these all things we need to get them done okay so what I will do is I will get this bean and these things added okay so let me come over here we have just data source over here so I'll overwrite this with this so data source already existed but we have added a couple more okay these are all red because we need to import them okay so I'll just import all right so this is done the error is gone and this thing is still giving error because we need to import it this is done okay and then we also need to expose the authentication manager being something like this okay so I'll expose it over here okay like so so we import all the relevant classes and we are done okay now let me take you through what we are doing over here okay so first thing we are having a couple of variables created so one is data source we added two more or one more I should say okay so this is unauthorized handw the object name is unauthorized handw and it is a type of au entry point jot okay so if you go over here ENT Point JWT this is like our method or a beam uh that was created to handle unauthorized access attempts okay and we have a custom response over here that we were sending so that is something we are Auto injecting over here okay then we are also creating a bean over here which is of GWT authentication filter type and this filter will intercept the request to check for gwts in the request header okay so you can see this okay this is a method now if you come over here this is the default security filter chain we have done quite a few modifications over here and I'll take you through the modifications so number one is the here here we have defined the interceptors okay so what we have done is we have first said that uh whenever in terms of security we want to permit everything that comes to H2 console okay we also want to permit everything if the API is sign in API okay because of course this has to be unauthorized endpoint only then the user will be able to sign in okay this will be used for authorization and any other request is then authenticated okay so we are just permitting two endpoints over here H to console and sign in so this is H2 console and then we have sign in okay this is done then what we do is we Mark the session as stateless over here with this code okay and uh this is suitable for rest apis where no session state is maintained between request and since we are implementing jwd it has to be stateless Okay then if you come down here what we are doing is here we are adding an exception handling mechanism okay so we are seeing HTTP do exception handling okay and we are saying the exception Handler should be the unauthorized Handler what is unauthorized Handler it is of type created over here or entry point JWT which is the custom Handler that we have written okay so we are adding that to the uh to the authentication entry point over here okay and we are passing this Handler over here okay so it configures the exception handling to use the custom unauthorized Handler for authentication related errors okay I hope this makes sense then over here what we have done is we have uh like set the header configuration so what we have done is we have disabled the frame or we have like set the frames to uh frame options to same origin which allows the frames to be used only from the same origin okay this was done for H2 console then if you come over here we have disabled the csrf this was done again for H2 console okay and now here we have added the filter over here so what we did is the filter that we created okay this is a custom filter right which we have created uh so this filter is au token filter this one this is a custom filter filter and it needs to be added in the filter chain right how would you get it added to the filter chain so we have said HTTP add filter before okay so you have said add this filter before the username password authentication filter in the filter chain so this is the inbuilt filter that exists okay username password authentication filter and you can see it processes an authentication form submission okay so just before this filter we have added our own custom filter so in the filter chain whenever all the filter filters are being executed this one will be executed just before this one okay I hope this makes sense and this Returns the uh filter chain okay it it completes the configuration and builds the security filter chain okay so this is what the entire code looks like here we are having the bean like we had earlier on for user details service okay we have not made any change over here but uh we might need to make any change over here but for now I'm just leaving it as it is okay we have password encoder Bean which is being used for encoding password over here and then in the end we have authentication manager Bean so this is exposing the authentication manager as the be which is being used by Spring Security to handle the authentication okay so yeah I hope this is making sense like this entire configuration that we did there are some changes that are important like if you create a filter and if you don't add it in the filter chain okay that filter is never executed because it's not added into the filter chain like Spring Security you need to tell Spring Security that hey this is the custom filter that I created and you need to execute it at this point and here we are specifying exactly that point over here okay so yeah this is done and uh yeah this is our setup for the configuration of security so I hope this was useful and I hope this was clear so we have come with our application really far we have we are done with the JWT authentication implementation and now it's time that we test the application but before that there are some lose ends that you should be aware of so here if you see the post mapping the endp point is/ signin we don't have anything at the controller level no requ W mapping annotation but if you come over here to security config what we are doing is we are saying permit SL API signin so this is incorrect we need to like correct the URL just make sure that you are having the correct URLs okay this is done now what we will do is we'll run this application let us see this application in action okay all right we start getting errors and uh okay so so this is a number format exception this is this number is very long okay so and this is coming in from properties application. properties here where we have specified a very long expiration time so I'll trim that out let us run this let us see how things go okay we got one more error let us see what this error is okay so this is the error which says table users not found and uh this database is empty okay so let us head over to Security config and let us see user details so we are creating the users over here but still we are getting this error if you scroll up further over here at the top okay you will see an error one second so let me go over here you will see an error that this Factory method user details service through and error okay so it is saying pad SQL GR okay which means like this table probably does not exist yet but over here we are actually creating the table so what is the issue so the problem over here is coming in because we are uh making use of user details service and we creating this bean and we are also trying to insert the user into the database as the part of bean initialization process and at this stage the database might not have been fully configured right and uh that is the reason why we are getting this and the necessary table that we need might not have been created okay and that is why we are getting that SQL exception so what we can do is we can actually separate this uh user creation process so what we can do is we can have a command line runner in use okay now you can make use of command line Runner to get a part of the application execute at the application startup okay and once it's once the application context is fully set up okay so if there are initialization pending that would be done and only then the part within the command line Runner would be executed okay and you can separate this Bean creation so we need a bean of user details service over here we are returning it so instead of having this logic of user creation inside this entire uh Bean initialization process you can separate this out so I would suggest over here you have this kind of a logic here okay so I'll move this logic or move this code over here to this file and let let me show it to you what I mean I'll paste it over here okay and you can see I'm making use of command line Runner you can import this okay command line Runner it is coming in from Aug springframework dop if you overun this you can see it's an interface okay so what we are doing is we have added two methods one is the creation of the pain we are creating a bean over here okay here also we were returning the bean okay so Bean was getting created after inserting the user but here we quickly creating the bean instead and then we are making use of command line Runner initialized data over here this is also Bean okay and this will be executed on the application startup okay and this execution will happen after all the initialization have been done okay so what we are doing is here you get this Bean using user details service and and uh if you come over here you're making use of user details service over here okay here you can see and this user details service is coming in if you scroll up okay where is it coming in from one second so okay so it is coming in from this as a parameter okay and it is being injected over here and uh it's it's actually coming in like we are creating it over here and it's getting injected over here okay and then we are making use of it to create the users you can see all the encoding and the logic remains same like we had over here but just the bean creation and the user insertion is being managed separately so I'll I'll just get rid of this okay I'll just remove this part over here and I'll run this application now let us see how this behaves all right you can see the application is running up and fine you can head over to H2 console you can connect and you can see the user creation is done okay you can even clear this and you can check the authorities admin is of role admin user one is of role user this is done all right coming back to our code what we can do is we can come over to postmen right so here we had mentioned that if you want to query the API you need to pass in the authorization header followed by uh the value should be Bearer followed by token right now we need the token first so what I would do is I'll duplicate this okay we can duplicate this to sign in sign in is the API name here in terms of O I'll say no O Okay so be sure to select no o over here if you're duplicating in the body part of the request I can say raw Json over here okay in here I can say username and uh I can say username as user one and here I can say password as okay one second so password is let me check the password what was the password that we set it should be exactly the same one over here user one password one admin and admin pass you can see over here password one password one let me send this and let us see how this works okay so we are getting 41 unauthorized now to check the issue what I'm going to do is I'll head over to our application we'll open this and we'll see so there's an exception here okay let us go to the top okay so you can see over here cannot set user authentication so it is chasing web token.io decoding exception illegal base 64 character exclamation all right so if you come over here to application properties we have the secret over here which we using for incuding decoding right so I'll get rid of exclamation and any sort of special characters and I'll also increase its length Okay so or let me not increase the length let me just run and let us see what happens so I just remove the characters which were causing issue and uh it's up and running I'll come back I'll say send we get error again let us see what the error is is it around length yes so you can see is a 120 so the specified key bite is 120 bits which is not secure enough okay so you need to have a long uh key over here okay and that error related to exclamation is gone so I'll just type in some random characters something like this okay you can make a Long Key and you can run this okay so it's running and we can come over to postman now and you can see send okay we still getting an error interesting okay it says get is not supported which makes sense we need to switch to post and I'm sorry about sending get request over here post if you say send H we have the jwd token over here you can see so you can see over here jwd token username and you have the rules over here so this user has this role this is something that you know and this is something you're getting in from where you're getting in from if you come over here login request okay so this is the request that you sent and login response is the response that you got okay this is what is in action over here okay so you can see over here okay and uh there are some logs over here okay so you can come over here you can copy this token now this is your token or you can say this is your ticket all right I'll save this request I'll go to the other request here I'll add this token okay something like this now if I send this I'll get 41 unauthorized okay I know why this is coming unauthorized okay but I want you all to understand as well now one thing you need to understand okay I have not enabled logging over here so you you can enable logging to know more about the issue so if you copy this what we are doing with this is we are enabling logs for spring framework SQL related logs security related logs and even our application related logs so I can copy this I can come over here and in application properties I can paste this okay this thing right and let me run this okay this is running I'll I'll just clear this logs okay and I'll send this okay now you can see over here you have okay you can see authentication filter. Java null okay authorization header okay so if you copy this we are printing this in GWT UIL so if you go to this particular class we are printing it over here you can see if you clicked on that we we are printing here and beer token is coming in as basic and this is a token okay so I'll tell you where so ideally it should not be basic it should be Bearer and your token right beer and your token but where where is this coming in from basic so if you go to authorization here we had selected basic Au early on right and we using that same request to add the header all right so basic authentication header is being passed in instead of this one so you need to so there's no issue with our code it is issue in the way we are sending in the request or how this Postman is set up so this was earlyer on set up for basic authentication you need to select this and say no Au so we don't need any Au over here right we need to disable Au and from header here you need to send this and you can see Hello is over here okay and if you come now over here earlier we were getting basic this if you scroll down you can see authorization header now we are getting Bearer and the entire token okay you can disable these logs uh like you're printing in token and all so you can disable them but you can see how hello has been printed printed if you come over here somewhere we are also printing like what kind of user this is like what role it has so you can see all token filter is printing if you see here if you click on this this link is printing the authorities of the token okay so here the rule is role from jwd is Rule user okay so server knows now okay this token is being presented to me this is the user and it has this username and this is the role so this is what I need to give it access to okay if you come over here okay and let me try to access admin admin API if I say send over here you get unauthorized and if you check the logs now let me scroll down okay this is the entire log okay the entire log if you come over here you can see this is a second request now okay to SL admin if you come down come down it says rle user and it's trying to access SL admin you can see or token filter called for this Ur okay and if you come here you will see an issue somewhere okay you can see here this is the issue failed to authorize right and it's saying that this particular endpoint admin endpoint is the target of class this okay and uh you can see it has this attribute has role admin okay now what has happened is because of this it failed to give it access because it's uh not allowed to access you can see unauthorized error full authentication is required to access this resource now you can generate admin token as well you can come over here instead of sign in with the user you can say admin and you can say admin pass you can say send this is the admin token you can see what the rule is usern name is this rule is this now you can go to Hello uh sorry this admin slash and you can change the token here so I've presented a new ticket I'm sending I'm saying send and you get hello admin okay so it's working absolutely fine you can see we have been able to implement gwd in a amazing with with amazing learning experience I would say there were few changes that we did okay during testing but I think that's fine and it's it's a good learning experience so far okay so you can see we have also taken care of making sure that the DS are separate like the request and response objects are separate we have three classes that are helping us do uh like one is the filter like the custom filter which is all token filter we have a helper class which is JWT utils we have this class which is used to handle the unauthorized requests right so all entry point jwd and then we have the security config wherein we are configuring JWT to work with our application so I hope this was useful and I hope you learned a lot okay this entire thing has is a really good learning experience and uh I hope you will be able to implement gwd in your real world projects
Info
Channel: EmbarkX | Learn Programming
Views: 29,782
Rating: undefined out of 5
Keywords: spring boot security course, spring security configuration, jwt in one video, spring security example, spring-security-jwt maven, learn java, spring security in spring boot, spring security, spring security tutorial, securing spring boot, jwt authentication, jwt authentication spring boot, spring boot database configuration, spring security 6, spring security 6 jwt, role based authentication, spring role based auth, method level security, spring
Id: GH7L4D8Q_ak
Channel Id: undefined
Length: 225min 2sec (13502 seconds)
Published: Tue May 21 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.