OAuth 2.0 Implementation with Spring Security and Spring Boot | Full Example

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up everyone and welcome to daily code buffer in this video we are going to learn about the auth 2.0 and open id connect in detail with example so without wasting any time let's get started [Music] so in this video what we will do is we will understand what is auth 2.0 and what is open edit connect how we can use both of them with the spring security and spring boot and how we can create a cohesive application where we have the login functionality with the help of authorization server resource server resource client and all the different components so what we'll do is we'll create one application where we want to call the authorization server that particular api that we are going to create that has to be authenticated that are then only we will be able to access the apis without authentication we won't be able to access the apis and to make that possible we will be using the authorization server so we'll be creating our custom authorization server which will handle all the authorization requests and if there is any apis that are behind the authorization server suppose resource servers right so there are resources that we want to connect after the authentication from our client so that also we are going to create and it will be handled using the authorization server with the os 2.0 and open id connect so this type of functionality you would have seen at many places if you go to any of the websites and you might have seen the button like log in with google log into twitter login with github and all the other things right so this type of implementation is possible using the auth 2.0 where you will give the authorization of your application to a client like that particular client can use your application so we'll be providing the consent to the client like okay you are authorized to use this on behalf of this particular user so you can use this particular application so that's what we are going to build today so we are going to see everything in detail in the demonstration and if you are interested in any kind of path based learning where there is a predefined path available and you can learn those particular things then you can check out the educative dot io in the education dot io there are different paths available and within those paths there are different modules available you can learn all those particular modules and you can complete your path and you can get the certifications there are parts such as machine learning engineering devops engineering full stack application developer system design expert and many more so if you're interested i'll add the first link in the description below for you to check out now let's get back to the video so before we implement the login functionality we need to understand about the auth 2.0 so you might have seen this auth to implement it at many places so everywhere you go you will be seeing this particular buttons to log in with those particular authentication providers there will be octa or xero and many things okay so these are all the authentication providers based on the auth 2.0 standards now before we implement anything we need to understand about the auth 2.0 so os 2.0 which means open authorization is a standard designed to allow websites or application to access resources okay hosted anywhere on behalf of the user so it's like very simple if i give you the analogy i have my mobile phone okay and if you want to use my mobile phone you have to take permission from me to use that particular phone that's a simple thing so that's the analogy that we are going to understand from there so i have my phone that means i have my resources or my apis if you want to access it you need to take the permission from me to use those apis or to use my mobile phone okay so that's the standard that has been os 2.0 so os 2.0 is just the authorization protocol and not the authentication so it only provides the authorization like you are allowing someone to use your resources i am just allowing you to use my phone okay simple things it's just the authorization that you can access this but what about the authentication that authentication comes later when you connect open id with it okay so all 2.0 and open id connects together and you will get the complete authentication and authorization working together now the other important part of the os 2.0 is it is designed primarily as a means of granting access to a set of resources suppose you have a set of resources like if you take the example of a twitter twitter has its own api if you want to access those apis you need to request for it right you will be requesting twitter to use it okay and the twitter will give you some extra details about authorization client id and all those tokens and everything to use those apis so it's just like that and watch 2.0 uses access tokens so we will go in detail about the access tokens and how everything works but this is a basic idea about it now in watch 2.0 these are the basic jargons that you need to understand because everywhere this will be the thing that we will be talking about that is the resource owner client authorization server and resource server entire auth 2.0 depends on this and you will be implementing this only let's understand resource owner what is resource owner a user or system that owns the protected resources and can grant access to them i just give you the example right i have my phone and i am the sole owner of that particular phone because it's my phone okay and if you want to use it i can grant you access and you have to ask for me so that's the resource owner now the client the client is the system that requires access to the protected resources you my friend you are the client because you want to access my phone right so a client will need the access from the resource owner and here you can see that client must hold the appropriate access token if you want to access my phone you need to have my password right so that is something that the access token will be given to you so that's the resource owner and the client now the next is the authorization server so this is the server receives request from the client for access token and issues them upon the successful authentication and consent by the resource owner so it's something very simple right authorization server will what it will do is it will just give you the token on behalf of the request that you are giving okay authorization server is nothing but to authorize your request it will just check that are you authorized to use that particular resources that you are trying to use and once the consent for that is given by the owner resource owner then authorization server will allow you to use those particular resource that's a simple thing and the resource server a server that protects users resources and receives access request from the client it accepts and validates the access token from the client and returns the appropriate resources to it so it will just try to handle or it will have all the resources so it will try to handle all the resources and if any of the request comes with the proper authorization with the proper code then it will allow the client to use those resources otherwise it will decline the request so these are the terms these are the main terms that we are going to implement we will be implementing the authorization server we are going to implement the resource server and we are going to implement the client so whatever the application that we are going to build the apis that we are going to build that will be your client so with that particular client we will be implementing the authorization server and the resource server so all everything works together and your request will be authenticated now if you go back to the intellij idea if you see here this is your spring security client this is your project where you have the different apis right whatever we have created so these are the apis that is your client and this particular clients whenever you are doing any requests you might need the access from the authorization server or the resource server whenever you want to create any of the things it's simple as that right so we have to create the authorization server and all this authorization will be handled from your database okay if you go to the database these are the users that we have right shabby and nickel currently so all your authorization will be validated against this particular users will be passing the user details it will handle this user details and once the users are validated it will be allowing the resource to use and the next thing that we have to understand is the scopes scopes are important concept because scopes exactly defines what you are allowed to use okay suppose you are not the admins you are just the user then you have only rights to read the data if your admin you have some rights to modify the data as well so all these particular things are defined based on the scopes of the application okay scopes for the particular user and all these particular scopes you will have to give the consent to use those particular scopes so it's very simple like if you are going to any of the websites and there is a button to log in with google when you hit on that button login with google you will be redirected back to the google page and where you will be entering your credentials once you enter the credentials you are authenticated by google and after that you will be displayed the scopes like these are the permissions that your client is asking right to read your name to read your email id to read your profile picture these are the different scopes i've defined so it's asking the consent from you that a particular client is asking all this particular details from me and if you hit allow then only the consent is accepted and the particular client is allowed to use those resources it's similar thing so these are scopes and if you see this particular flow over here so this is just the abstract flow there are different particular variations available based on the different grant types and the flow will be changed accordingly so the ideal flow would be like you have the client your application your user that is a resource owner your authorization server and your resource server and this is your service apis entirely on top of the authorization server and the resource server whenever application wants to use anything application will create the authorization request to the user to the resource owner like i want to use this particular resources and user will grant the access like you grant the access when you click on the gmail right after login to the gmail so you gave the grant like okay you can use those resources to the client now client got the consent like okay i am allowed to use those resources then client will send that grant to the authorization server okay i got the request okay i got the permission now okay this is the permission so what authorization server will do is okay it will validate okay you got the request you got the code now take this token so authorization server is giving token back based on the code that we got as the grant okay so now the token is given back to the client after validation now with this particular token the application of the client will hit the server to get the details so once that particular token is valid until that particular token is valid so resource server will allow those requests if the token is not valid resource server will not allow those requests it's a simple flow this particular things you need to understand that is the client resource owner resource server and the authorization server this is how everything will work together now we will go to the application and we will implement the authorization server and we will connect our client with the authorization server and we will also create the resource server so if there is any resources that we have created behind the authorization server then user can use those so let's go to the intellij idea okay we have one client available and this particular client has a controller and you can see that there is one api get mapping slash hello so this particular request should be allowed only if you are logged in now let's implement the authorization server so we need to create the new authorization server application so let's do that so now if you want to understand this flow you can go to the auth playground okay oauth 2.0 playground this one okay and from here you can understand that particular flow so here you can see that there are different flows available there are different types of implementation that you can do authentication code pixy implicit device code open id connect and anything okay generally authorization code or the open id connect with pixy would be more implemented so let's try to understand the simple authorization flow i'll add the link in the description below so you can check this out i'll go to the authorization flow and here you can see that it is asking to register a client first okay client means your api from where you're going to access okay before you can begin the flow you will need to register a client and create a user simple thing so let's register a client okay in order to use what api you will need to first register application if you go through this right if you go through this entire flow you will get a much more understanding about the oauth 2 flow so i i'll highly recommend you to go through this particular flow as well so you will get more understanding so let's register this client okay and here you can see that you got the client registration data so it's simple it's similar to how you will be registering your application to any of the auth to providers like google github linkedin or whatever like whatever the austral providers are there you have to register your application and you will get the client id client secret let me just open this in a new window and these are the client registration so let me just continue and register this client to the os2 okay and here you can see that this is the first row build the authorization url and redirect the user to the authorization server and currently this way the authorization url will be built so your authorization server dot com whatever the authorization server is slash authorize so slash authorize this this so these are the standard apis okay these are the standard apis from the auth 2.0 wherever you will be implementing this this will be the standard urls if you want to modify you can modify but these are the standards and with this authorize you will be passing more parameters that is the response type what type of response type it is its code so because we have started with the authorization code flow the response type is code okay for the different uh flow this particular value would be different and you can see the client id and cliented equals to client id that we got and the redirect uri this redirect uri is nothing but once the authentication is done where you want to redirect back so that particular uri we need to define and the scope so these are the scopes that we talked about earlier like what should be the scope of the access that you want to grant so that scope and this particular state you can see that this state is the parameter the client will need to store this to use in the next step okay so this state also will be generated so these are the standard parameters that will be generated to authorize your request so let's authorize this request against the or server and here we need to add our credentials so these are our credentials so let me just copy the username and this is the password okay once you log in it will be authorized and here you can see that now it is asking for the consent okay that do you approve or not so we will approve and here you can see that verify state parameter and here you can see that it is checking the earlier state and the current state after redirection the states are same if it if it matches then continue if it doesn't matches then what is the flow so you can check both the flows so let's continue with the it matches continue so you can see that once this match is the next is the exchange the authorization code so after that whatever the code we got right we need to hit this token uri to get the token so here you can see that the grant type equals to authorization code we are passing the client id we are passing the client secret okay whatever the client secret it was we are passing the redirect uri and also we are passing the code okay whatever the code we got from the above step so once once we hit on go against this authorization code and all the details we will get the token and that is the token that we have to use so once we click on go at the end you can see that we got the token this is the access token for your resources from your client so you can see that there is a refresh token the scope is also defined what is the scope of this token it's a barrier type okay when it expires so all this information is there so you can try for the another flow as well and you can check it out how everything is working so this is a general idea how this oauth 2 will work and similarly we will be implementing in our system so now let's go to the spring initializer okay start dot spring dot io and let's create the authorization server so let me just add the group id com dot daily code buffer and the artifact i'll give is auth authorized server the package name i'll give auth server okay packaging is jar jar version is 11 and let's add the dependencies so i'll add the lumbar dependency i'll add the gpa dependency as we need to connect to the database i'll add the mysql driver i'll add the security and i'll add the web dependency so these are the dependencies that i'm adding in my authorization server so let's generate the project and add in the intellij idea so i'm just generating the project let's open in the finder unzip it let's copy this go to documents java workspace spring security and i'm adding over here okay now this should be added to the intellij idea and if i go to my parent that is spring security tutorial let me add the module or to authorization server okay here you can see that authorization server is imported i'll be using the services now within this authorization server okay we need to add one more dependency that is the authorization server so let me just go down over here in the dependency section let me add the dependency that is the spring security auth 2 authorization server the version that we are using is 0.2.2 so this will allow us to create the authorization server now for this authorization server let's go to the java main resources let's change the properties files to yaml and let's change the server port server.port to 9000 okay so i'm just changing the port and for this as we are going to use the jpa with the same database i need to add the configuration details for the same so let me just go to the spring security client i'll go to the resources application.yaml let me copy this detail and let me go to application.dml and paste this simple right i'm just using the same my sql localhost 3306 user registration schema username password is root class name provided and shows equal is equal to 2. so all these details are there now for this particular authorization server as well we need to use this user registration and the user flow right so we need to have the user entity user repository and the user services that we have defined in the spring security client to my authorization server as well ideally if there is any duplicate or duplicate files that you have to use so you can separate out all those particular files in a separate project and you can use that particular project's dependency in your prom.xml file you can go ahead that way also but currently let's directly use those so in my java folder let me create the packages i'll create the package entity service config so i need the user entity so let me just copy this and paste it over here then i need the user repository so let me just copy user repository and paste in the user repository now in your auth authorization server we need to implement the custom user detail service now user detail service is the default service provided for the users to interact with the spring security to check if the user exists or not so that particular thing we have to customize it to use our database so we need to create the custom user detail service for that so let me just create a class that says custom user details service custom user data services is the class in the or authorization server and this is the service and we will implement this is a transactional and this particular custom user retail service will implement user details service this user details service you can see that is part of the spring security okay and there is a method that we need to implement that is the load user by username so whatever the username is for me the username would be my email id whatever that we are using so with the help of the user id that we have we need to load the user from the database and we need to pass back to the spring security so spring security can handle that user this is very important step okay because without implementing this user detailed service spring security will not know about the users that we have in the database so for this reason only we had added the user and user repository entity and repository in our application copied from the client so let me just create the object of user repository and i'll auto wire it okay now instead of username i'll just make it as email so we can understand better so here let's implement it we need the user object that is the what we have added in the entity okay so let me just use this delegate buffer or server dot entity this user equals to user repository dot find by email will pass the email okay we got the user then we will check if user equals to null then throw a new user not found exception and you can pass no user found and after that if so and now we need to return the user that user would be of this one that is the origin.springframework.security.com so this is the user that we need to return back okay and here this particular user needs few details so let's pause it user dot get email then user dot get password currently i'm passing everything to true because if you see this we need to pass username password it's enabled account non-expired credentials on expired account unlocked so one two three four true this value i can get from the user itself so user dot is enabled rest everything to true okay and the last thing it requires is the authorities authorities is nothing in the spring security that what all things that you are authorized to use the resources it's just as the scopes okay so let's implement the method for that as well so i'll just implement get authorities method and here in this authorities i'll pass the list dot off user dot get roles and this get authorities let me just create this method and this is a collection that extends granted authority now we need to create this granted authority so let me just create the list of granted authorities authorities equals to new era list and for each string role in roles okay let me just rename to rules i will need to add the authority so authorities dot add a new simple granted authority si simple granted authority and i need to pass the rule then return authorities okay so let me just add the new over here cool that you can see that you my thought that we did a lot of things but it's simple we just created the custom user detail service and implemented the user detail service which is very important part of the spring security to load the user based on our database that's the custom implementation so we injected the user repository and this is the load user by username method that we have implemented the method which is taking the email as the input parameter we got the user from the database if user is null then user is not found exception withdrawn else we created the user object from this user that we have from the database so we passed all these details email password enabled everything okay all these details you can pass from the user you can add all these details in the database okay and we can handle it and we got the roles and based on the roles we created the authorities okay so the user is created so now we this particular user will be part of the spring security so whenever we need a user we'll get directly from you so your custom user detail service is done now comes the other thing that we need to implement the configuration we need to add the configuration for our authorization server so this implementation would be standard for all the authorization servers so there is a bunch of code where you will be creating the public keys private keys and all those stuffs to handle your authorization server so your clients can connect to it and the exchange between the authorization code and the token can be happen smoothly so it's a bunch of standard codes that i'm going to add over here and i'll try to explain it so for that let me create the configuration file so in the config directory config package sorry i'll create the java class and i'll say authorization server config okay so this configuration would be basically standard configuration for your authorization server i'll just add the configuration and i'll just add proxy bin methods to false now there are a bunch of standard implementation that we have to do so let's add that we would be needing the password encoder so i'm just adding the password encoder over here so now you can see that the bin is not available so we need to create the bean for it so let's create the bean for it so let me go to the custom user detail service itself and here let me just create the bin okay i'll just use password encoder i'll just make it a public method and return new baker password encoder with strength 11 same thing that we have added in our client as well and annotate with pin no fancy stuff okay so now in the authorization server there it is gone now let's add bunch more things now we need to add the security filter chain okay so let me just create the bean of it let me just so you can see that we have implementing the security filter over here and we are injecting the http security so what we want to do for our security so it's simple stuff this particular thing you can see there the auth to authorization server configuration dot apply default security so we are applying the default security over here that means that default auth to authorization functionality so default slash authorized api slash token api all those default apis are there right for the oauth 2 all those default apis will be defaultly added to our configuration so that's what we have done over here for our security filter chain okay if you go to this particular class you can see that this is the apply default security that we are calling and these are the bunch of default configuration has been added over here okay you can see that all the rsa keys and jwt encoder and everything has been defaultly added over here and we are calling that apply default security so all those particular apis are available for us too all those default apis will be enabled and then what we are doing for this http we are using the form login and we are customizing this form login for the default so with the default configuration for oauth2 everything will be set up with this line of code okay and we have added the highest precedence for this bean to be used so if you want to configure any of the apis for the oauth 2 then this is the place that you have to configure but i'm going with the defaults you should go with the defaults unless there is a specific requirement okay so this is the configuration for that now as we saw earlier every time the clients were getting registered to the authorization server so here also we need to register the clients so client registration also we need to enable over here we need to add the configuration for it so let me just add the default basic configuration i'm just copying this code because this is the standard code okay now there's a lot of things in this method but don't worry everything is simple so here you can see that it is registered client repository so this is the repository that has been provided for all the clients to get registered okay so if you want your custom implementation you just have to implement this interface okay it has the couple of method that is the save find by id find by client id that's it you just need to implement these methods according to your requirement according to according to the database that you're using or according to any of the things that you're using if you just implement this three method to get the particular output or particular return type that's all good okay so currently i have only one client available okay i am using only one client that is my spring security client this particular spring security client i want to register with my authorization server so that's why i have just added one client statically over here ideally you won't be doing this these are the steady configuration okay if you want to do dynamically like with like how we saw earlier you need to use the jdbc registration client or your custom registration client where you will be getting all those details or you will be generating all those details and giving to the user who wants to use your authorization server i know what i want to use because this is my project this is my client and for this client there are details that i am using over here that i am positioning over here and this details i will give to this client so this client can connect to the authorization server that i have okay so this is a simple thing i'm creating the object of registered client with a random uuid okay and what i'm giving this details that is the client idm i'm passing the client id as the api client that is the name of my client so my spring security client this is the name i'll be giving to this spring security client then i'm giving the client password that is the client secret i am encoding the password with the secret then client authentication method so i'm using the client authentication method as the client secret basic okay so whatever the secret information that you are passing over here with that particular information i'll be able to authenticate my client these are the grant types that that we are allowing you can see the authorization code password refresh tokens so these are all we are allowing for the client to access through then these are the redirect urls i will talk about this redirect urls later so these are the urls of your client so once the authentication once the authorization is happened from the authorization server where you want to redirect back so i want to redirect back to this particular urls now how i got this particular urls that i'll tell you like how we got this these are the standard format urls that you can define okay so everything i'll tell you later once we implement this but consider these other two urls redirect urls then i have defined two scopes okay one scope is the oid scores for your open id connect because we are authenticating as well and the other scope is read scope api.trade and then the client settings i have extra added so what i'm doing is in the client setting is client settings dot builder dot require authorization consent so i am enabling the consent over here that my authorization server this server needs to give the consent back to the client to allow okay so it will have the page of the consent as well if i don't add it there won't be consent the consent will be directly given and i'm building this particular object okay and i'm using the in in-memory registered client repository so this particular register client will be in the in memory itself of this particular authorization server there is one more default implementation added that is the jdbc registered client repository if you want you can directly use that as well and if you want you can create your custom implementation as well as far as i know there will be only these two implementation by default provided by the spring auth server because there are a lot of databases and there are a lot of implementations available so you can always go ahead and implement according to your requirement if you want to use red days whatever center whatever you want to use you can implement this particular repository you can extend this implement this repository according to the database that you're using to register your clients i have one so this is direct so this is a code to register my client we will come back for this to redirect urls later okay but rest of the things are clear that we are giving the authorizations and everything so how to connect my client to this authorization server then now the next thing i required is the public and private key configuration so let's add the code for that okay here you can see that i've just added this information but this is nothing but the standard configuration for your public private keys we just have to create one bin for the jwk source and we're just creating the rsa key over here this is the standard you just need to copy paste it and it will work you don't have to change anything okay until unless you have to change the algorithm like which algorithm that you are using to generate the key that's it rest everything you can directly use it now you might be wondering from where i got this code got this code from the samples shared by the spring security team itself you go to that repository swing security or server all these particular details are there so you can directly use from there this is nothing fancy just just directly use it you don't have to change anything you don't have to bother about it okay now the next configuration that you have to do is the provided settings so provided settings is nothing but the pro the authentication or your authorization provider or server provider so these are the bin configuration for that so yeah you can see that i have just defined a beam for the provider settings okay you can see that there are a lot of information a lot of changes that you can do we have just defined the issuer you can change the authorization endpoint token endpoint jwk certain points so if you want to configure any of the end points over here you can configure the endpoints okay but by default the standard endpoints you will get these are the beans that i have provided now you can see that the issuer i have provided is http or server colon 9000 so if you see 9000 that is the 9000 port of my hot server itself if you go to the application.aml this is my auth server currently and i pass the url for that so now this particular server url you can define in your host files okay so what you can do is you can go to the terminal and if you go to cad slash private etc host file okay and here you can see that this is the host file that you if you want you can change this host file and here you can see that by default the localhost for 127.0.0.1 would be there and i added one more entry for the host as the oauth server over here that's the only thing that i have implemented so this is the confusion that you have to add for your odd server to work with that particular url so i hope this is clear now so the configuration for the authorization server is done now we need to do the configuration for the basic spring security as well for this so let's add the default spring security configuration so let me just add one more configuration file and i'll just say default security config now you might be wondering there are a lot of changes and a lot of complex things here but don't worry these are very simple and this you have to do only once once this is done once it's set up you're good to go always so this is the default security config and we need to enable web security and here i am just adding the configuration simple okay if you see here i'm just adding again the security filter chain and i'm getting the http as the input parameter what i'm doing i'm just changing the authorized request so i'm just doing that all the requests coming here has to be authenticated okay any request has to be authenticated with default form login for the authorization server that's it okay simple thing now a lot of configurations are done for the odd server very little things are left so now we have defined the custom user detail service like this is the user data service that you have to use to validate the user we define the authorization server config like how the authorization authorization server should work we also defined how your basic security should work like all the requests should be validated so now one thing is left is your authentication provider like authentication manager how you should be managing your authentication so whatever the user object from the custom user detail series i created right from here now with this particular details with this user that i've created i need to validate the credentials that i'm providing from the input so whatever the input that i'm providing that has to be validated against this users right whatever the users that i have mentioned so i need to define the custom authentication provider as well so that the users are validated again so let me just create the configuration for that so let me just create this service and i'll just say custom authentication provider i'll annotate this with service and this custom authentication provider will implement authentication provider okay and we need to implement the method as well that is the authentic kit okay these are the implementations that we have to provide now how we can authenticate we need the custom user details service as well so whatever we have defined over here so let me just inject that private custom user retail service i'll just auto wire it and i'll also need the password encoder over here so let me just auto wire it private password encoder and now this is the authenticate method where in which we have to customize it okay so let's do this so let's get the username password string username equals to i'll get authentication.get name string password equals to authentication dot get credentials dot tostring now user details object we need from the security user details equals to custom user detail service dot load user by username and yeah we need to pass email so email we see our username we'll get the object of the user details let me just make it to user that is better now we need to validate the user so let me just create a method check password where you are passing the user and password okay and let's create this method and this is your raw password okay let's implement this if let me rename okay check password i don't know why i make this much spelling mistakes okay now if password encoder dot matches raw password with user dot get password return new username password authentication token okay where we need to pass user dot get username user dot get password and user dot get authorities else return new written new bad credentials exception let's say bad credentials okay throw simple so yeah you can see that we are just authenticating okay with the authentication manager over here and we need to add the support as well so let me add this return username password authentication token dot class dot is assignable form authentication okay so this authentication has been handled over here so you can see that simple thing authentication is handled now this custom authentication provider we need to bind okay so let's do that so let me go to the default security and let's bind this over here let me create the object private custom authentication provider okay i'll auto wire it and let me create the bin of authentication manager public void bind authentication provider auto wire it and i'm just injecting authentication manager builder auth and this authentication manager builder dot what is the authentication provider there's the custom authentication provider okay so we just bind this custom authentication provider to our authentication manager builder that's it you can see it's simple looks difficult but simple so now your auth authorization server is ready all the configurations are done it can handle all the requests now we have enabled everything now we need to register our client we need to add the configurations in our client to talk to this authorization server okay as every authorization server will give you the details to handle everything in your system we need to do that so if you go to this authorization server config you can see that these are the register client repositories these are the details that we need to handle so this is our spring security client here we need to handle everything in our application.yaml currently we have the spring data source on jpa now we need to add for the spring security oauth so let's add that i'll just copy the details and i will explain you everything if i type there will be some error in the indentation and we might waste a lot of time so let me just copy the details after the ddl auto update i'm just copying every details over here okay so now you can see that it's part of spring security auth 2 and we are adding the client now now after this client these are the custom things now we need to handle custom is registration so this is the name of your client okay we are adding the registration client and the name is api client oydc okay provider is spring now this spring provider i will get into details the client id and secretary is the api client and secret this is the same thing that we have defined over here that is the api client and secret okay api client and secret that is the api client oydc authorization current type is authorization code this authorization code we have enabled you can see that authorization code we have enabled grant type then redirect uri now this redirect uri is standard http your server name your port slash login slash auth to slash code and registration id your registration id is nothing but your api client ydc okay and the same uri whatever it is configured over here the standard format you can see over here okay http one two seven zero dot zero dot one eighty eighty login was two cod and api client ydc that is the client over here that you have defined make sense right now now the scope scope is open id for your authentication as we have implemented as we've added the open id as well and the client name api client ydc and now the below one you can see it's for the api client authorization code where the provider details client id and the client secret we have mentioned the same authorization current type is authorization code and the redirect url is 127.0.10.1 colon 8080 authorized once authorized this is the redirect api it will be redirected to okay and the scope we have defined is api dot ready so this is the scope that we are going to define and the same thing we have defined you can see in the authorization server config you can see that api dot read scope and the other one was odc scope.open id the same thing we have defined over here that is the open id scope and the provider you can see the provider spring issuer url it's http colon or server caller 9000 if you come back over here you can see that we have defined the issuer over here that is the or server 9000 so the same configuration we have defined over here similarly you can define according to the name that you have given over here so this is the name according to the name everything you have to provide over here so if you come you can see these are the two redirect url you have mentioned over here that only you have configured okay and this redirect url is nothing but the standard format that you have to give based on the client id or the client name that you are giving registration id so this is the configuration now the next thing you need to configure is your web security so if you go to the config we have created the web security config here we have enabled the web security and we have added the security filter change where for the http we are disabling this urs and csrf and we are adding the authorized http request and we are permitting all the urls these all the urls we are permitting but other than that what all the other urls we have to be authenticated to go into that okay so let's add that so i'm adding one more and matchers slash api slash anything anything coming with slash api slash anything has to be authenticated okay and we need to add the configuration for our server as well now dot auth to login we need to add now for this to work we need to add the authorization client as a dependency so let's add the dependency so i'll go to the spring security client and i'll go to the pump.xml file and i'm adding one dependency and this dependency you can see it's for boot starter auth 2 client so this will be my all stock line now so now if i go back to the web security config i'll be able to add let me stop the server and invalidate the caches so everything is refreshing so give the oz to login and order to login and you need to give the login page which login page to redirect so we can define our two dot login page and we need to pass the url so the standard url we need to pass that is slash auth to slash authorization slash your registration id so whatever the registration id that you have defined right if you go to your application.yaml that is the api client ydc so you will be giving api client ydc your login page dot auth to client customizer dot with defaults okay with default configuration we are enabling everything that's it so this is the configuration that we need to add now slash epi right so if you go to the hello controller so let me just add the slash api slash hello over here okay so this is the api that we are going to call and it's just returning hello welcome to daily code buffer okay so let me just start the watch server so your odd server is started and let me start the client as well so i started the client as well okay now you can see that it's connected let me just let me just go to the browser okay now let's go to the local host let me just open the debugging tool we'll go to the networks let me just close this okay and let me go to the localhost dt slash api slash hello for this my request should be redirected to the authorization server for authentication okay and here you can see that it has been redirected okay now here i need to provide the authentication here you can see that it's redirected to the alt server called 9000 slash login page and here you can see that your hello controller was there right here hello api it was called and it was sent to the epidc this is a url you can see that auth 2 authorization slash api client ydc and and you can see that the authorize was called with the response type client api sorry client id so scope information state information redirect uri everything is passed the same flow that we have seen with the playground right that these are the api these are the end points will be called okay and after that it's been called the authorized we need to get authorized so what i'll do i will add the details so first if i add any details okay and if i try to sign in you can see that no user found so this is a particular flow that will happening so it has to be authenticated okay now if i give the correct information if i go to the my sql okay if i get the nickel over here okay if i pass nickel gmail.com and the password for that we had kept was 789 okay so if i go back to the browser okay if i do 789 and if i sign in you can see that it has been redirected back okay if i go to the slash api slash hello you can see that i'm getting the proper response now okay hello welcome to daily code buffer now if i want to get the logged in user information that also i can get using the principle so let me just add that as well so if i go to the controller hello controller and here if i inject the principal object principle from the java.security and here i'll just say hello and i'll just define principle.getname let me restart my client okay my client is restarted now let's go to the browser let me just open the incognito mode and i'll just do localhost 8080 api slash hello okay you can see that i am redirected back to the login page and if i give the proper information let me just copy the email id okay and i'll give the password 789 and if i click on sign in you can see that i'm redirected back i'm getting this error because i have not defined this particular endpoint but instead of this if i go back to api slash user sorry hello you can see that i'll get the user as well that nicky let gmail.com is signed in okay and as i have defined everywhere as 1.127.0.0 instead of localhost if i hit this url instead of localhost okay let me just close this let me just open the incognito again and if i hit this i'll get the login page let me just give the nickel information over here and if i do 789 then it should react to the correct page you can see that i'm getting the correct page now right it's been redirected correctly so this way you can see that we have implemented the auth 2 with open id authorization server and the client as well so it both of them can interact with each other and only the authorized resources are allowed now what if you have a resource server as well so your resource server is there where only the authenticated user can access those authenticated resources and if you want to access those resources using your client how to handle that so let's create the resource server let's create one more application add into our project and let's go around how to fetch the data from the resource server as well so let's try to do that let me just close this uh let me go to the star.spring.io and just do com.daily code buffer artifact s oauth resource server packaging is jar jar version is 11 okay and here what i'll do i'll just add the web dependency i'll add the spring security dependency and i'll add the auth resource server dependency okay that's it let's invite the project and add an intellij idea so yeah let's generate it open in finder unzip it let's copy this okay let's go to intellij idea and add as a module in our main project let's go to pawn.xml file i'll add the author resource server and move on reload projects here you can see that this is the watch server now let's configure the oauth resource server as well so what i'll do i'll just first change the application.properties to application.yaml and i'll just do server.port as 8090 and i'll add the configuration for the spring security as well so what i'm adding i'm just adding spring.security.oauth2 this is a resource server jwt issuer url is auth server 9000. so this is my issuer url so i just configure this as a resource server now we need to handle the basic spring security as well so let's go ahead and do that so here with the java let me just create the new package and i'll just say this is a config package and within this config package let me just create the java class and i'll just say resource server config and i'll enable the web security here we need to create the security filter chain bin so i'll just define security filter chain and this is a bean now you might have noticed that we have everywhere in all the application we have defined the security filter chain okay and i'll just define the http security now we need to configure this as the same way we have configured in our all server and the client as well so we'll just define http dot mvc matchers now all the api request okay we are targeting and should be authorized request dot mvc matches slash api slash all the epa request and here we need to add the exception okay let's add the exception dot access we need to provide the access and it should have the access only so here you can see that we are calling the method that access only has authority api read so here you can see that we have defined this scope okay so whenever we are defining the scope for the authority we need to define as scope underscore and whatever whatever the scope it is so we are just handling the api read now if there is multiple we can add the multiple access over here so this is the api read that we are defining dot and auth to resource server or auth 2 is a resource server dot jwd okay and we need to return http dot build simple so here you can see that simply we just defined the security filter chain where we are authorizing all the request where scope is api dot feed now let's create the resource or the api for this resource server okay so what i'll do i'll just create one package and here i'll just say controller inside this controller let me just create one java class and i'll just say user controller annotate with rest controller okay and let me create one method public string of array get users return new string and here i'm defining multiple users okay let me just define shabir nikhil shivam and let me annotate with the red get mapping slash api slash users okay you can see that the simple api that we have created now suppose this is the api provider this is the resource server okay and now in your client you want to call this api but it has to be authenticated right it has to be within this scope whatever the scope we have defined if you're passing this scope and it's matching with the scope then only we should be able to get the details so we need to configure our client to handle the web client so we'll be using the web client to call this particular url and to find the data so we need to configure our web client as well so let's go ahead and do that if you go to our spring security client and in the palm.xml file in the pom.xml file we need to add the dependency of the reactive spring as we are going to use the web client now this is nothing but you are calling one of the apis that is behind the authorization server that is your resource server you want to call those resources you want to utilize those resources to utilize those resources your web client has to go around get authenticated and should get you the data that's it right it's simple as that whatever the api that you are directly calling from the client and if you want to call another api from the another resource server it has to be authenticated it has to be within the scopes that you have mentioned then only you should get the details so that's what we are trying to implement so let's add the dependency for that so let me go to the file over here within the dependency after the watch to client i am adding two more dependencies and you can see that it's a spring web flux dependency and reactive unity dependency so we can use the web client so now as we are going to use the web client we need to configure it as well so let's go ahead and configure it we will create the configuration class for that now this all things you can see whatever i'm configuration i'm adding that is only one time configuration so the only challenging thing to understand is that configuration part in the starting but once you add the configuration once you get the hang around of it it's very easy to implement the other things so as i need to configure the web client i'll create a new class that says web client configuration okay and i'll annotate with address configuration okay now now there's a default configuration okay you can directly add the configuration so i'll just add the configuration so you can directly utilize it so yeah you can see that i've just added the configuration let me put all the classes so okay i'm sorry i just added the webcam configuration at the wrong place so let me just delete from here let me just ctrl x from here go to the src in spring client in java config here i need to add okay and from the pom.xml file let me just correct it out if i have done any mistake now it's all good in this form only i've added okay make sure that if you're working with multiple projects this type of things happens this this type of issue happens so make sure that you are adding at the correct place so you can see that it's just a filter function added and it's applied that web client will be austral client to configure okay os2 is configured to use and here you can see that this is the authorization client manager where it is using the authorization code refresh token and all those things so this is just the default you can see it's just a default implementation you just copy all these details you just enable the beans web client and watch to authorization client manager and you're good to go you don't have to do anything now once this is implemented we can use web client to call that particular api that we have added in the web in our resource server okay so let's do that so let's go to the controller let's go to the hello controller and here we can call that api so let's do that so right here am creating one method that is public string of users okay and you can see i'm just passing as a guide mapping and slash api slash users and here we need to inject oauth to authorization client okay and which authorization we need to annotate with registered auth to authorization client okay so we need to bind it so which particular so if you go to the client okay if you go to the resources application.dml this is the one api client authorization code this is the one that directly we are binding that it will be using the api client as the client id secret the authorization code the url the scope all this information for our authentication for our resource server okay so let's go over here and let's define this that this is the one that we are going to use hope so now it is visible now we need to use the web client to call that so let me just auto wire the web client as well so i'll just do private web client and i'll auto wire it now return this dot web client dot get dot uri so we need to pass the uri so whatever is the uri this one http 127.0.0.1 colon 1890 that is the port number that we have defined in our resource server and slash api slash user is what we have defined as the end point to get the resources okay and then we'll define dot attributes or to authorize client okay so in the attributes that you have to define is server watch to authorized client exchange filter function okay this is what if you go to the web client this is what you have defined right so that one we have defined and let me just do the static import and here we'll define the client dot dot retrieve dot body to mono this is of string array dot class dot block okay so the error i'm getting is because of the attributes it should be attributes okay all right simple thing okay now this particular method is ready it is trying to get the data from the resource server that we have defined and after authenticating authorizing i am getting the data so now let's start the server i'll start the what server first then let me start the resource server as well i'm sorry the resource only started let me start the watch server as well spring client as well okay so yeah you can see that everything is started now if i want to call the hello controller slash api slash users it will try to call this particular resource server that is behind the authorization server as well after authenticating with the proper scopes only i'll get the resources so let me just go to the browser let me open the incognito window i'll just use this slash api slash hello instead of that i'll just define users okay it should be redirected to the login page as it was intended then i'll give the user information and password is 789 and here you can see that it is asking for the consent from the resource server that you should be authenticated you can see that epi client what is the api client api client is nothing but your client if you go to the application.dml api client this is your client right and what it is asking you can see there is one to access your account that is this one nickel gmail.com the following permissions are requested what is it scope only we have defined api read so we'll just give the api read consent and submit the consent and you can see that i'm getting the data over here so you can see that my resource server is behind the authorization server once the consents are there after that only i'll be able to access those resources so that's how the complete flow with the auth to an open id for authorization server resource server and the auth client works so if you want to understand more in depth about everything i'll add the documentation link in the description below so you can check that out i'll also link the different articles where i have read about it i'll link everything in the description below so you can check that out and there are different flows as well like we just use the authorization code flow there are different flows also available so you can try and implement those flows as well but the fundamentals are same just focus on the fundamentals just try to understand everything and learn accordingly ideally there will be very less chances where you will get to implement all this kind of securities because nowadays there are a lot of third party tools available like octa or xero like gmail github and everything right so most of the times people will be using that only and it is suggested to use it because they've done a lot of work on that the tools are really good so we can directly without worrying everything we can directly get all those security features and i'm also not a security expert by any means but this is what i have understood and i've implemented and is also not a particular flow that you will be implementing the production there are a lot more extra features there are lot more extra configurations that you have to do within this as well to make your application more secure so this is all about the oz 2.0 and how to implement auth 2.0 with spring security and open id connect in your springboard application now if you want to know more about the how to deploy this particular application in the kubernetes cluster and how to automate the deployment in any of the cloud provider as well and you want to learn the kubernetes in depth then check out these videos on the screen so go check out these are really good videos
Info
Channel: Daily Code Buffer
Views: 169,365
Rating: undefined out of 5
Keywords: oauth, openid connect, spring security, spring boot oauth2, spring boot, spring security with oauth2, oauth 2 sprig security, spring security with oauth, spring security oatuh tutorial, spring security oauth2 tutorial, oauth spring security example, spring security oauth example, spring security oauth2 example, oauth2 example, spring security oauth2 tutorial example, spring boot oauth2 example, spring security using oauth2 in spring boot, oauth2, oauth 2.0, oauth tutorial
Id: MOCeQYbQPPU
Channel Id: undefined
Length: 71min 15sec (4275 seconds)
Published: Sun Feb 20 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.