Easy JWT Authentication & Authorization with Spring Security | Step-by-Step Guide

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey dear fellow coders welcome back to another exciting tutorial today we are diving into a crucial aspect of modern web application JWT based authentication and authorization in a spring boot application here what we will cover setting up Spring Security for JWT integration creating and validating JWT for secure user authentication implementing authorization mechanism based on user roles based practice and potential pitfalls to watch out for and the best part you don't need to be a security expert or spring Guru to grasp this whether you are just starting or a season developer this tutorial breaks down JWT authentication and authorization into easy to follow steps let's Master JWT based authentication and authorization together before starting to code let me give you a small summary of JW WT JWT stands for Json web token so what exactly are jwt's think of them as compact self-contain Jon object that securely carry information between different parties they are like digital passports for your data ensuring it's verified and trusted here's how they work under the hood a JWT is like a sandwich made up of three parts haer payload and signature each section is base 64 encoded and separated by dot here is an example of JWT this first part is header that contains metadata like signing algorithm after header there is payload payload holds the claims or you can say the data you want to transmit such as subject or you can provide your username as a subject here rules or permissions then comes signature a cryptographic signature that verifies the tokens authenticity and integrity to create and sign JWT you can use either a secret key like a shared password with the HM algorithm or a public private key perer using RSA or ecdsa this signature is what that makes jwta temper proof JWT payload can be encrypted and transferred securely but most implementations use unencrypted but signed tokens when a server receives a JWT it uses the same secret or public key to verify the signature if it's valid the server can trust the information in the payload let's start by creating a new spring boot project I will use my favorite online tool that is spring initializer you can go there from start. spring.io make sure you have choose Maven project and language is Java select latest spring boot version at the time of this recording is 3.2.1 scroll down a little bit here choose package as jar and Java version is 17 I'm using Java version 17 because it's the minimum required Java version for springboard version 3 now it's time to edit the metadata change the group name com do hello if car uh that's my Channel's name give it a artifact name spring JWT let's leave the rest as it is now I will move on and add some dependency the first dependency I will need that is spring WB because we'll expose few end points then we'll need Spring Security which is main object of this tutorial then we need spring data jpa because we need to manipulate and interact with the database then we need MySQL driver to connect to mySQL database you can choose other drivers based on your database like for postgress you can add postgress driver or for Oracle you can add Oracle Oracle driver as well so I'm skipping this because I have all I have added my SQL driver now click on this generate button it will generate and download this project in your computer import it into your ID e and start coding I have opened the project on my IDE I am using it IDE ultimate version here is my project this is our pom file let's open it here is our properties defined of the of our spring board project our spring version is 3.2.1 here is our artifact name our group ID and even our dependen is added now let's connect with the database int idea has a built-in tool to communicate with the database this tool is available in the ultimate version only if you do not have the ultimate version you can choose free MySQL tool like MySQL workbench just search for my SQL workbench here is the result from Google from there you can download it and use it for your project I'm going to use my built-in tool here so to connect with the database from my ID click on this database icon that is from your right side bar alternatively you can open it from view tool windows and database click on this plus icon to add database connection choose data source here I'm using MySQL let's filter for MySQL this one click on this now I need to provide our necessary properties for this uh I don't need to change the name host is Local Host that's okay my database is running on default Port that is 3306 now giving my username that is root and giving my password if you're connecting first time you need you may need to download the missing driver files just click on this download link it will download the necessary driver for you our driver is downloaded Let's test this connection make sure you have got this success message otherwise check your configuration and try to connect to your database click okay so our database is connected now we need to create our schema right click on this connection new schema let's give our schema a new name that is spring JWT click okay that's it our schema is is created now let's move on our new Step we'll now establish the connection between our application and the database we have created so go to Project SRC main resources rename this application. properties to application. yml open it this is for representation IM IML you can keep the properties if you want using IML file for setting up the properties is just my personal preference to follow this tutorial it's better to transform it to IML in order to connect database we need to provide a branch of properties here we will add spring then data source here we need to provide the URL of our database connection it is jdbc colon MySQL colon slash here we need to add our server address my server is running on my Local Host so it will be Local Host then my port is 3306 and my schema name is let's check my schema name that is spring JWT so spring JWT now we need to provide our database username and password my username is root and my password and giving my password this is my database password make sure you provide your correct username and password now here we need to provide the driver class name this will help the spring to detect and use the best driver class name here we are using MySQL so my driver class name is com. MySQL cj. jdbc do driver after providing our data source information we need to add some other jpa properties so here we'll have jpa please take a closer look about the indentation here the indentation of this jpa must be the same as the indentation of this data source that means this data source is under spring and similarly this JP is also under spring and this URL is under spring data source if you do not do the indentation properly spring will not able to communicate with your database so after jpa under jpa it will be hibernate and ddl auto this ddl Auto have a branch of options first one is update that is whenever we start our spring application it will check the table and validate it and if any changes necessary to the columns or table it will do that in case of create every time spring start it will try to create new table for our case I'm going to use create drop the main use us of create drop is when we start spring boot it will create necessary tables for us and whenever we stop the application it will drop the tables so we'll get FR table every time we start our project that is for our development only when you deploy it in the production make sure you choose the right one giving create drop now the new properties I am going to add it will be under jpa so this ination will be the similar as the ination of this hnet so it will be jpa and show SQL I want to show the SQL query so I'm marking it through whenever the spring application perform a query I want to see the query I also want to add some other properties so just under show SQL query it will be properties that is spring jpa properties and now under this properties it will be hnet and format SQL and make it true I want my query to be formatted now at the same level as properties give database here we need to tell jpa that which database we are using in our case we are using MySQL and then we also need to provide the database platform we are using this will help spring performing and writing better queries to suit our mySQL database so for this one it's org. hnet do MySQL 8 dialect and that's it about our configuration let's move on and start implementing our security when securing an application and implementing authentication and authorization first thing we will need that is the user so let's create our user class here within the Java and within our root package let's create a new package right click new package give the package name name it model and now inside this model package I will create our user class so right click new Java class make sure you have selected this class here name it user and our user class is created let's close this sidebar for make it some room mark it with entity make sure your entity is from Jakarta assistance the entity in jpa is nothing but plain old Java object representing data that can be persisted in the database now annotate it with table this table annotation specifies the table in the database with which this entity is mapped I want it to be mapped with users table in the database so name is user now this user class will have couple of properties at the first I want it primary key my primary key will be type of integer and I'll name it ID I need to annotate it with ID to let jpn know that this is our primary key and make sure your annotation is come from Jakarta persistence next we need to tell sping jpa how the value of this ID will be generated for the is here we will need to add another annotation that is generated value this generated value strategy has has bunch of options first one is Generation type Auto this is a default strategy if we choose this strategy spring jpa will choose the best applicable strategy for ID generation for the database for the generation type identity strategy it will rely on the database Auto increments feature and alternatively if we choose sequence it will rely on a database sequence to generate unique identifier values for our entities I want my ID to be Auto incremented so I am going to use generation type identity make sure you choose best strategy that is supported by your database when creating table this field will be mapped with database of Name ID if you want to change it you can use another annotation that is column and give it a name of the column with which it it will be mapped so let's give it our so let's give it ID uh let's format this code next our user will have first name and type will be type of the variable is string and name is first name it will also have a last name so column name is last name type is string and and name is last name then we will need a username and password to authenticate the user in our application so for the username column name will be username type a string and name is username next for password column is password and Di string and variable name is also password another property that our user will have that is role like our user may be admin or maybe agent or maybe a normal user so we can assign it using role so adding a new variable of type role and uh here various role is available from various libraries I'm not going to use any of them I will create my own custom rule so I'm not going to import anything and give it a name rule let's create this class create inum I'll put it in our model for the Simplicity our user can have only two rules one is user and another is admin that's it here we need to give it an another ation enumerated and the value is enm type it supports two type of value ordinal and string for our case it's string so that's it for the class now we need to generate the seter and Gator so right click here and generate Sater and Gator select all and click okay perfect our ID has generated necessary seter and geter method for our Fields now let's move on to our next step for user authentication and authorization Spring Security uses a special object that is user details this is a interface and we need to implement this I will implement this in our user class so Implement user details this is from or Spring framework. Security this user details interface needs to implement some of the method let's implement the methods these meth methods are like get authorities e account nonexpert and many of them make sure you have selected all of these and click okay here our method is generated so check those first one is our gate authorities this method should return the list of role that our user have we made our user should have only one role so in our get Authority method we need to give it list of here we will give it a simple granted Authority object and and pass our role name as parameter ro. name our next method is is enabled we want our user is enabled by default make this return true and another is credential non expired take a closer look about this term non expired and this is false this is actually negation so we need to make it true and here is account non nonlocked this is also the same case nonlocked so we need to make it true and another is account non EXP expired and this is true as well and that's it for our user details now let's create a repository for doing some database operation for this user I will name it user repository to do it expand this left side bar in our Java base package right click new create a new package uh name it repository Repository here to create a new Java class repository is a type of interface so make sure you have selected this interface and make it user [Music] repository and this user repository should extend jpa repository and this JP repository accepts two parameter first one is the class for which we want this repository to work in our case it is user and the second parameter is the type of primary key so in our user data type of primary key is integer so we need to provide here integer let's close the sidebar um now I will define an method that we will need later this is for searching the user by their username so it will be optional of type user for finding the user here I will use quering method provided by Spring that is find by after that I need to provide the parameter after which we want to search that is by username and it accepts username so string username that's it for our Repository now let's run the project click the start button our project failed to start let's check what is the error uh the error is due to unable to resolve name work g. hyet MySQL diet this seems I provided wrong MySQL diet let's check it our application. yml file here this is our database platform here I have made a mistake stch it will be org hnet dialect. MySQL 8 dialect now let's try to start this application again okay this time this application started at port 8080 it also have generated as random password it has created our user table and our this is our FEI SK and our primary key is ID and this primary key will use mysql's Auto increment feature that is because we have let's close this one in our user class we have explicitly said that we want to use generation types to Identity so let's check again by removing this strategy and what happened rest start the server here is our user table that fills this ID see no Auto increment instruction is here instead it is creating an sequence table which will be used to generate the value of the ID uh let's go back to our previous ID generation type stop the project check in the console when we stop project spring JP is dropping the users table that is because in our application properties we provided ddl Auto that is it will create the table when it starts and drop the table when it stops so in our user class let's undo these changes and go back to our generation type to Identity so we have created our user repository and also implemented user details now let's move on to the next step here I want to grab you attention to another them check this fields of our user class here I have not provided any access modifier so what is access modifier access modifiers in Java specify the accessibility or scope of a field method or class when a class or method or variable does not have an access modifier associated with it Java assigns a default access the default level of this modifier fire is only within the package this cannot be accessed from outside of the package that means it is package private so what does it mean let me show you here our user class in this model package inside the package let's create a new class give it a name demo user here Define a public method it will not return anything so Bo give the method and name maybe demo inside this method create an instance of user and assign it to user variable now let's assign first name user dot check this here ID is showing Su of first name last name role we can access this field values here directly we can assign or modify values Direct directly from here we can assign the first name here and even we can give our user password directly without calling Sater method so this class is in the same package of the user class that's why these are accessible directly now some other site create a new class in the other package maybe inside repository creating a new class inside repository package give our class name demo repository here again create a method public void demo inside the method create new user instance same as before user equals new user now let's try to assign a first name user dot C here the first name field is not available in the suggestion for this class we need to use this Gator or Sater method to assign values for get for setting the first name we need to use the set first name method here and to access the value of the first name we need to use this gate first name method in this small application which is only focusing on creating and validating JWT this does not cause any issues however this is not best practice even it can cause security leaks of your application if not handled properly we should specify the access modifiers to these fields make this ID private change the first name to private and also making other fields private now this demo user class is showing an error because this is no longer can access the fs here instead we need to use use seter method to set the value for the first name it is set first name passing the text as parameter of the method we have done with it let's delete these classes and delete this demo repository class for authentication purpose Spring Security uses another special object named user Detail Service to make our development easier let's use that closing the tabs creating a new package I will name it service inside this service create a new class let's call it user details implementation or in short IM this class implements user details class make make sure this user details class is from org. springf framework. security closing the sidebar to making some room uh for the user details service we need to implement one method I made a mistake here this will be ex this will extend user details service not user details remove this unnecessary UT from here now implement method this needs only one method to implement that is load user by username this method returns user details if you can remember previously in our user repository we have created a method for getting the user from the database let me show you here is our user repository here here is the method find by username I will use it in this load user by username method to get the user by the username to do this we need to inject user repository private final user repository name it repository now generate a Constructor for making dependency injection here inside the method returns repository dot find by username pass the username as parameter dot or else throw any new username not found exception that's all for our user details service implementation don't forget to annotate it with service annotation now let's move on to the next step in order to generate validate and extract the information from jwd token we need to include new dependencies within our application to do this first open the browser and search for Maven repository go to this site that is ambient repository. comom from here search for JWT it is showing related dependencies in the search result from the dependency list we will need JJ WT API opening it in a new tab we'll also need JWT implementation dependency so opening it in the new tab and finally we need this JJ WT Jackson extension so open it in a new tab for the first one this is for JJ WT API here is list of available version let's select latest one at the time of this recording this is 0.1 2.3 click here scroll down a little bit make sure mavin is selected select and copy this text from the text box open pom.xml file from our project paste the code in this file now again open the browser select the next tab this is jjw implementation select the latest version copy the code from text box and paste it in pom file one more time open the browser open the next tab this dependenc is for JJ WT Jackson extension copy it and paste it in our P file now we need to click this Maven icon here for updating the changes in the maven dependency or alternatively we can right click inser the file Maven and reload the project this will refresh and download the necessary dependencies for us our dependency is downloaded now let's move on to the next step so far we have created our user model our repository and user details service we also added the necessary dependency for the JWT token generation and validation now it's time to focus on token generation and validation I will create a separate service for this purpose in our service package create a new class name it JWT service annotate it with the service to generate and validate the token we need a secret key we will use the secret key to sign the token and we will also use the same key to validate the token the key should be at least 256bit you need to choose your own secure secret key but in this project I'm going to use online tool for key generation from our Chrome search for 256 secret key generator let's select this first result um this will not work for our case scroll down a little bit let's select this from uh s security.com select key size to 256bit click on determine button our key has been generated I will use this hack key copy this inside JWT service class create a new variable private string secret key paste the key here make this variable final now let's generate our token for token generation create a public method return type string name it generate token it accepts user inside the method create a new string variable token value is JJ WT this is from IO dojon web token dot builder then dot subject the username is a subject for our token so user. get username then do issued at here we need to provide the time when the token is issued to get current time stamp new date make sure the date is from java utl date here pass system. current time me for getting current time in millisecond then dot expiration here we need to mention when the token will expire I want it to be valid for 24 hours so new date system do current time in M here we get the current time with this add 24 multiplied by 6 60 for getting minutes in a day then again multiply with 60 for seconds and finally multiply with 1,000 to get the millisecond value I made a mistake here this should be before this closing parenthesis now DOT sign with here we need to provide secret key to sign the key let's call get signing key method which I will create shortly and finally do Compact and return the token it's time to create signing key method this method is private return type it secret key from java x. crypto inser the method create a bite array name it key bytes equals decoder make sure these decoders from IO Dot Json web token do b64 urd code here we need to pass this secret key finally return key that is from iio dojason web token. hmsc sha key for pass our key by it's time to extract a payload or claim from the token I'm creating a private method name it extract all claims it accepts token and returns JJ WT dop parser we need to verify it with secret key get signing key then dot build dot par signed claims pass our token here do payload with this method now we are able to extract the claims this method extract all the claims from the token that is subject issue at expiry all the property will be returned with this method for extracting a specific claim for example I want to access the subject I'm creating a new method so that we can extract a specific property from the token payload creating a new public method making this method generic type name it extract claim it accepts token and function from java utl collection the first parameter of the function is the type of the input to the function and the second parameter is the type of the result of the function in our case the first parameter is the claim and the result is a generic type name resolver inside method extract all claims and save it in the claims variable return resolver dot apply claims now let's get the user name from the claim making a public method return type string name it extract username accepts token as parameter and returns extra claims pass our token and and claims get subject why subject because when generating the token we have added the user in the subject parameter now it's time to validate the token creating a new public method the return type is Boolean name it is valid it accepts two parameter token and user inside the method create a new variable username calling extract username method to get the username from token payload and return if the extracted username is equal to the user's username let's change this user to user details so now if the extracted username is the same as authenticated users username then it will return true otherwise it will be false we also need to check if the token is expired remember we have added expiration to our token so adding a check logical and is token expir I'll create this method shortly pass token as parameter checking if the token is not valid checking if the token is not expired so if this both conditions are true that is the username is equal to the authenticated users username and the token is not expired then this method will return true creating this token expired method return type is Boolean then returns first we need to extract the expiration time from the token and check if it's before the current date let's create the extract expiration method this is a private method return return type is date that is from from java utl date method name let's copy the name from here and paste it it accepts token returns extract claim pass our token and we want to extract the expiration time so claims get expiration so we have finished coding our JWT service it's time to create a filter what is filter in Spring boot a filter is a Java class that intercepts and process HTTP request and responses before they reach the controller or after the leave the controllers it's a powerful mechanism for applying cross cutting concerns such as authentication authorization login content modification and many more using this we can check users credentials and permissions before getting access to the resource let's create one expanding the sidebar create a new package name it filter inside this filter package add a new Java class name it JWT authentication filter annotate it with components I have made a typo here let's correct it refactor rename update the name it extends once per request filter I'm using this once per request filter because I want this filter to be executed once in every incoming request this need to be implemented let's implement it the method name is do filter internal closing the sidebar move it to a new line for better reability it accepts three parameters seret request seret response and filter chain here the ID is showing warning we can remove this by simply adding non Nal annotation that is from org. spring framework. length doing the similar to the other parameters inside this do filter internal method add a new variable data type string name it o header we need to extract authorization header from the request header request dot get header name of our header parameter is authorization now check if the header is null or if the header is not started with brr if that's true will not do anything just pass the request to next filter of the filter chain using filter chain dot do filter pass the request and response and finally return if the header contains the authorization hater with a varer token then we need to extract the token token equals o header we need to substring O header the beginning of index is s because we need to skip this text brr including space which is total seven characters long after getting the token I need to extract username for this we will need use JWT service so let's inject JWT service here create a new field private final name it JWT service now here after token extract username using JWT service and and save it to the username variable now we need to check if the username is not null and if the user is not already authenticated we can check if the user is authenticated using security context holder dot get context dot get authentication equals null in this case we need to authenticate the user we can do this using username password AU authentication token it accepts three parameters check the source this is the Constructor first parameter is principal second one is uh credential and the last one is collection of authority so our first parameter is user details credential is null and the last and the last user details do gate authorities we need to Define our user details variable to do this create a new field final user details implementation and name it user details inject the dependency with the Constructor this still now showing an error um let's update a name name of the user details to user details service now here after the if statement new variable user details name it user details equals user details service. load user by username let's remove this now we need to check if the token is valid if JWT service dot is valid it accepts token and user details if token is valid then inside this if statement add a new variable username password authentication token name it o token equals new user name password authentication token pass user details credential is null because it is token based authentication and last parameter is user details and last parameter meter is user details. gate authorities now a token do set details pass new web authentication details Source do build details and pass our request and finally security context holder get context dot set authentication passour Au token and finally if statement filter chain dot do filter request response here is an error we need to inject this user Detail Service using Constructor remove this portion generate Constructor our filter is complete now we need to register this filter in our Spring Security we can do this is using a bin named security filter chain create a new package name it config inside config new Java class name security config annotate it with configuration and enable web security here we need user Detail Service as dependency we have implemented it in our service package this is our service implementation this name is confusing let's change it refactor rename rename it to user details service IML refactor in our security config create a new bin public security filter chain it accepts HTTP security I will call it HTTP it thr exception inside the method return HTTP dot I want to disable csrf so csrf abstract HTTP configur disable dot authorize HTTP request inside inside Lambda expression req Arrow req. request matchers I want all request to login and register URL to be permitted so slash login douar comma register SL register double star permit all any other request must be authenticated after this authorized HTTP request we need to tell which user Detail Service Spring needs to use so do user Detail Service here we need to pass our user us Detail Service inject our user details service here private final user details service name it user service we will also need to inject JWT authentication filter authentication filter now generate Constructor inside this user details service pass the user service then dot session management inside parenthesis Lambda expression session Arrow session dot session creation policy session creation policy. stateless then after this do add filter before here we need to pass our authentication filter let's rename JW authentication filter let's rename it to JWT Authentication filter update the Constructor so add filter before first parameter is JWT authentication filter second parameter is username password authentication filter. class and finally build we'll also need password encoder bin for encoding password ban public password encoder name it password encoder return new bcrypt password encoder another bin public authentication manager name authentication manager accepts authentication configuration I will call it configuration returns configuration dot get authentication manager our security config class is complete now it's time to create our controller for handling the end points create a new package controller inside controller package create a new class authentication controller closing the sidebar for making some room add controller annotation m it should be rest controller remove unused import this controller class will handle login and registration request for user login and registration let's create a new service inside the service package new Java class authentication Service give service annotation declare a new field private final user repository name it repository another field private final password encoder password encoder another one private final JWT service JWT service create a Constructor our Constructor has been generated now let's create method for for our registration creating a public method return type is authentication response I will create this response class shortly name it register it accepts registration request as parameter name it request inside the method create a new instance of user set user first name user dot set first name pass request Dot get first name let's change it registration request to user set user last name Now set username request do username for password user dot set password Here we need to pass hash password to do that use password encoder Dot and code here pass our password from request it's time to set role user dot Set Roll pass pass user dog roll and finally save the user using repository Dove after saving the user let's generate the token string token equals JWT service. generate token pass our saved user here and finally return authentication response pass the token into the Constructor it's time to create authentication response class inside model repository create a new Java class authentication response add a private field string token generate a Constructor to set the token value and also generate Gator method to get the value of token now back to the authentication Service import authentication token class now create a method for logging the user public authentication response authenticate it accepts user for user authentication we will need to inject another bin here it will be private final authentication manager name it authentication manager we need to update a controller for newly added field let's delete old Constructor now generate Constructor select all click okay now inside authenticate method authentication manager do authenticate new username password authentication token here we need to pass username and password so request. getet username and request.get password now add a new variable user equals this is our registered user we need to get the user from the database repository dot find by username pass the request do username this is showing error let's check what's my ID is suggesting we need to change it to optional let's change it after that I will generate the token string token equals JWT service dot generate token pass our user this is now showing error let's fix it from here remove this optional and here find by username at dot or else throw finally return new authentication response and pass token now back to the controller add private final authentication Service name it o service generate Constructor for setting the value and post mapping it is for register public response entity type is authentication response method name register accepts request body user request this method returns response en itty do okay pass OD service do register inside register pass request another post Ming for login URL public response entity authentication response method name login accepts request body user request return response entity dot okay pass Au service do authenticate pass request to the authenticate method so our controller is complete let's start the project project started here new user table is created to check it uh open Postman open a new tab request type is post URL is Local Host 8080 this one is for registration slash register select this body tab choose raw choose Json from drop drown here give our Json request first name last name username password and roll send the request our token is generated this is our jwd token let's check the data in the database open the database from the ID it's not showing our table let's refresh it our table is here expand it this is our user table view the data from the table here is our data this is our password but the first name is null let's check what is the problem close this table close the database tool authentication controller it looks fine authentication Service um we are setting our first name and getting the first name from the request no problem is here let's check the request here I made an typo this should be first name let's remove the data [Music] better to restart the application it will delete the data and will create a new table let's do it fix the request send the request again registration was successful and the token is generated let's check in the database again but this time the rle is not saved check the request no problem with the request here we are setting the RO why is that check the user class yes we have added R seter and geter here check the rule check check again the user class authentication ser service register method here we are setting the rule this should be request.get R restart the server send a new request this time it was successful a token is generated check the data the first name is here this is the password user the name and roll our data is saved let's decrypt the token and check it copy the token open the browser go to jw. scrolling down a little bit here paste our token here is our decrypted data our payload subject is the username this is token expir time and the time when the token is issued now let's check the signature here in this input field I need to provide the secret key so that this can validate our doken signature we have the secret key in our JWT authentication filter no not this authentication filter it's on JWT service here is our secret key copy it and paste it in the input box now this can verify our signature using our secret key now let's try to log to the system at first uh try with wrong user username password send request 43 forbidden okay uh let's uh request with a current username correct the username name send request now use authentication is successful and the token is generated let's create a new endpoint to check the authentication creating a new controller inside controller package name it demo controller annotate it with rest controller get mapping for demo URL public returns response entity entity type is string name demo and return response entity. okay and passing a string hello from Secret URL now let's try to access this URL restart application from Postman copy the URL open a new tab paste it change login to demo send request 43 forbidden now let's try with token we need to register the user the token is generated copy the token now in demo request tab click on authorization select brr token from the drop- down list past the token in the input now navigate to Body send request respon status is 200 we can now access the secured URL now let's do the authorization part in the controller adding a new get mapping for adminon URL public method returns response entity of string give method a name returns response entity do okay provide the text that we are going to display hello from from admin only URL Now navigate to security config class here in the security filter chain method after this white listed URL we need to configure our authorization do request matchers URL is admin uncore only followed by SL doubl star I want only admin user can access this URL so dot has any Authority pass our Authority name that is admin restart the server now as our user table is recreated we need to register the user again first user with user Ro user is created copy the token head to the demo URL tab authorization BR token paste the new token send request it accessible now add a new tab provide URL for admin only page authorization brr token copy the token from registration tab paste it in token input field navigate to the body send a request forbidden access that is because the user withdraw does not have the permission to access this URL let's add another user for admin rooll change the username change role to admin send request new user is created copy the token back to the admin all URL authorization tab paste the token back to body send the request this time the status code is 20 admin has permission to access this URL and with this we are at the end of this tutorial it's pretty long tutorial I have tried my best to teach you something that you may find useful I'll be back with a new tutorial soon if you have any specific tutorial in your mind drop me a comment I will make the tutorial on that well done and happy coding
Info
Channel: Learn With Iftekhar
Views: 19,127
Rating: undefined out of 5
Keywords: spring security, jwt authentication spring boot, spring security jwt, spring boot security, spring security in spring boot, spring boot jwt, spring jwt, jwt spring boot, spring boot security jwt, spring security in spring boot jwt, spring security tutorial, spring boot, spring jwt authentication tutorial, spring boot jwt token authentication, spring boot security tutorial, spring data jpa tutorial, spring security 6, java spring boot security, java spring security, jwt
Id: RnZmeczS_DI
Channel Id: undefined
Length: 68min 14sec (4094 seconds)
Published: Tue Jan 30 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.