Keycloak - A gentle introduction to Keycloak using Vite+React, NodeJS

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
key clock is an open source authentication Service so what it means is it allows you to implement authentication and access control related services in your web application now there are other auth providers in the market like all zero and OCTA but these are paid Services whereas click look it's open source as in it's completely free the other thing about key clock is it's self-hosted whereas r0 and OCTA these are hosted on their own servers so when you integrate OCTA or all zero in your web application you route the user to their servers where the authentication happens and after that the user is redirected back to your service so aug0 and octo takes care of authentication on their own servers whereas with key clock when you if you choose to implement it you have to run it on your own servers it might look like a lot of work but it's really not it's quite easy to set up and it's quite easy to configure so in today's video I'm going to show you how to set up quick look and how to configure it and we're also going to see a demo where we integrate it with a react app generally when we talk about all services we only think of login and logout but there is so much more to it generally these all services fall into a domain called identity and access management and within identity and access management there are several branches like authentication authorization user Administration and and so on and so forth so the reason I'm discussing these points is because key clock allows you to do all these things within your application so that that makes it really really powerful so let's explore each of these you know let's explore what these services are so authentication is quite easy to understand it just talks about login and log out and session management and single sign-on and you must be familiar with these terms and social media integration so what is social media integration you must have seen some websites where you can sign up with your Google account and login to the application and access it without having to create any new ID so that's what social media integration is so geek look allows you to integrate Google or Facebook or Twitter into your application so the user this allows user to login to your app using the using Gmail or Twitter credentials so that makes it really convenient for the user right they don't have to create any new ID or remember in a new password so it's quite it makes it convenient next is user management so Key Club gives you an interface to manage the users as in you can perform all the user administrative related tasks using that interface like creating the user or deleting the user or exporting the users all it doesn't it doesn't allow exporting users but there's a workaround which we'll discuss in this video but yeah I mean it does give you an interface to sort of manage the users like you can set the password expiry time or you know you can reset the password or give a temporary password and allow the user to change it to whatever they want so yeah all these things come into user management now speaking of authorization a lot of users get confused between authentication and authorization so authentication only deals with login and logout whereas authorization is is describes what the user can see or cannot see in your application and what the user can or cannot do in their application so we achieve this by assigning roles to the users so generally when you're creating a platform not every user is the same right you might have an administrator who needs elevated access or you have just have someone who's just subscribing and you know you just want to explore the content so they might need limited set of access so we achieve this segregation of Duties sod stands for segregation of Duties by assigning different roles to the user and thereby restricting what they can and cannot do on your platform last one is Central user repository it just means you know you can simply manage your users it's not that relevant but yeah because key clock is self-hosted you can run it on your own server and you can integrate it with all the applications that you run within your ecosystem right you might have you might just have one web service or you might provide different services so you can simply manage all the users that way the user can use a single credential to login across all the platforms so it makes it really convenient all right uh that's a brief summary of identity and access management now let's get into the technical so I'll show you how to spin up a key clock server we're going to use Docker to spin up the key clock server if you don't have Docker installed on your machine maybe watch some other video get it set up and then come back to watching this video also you don't need to be an expert in Docker I'll try to break down the commands that I use and make it as simple as possible all right to spin up the server we just need to run the single command that's it so let me break break it down so what this command does is it downloads the key clock image from Docker Hub and then we set certain parameters like the admin ID account and admin ID password and we also do a port mapping because Docker runs on its own virtual OS we have to do a port forwarding so we map the adid port on our machine to the ADHD Port of the docker container and that's it I'm going to change the port though I don't want to run it on 8080 I want to run it on my own custom Port maybe I'll try 4000. but yeah that's it so let me copy this command Cody obscore terminal do a right click let me change the port to 4000. and I'm also going to run this command in detach mode so detach mode frees the terminal that way you know I don't have to keep this terminal open while key clock is running that's it hit enter you can see that the image does not exist on my laptop so it's downloading from Docker hub and once the download is complete it'll spin up the key clock server with the IDS admin and password also admin that's it because we ran this command in detached mode after all the steps are done the terminal is freed up if you open Docker desktop under containers you will see the key clock instance running and if you click on it you can see all the logs but yeah it is running if you open port 4000 on your machine you will see the cake look interface first we need to log in to the admin console the username is admin and password is also admin and then we'll see this interface there are so many options we look at each of them in detail later in this video the first thing to do is create a new realm when you log in for the first time you will see the master Realm by default and Rel is nothing but a grouping for all your settings and it's advisable not to change the settings in the master realm instead create a new realm and configure all your settings there the reason it's designed this way is because let's say you have two different applications and you want one app to have certain settings and another app to have a completely different all settings so in that case instead of creating two different key clock servers you could have just one server but have two different Realms thereby you know isolating the settings to their own application so yeah first let's create a realm I'm going to call it my Realm and after we create the realm we need to go to clients and we have to create a new client and I'll do a demo shortly where we'll create a react app and connect to this realm and I'll show you the authentication and in that app we connect to the new realm that we created and we also need a new client so create a client and call it my client just just click on Save that's it so all we did here is login create a new realm and also create a new client there are so many other settings but there's no point in me talking about it right now instead what I'll do is I'll Implement a basic authentication and then I'll show you how these configurations affect that login page okay yeah all right now I'm going to create a simple react app that connects to key clock server for Authentication I'm going to use wheat to create the react app I'll give the project name as demo key clock and I'm going to use react JavaScript hit enter now let's go to the demo key clock server first install all the dependencies I'm also going to install a package called key clock Js we'll use this package to handle the Authentication that's it let's start the server all right this is the standard wheat react template I'm going to delete all the unnecessary files and modules all right now that everything is cleaned up let's start with the code I'm going to create two folders one to host all the components and one to create the hook we're going to create a hook called use auth and we'll handle all the key flow created functionality inside that hook we'll create two components inside this folder one is public the other one is protected the names are self-explanatory the user when not logged in sees the public page and after login sees the protected page I'm creating inside this user hook I'm creating a state called is login to keep track of the user login status in the app module we'll import all these components that we just created and like I said when the user is logged in will show the protected route if not will show the public page as you can see we are seeing the public page because the default state is set to false if I set it to true you should now see the protected page so that works well let me change it back to false and now let's implement the key clock functionality we only want to run this user effect once when the component first loads so the dependency array is set empty when we instantiate key clock instance we need to pass certain options so we need to pass the URL and Rel and the client ID remember we just created the realm and clientele right we need to pass these parameters here so I can write the values here but that is not the right way to do it instead I want to create an environment variable put in all the values there and then and then import them here so first one is the key clock server earlier when we spun up the server we were running it on the 4000 Port so that's the link and then my Rel that's the realm ID and then my client that's the client ID after we create the environment variables we need to restart the servers for these to take into effect so I'm going to stop the server and start it again that's it now if I go to use auth now let's import all the environment variables thank you after instantiating client we need to run the init method with the option login required that mandates authentication whenever the component loads which is an async function that Returns the odd state so let's do that the way this works is if the user is not logged in then the user is redirected to the key clock server for authentication and after that he's returned back and then it Returns the odd state which we are setting here if the user is already logged in then it will not redirect it will just simply return the alt state which again we set it here so that's how we handle authentication it's really simple right now when we go back to the page you can see the redirect happened but it says invalid redirect URI so I left this bug intentionally so that I can show you how to configure this setting in the realm so now go back to your key clock server and if you go to the clients okay I think I log dot editor login again go to my realm yes myrel and go to clients and my client if we scroll below we need to specify the valid URLs here only auth request coming in from these URLs are accepted so valid yeah web origin yes now click on Save now let's try again awesome so now you can see this works so we need to set now this is like a security feature right we don't want any app to connect to our kick log servers we only want our applications to connect so that's how we enforce this restriction all right so now that we have everything set up we look at the different key clock settings and how they affect this login page all right now that we set up the application and connected it to Key cloak let's see how we can customize the screen and how these different configurations affect the login page okay first you can see on the top you see the project name here and let's say I want to change the project name to something else okay so if you go to realm settings and you have an option called HTML display name if I change it to let's say atom and save it that updates the project name here now if we go to the site and refresh the page you can see that it's changed to atom so you can set the project name or you know any name of your choice here to update the login page also if you look at the page you don't have an option to register or forgot password and all this stuff you only see an option to sign in right so again it depends on your project requirement right let's say you don't want to allow the users to sign up right you only want to you want to create the users in-house and only give access to those users but let's say you want to make it open right let's say you want to enable sign in so you do it by going to login again realm settings login and let's say you turn on user registration right now let's see what happens if you go back to the page refresh the page you see there's an option to register now so that's good so yeah there are so many customization customizations here that you can you know toggle to customize the screen so let's look at each of them yeah I'll try to cover as much as possible but yeah it's it's heavily customizable so let's say you have return on this option forgot password right so this allows you to this you see this gives you an option to reset your password and what else do we have here so yeah remember me yeah now you can save your password in the browser yeah so that's pretty neat what else do we have email as username so let's say you want the username and email to be the same and you don't want to differentiate them then you can turn on this option so it doesn't yeah you can now it just earlier you might have seen here username and email now it now it just says email so yeah that's it what else uh yeah if you go to the email tab this is again now this email section is helpful if you want to enable some kind of email functionality in key clock so let's say when the user signs up or you you have turned on email verification is mandatory right in that case you want to send out an email after the registration asking the user to you know verify their account so in that case you need to set up your SMTP server here then you can change some settings here like from it from email address display name and all that stuff so this is applicable for email options I need an SMTP server to be able to show you this I don't have it at this moment so I won't be able to cover this but yeah I mean most of these options are pretty self-explanatory okay then you can go to theme so here you can customize this theme so there are just two themes available if I select the base version and save it looks pretty bland so let me refresh this you see it looks pretty like it looks like all the CSS has taken away so yeah let's turn it back to kick log click on Save yeah now it looks now the previous uh styling is restored so yeah Keys let's see what we have okay so we will talk about Keys later in this video when I show you how to restrict access to your routes on the backend server so more on this later events again localizations I've never used it security defenses yeah let's say you want to put some headers right on your API calls then you can do it here sessions yeah this is useful so how long do you want the session to be active after authentication right so those kind of settings you can configure here so there's that and tokens yeah we don't same thing about the tokens right so under the hood key clock uses Json web tokens to handle the authentication so you can configure the lifespan of these tokens over here so these are a bit too technical so I don't want to get into the details but I'm giving you a high level overview okay client policies yeah okay user registration that's it okay so that's pretty much it so so yeah this is how you can customize the login page now that we saw how we can customize the login page using the settings let's try to create a user and login to the application I'm going to create the user first from the admin panel so go to the user section and click on create new user so let's create a user called yes associate bitcoin.com to give the first name as Satoshi last name that's Nakamoto and you can select different actions but yeah we'll just leave it blank for now and click on create we also need to give a temporary password for the user to log in and let's go to credentials and set password make it temporary the temporary option is turned on and I'll set the initial password as one two three four five click on Save yeah set password awesome so let's the user is now created if you go to the users tab you will see this user now go to the login page enter the email address and set the initial password click on sign in awesome so you are now prompted to change your initial password so that's the beauty of Click look right you can set an initial password and we can make the user change their initial password so if you were to do it yourself we would have to write a lot of code to handle this but because we're using click look the whole process is simplified for us so I'll set the initial password to one two three four five six click on submit after we enter the password you are logged into the application but you can see that the page keeps refreshing right if I just refresh this you can see that the page keeps on refreshing and if I stop it if you notice carefully you will see the state and session state in the URL so that means the login is successful but for some reason our application is not able to retain the login State the reason this is happening is because of the way uh use effect works under strict mode if you go to main.j6 you can see that it runs react is running in strict mode and there is an issue with use effect in strict mode so what happens is in strict mode there's there's been a change in the react version 18 I believe where use effect runs runs twice so we have to this piece of code runs twice which is not what we want so we only want to make it run once so we do that by using a user F so I'll just call it user f I'm going to use user F hook to achieve that I'm going to create a reference variable called is run I'll set the default value to false and inside use effect I'll check the value of Israel if the value is set to true I'll just return if not I'll set it true and then the rest of the code is executed so the way this works is first time it's run the value is still false so it comes to this line the value set it through the whole code runs and next time when it tries to run again because the value is true it just returns it doesn't execute the rest of the code so that's how we prevent use effect from branding twice awesome so you see the protected page so that means you are logged in now if you go to the key clock panel if you go to clients go to my client under the sessions tab you will see all the active sessions so these are all the users who are currently logged into your application so again this is again the power of key clock right if you let's say you want to kick some user out of your application you can just click on sign out and the user is forced to log out of your application so if you go back to the page and hit on refresh you will be redirected back to the login page awesome so it works so if we go to the users yeah now let's do one thing let's try to instead of creating from the admin panel let's try to register a user from here click on register and I want to create a user called Sam and last name is bankman and let's put the email as Sam bankman gmail.com whatever and set the password to one two three four five six click on register so you will see the protected route so the reason this happening is because key cloak immediately after registration it logs you into the application so that's why you're seeing the protected route so you are logged in as Sam bankman right now if you go to clients and again my client you can you can see it over here so under sessions tab you can see Sam is logged in you can just log out here and if I refresh this page you will be redirected back to the login page awesome yeah there is one other thing that I wanted to show you so we have been looking at all these different customizations under the realm tab right there is also another customization under the authorization tab sorry authentication tab if you go to policies here you can customize your password policy so let's say you want to make the password to a minimum of certain characters or you want to have special characters uppercase and all that stuff so you can you can set it over here so if you select this drop down you have different options to customize so let's say minimum length I want eight minimum eight characters lens so that's it and I want to put an upper case where is uppercase here uppercase at least two uppercase or one uppercase whatever and I want to have special characters like how many number of special characters you want to have in your password and click on save so this policy is automatically enforced through this section so let's try to create another user so click on register and let's say create Chuck Norris Chuck Norris gmail.com and I want to set the password to one two three four five six right this should stop me if I click on register yeah we get an error that the password should at least have one special characters right so I'll say say at the rate whatever one two three four see at the rate one two three four now it will fail it because it doesn't have 12 characters right so click on do we have 12 characters your minimum eight characters I think it should fail click on register it should at least have one uppercase so it's doing all these validations for us so we don't have to write any client-side code or any of that stuff to make this validation click look handles it for us so that is what makes it so convenient for developers and yeah that's the beauty of cake look there is one last thing that I wanted to show you I deleted the password policies to make it easier for me to show you that is the two-factor authentication yes key clock does support two-factor authentication and we can enable it during registration so the way to do it is go to required actions and there's an option called configure OTP so it's not turned on by default so you have to make it a default action so when you click it it turns it it makes it default so if you go back to the login page and register every time a new user tries to sign up the user is prompted to configure two-factor authentication support so let's let's try that let's try to register a new user right let's say Caroline Allison and Caroline at red alameda.com and let's set the password at one two three four whatever one two three four and click on register all right so now you will get this two-factor authentication code scanner so let me try to set it up on my phone and scan QR code got it so the code is Pi nine seven one eight zero and let's call it a Firefox yeah click on submit you see the protected route so every time I log in let's let's try this that right so if you go to clients and every time I log in I now have to enter the two Factor authentication code so I want to test it out so let's log out Carolyn let's copy this time out so if I go back to the page refresh uh go back to the login page and one two three four click on sign in so see you're now prompted to enter the two-factor authentication code so yeah it works as expected four to eight and only then will I be redirected to the application so perfect so we looked at all the customization settings and we looked at the password policies and also how to turn on the two Factor Authentication all right so far we have looked at how to secure the front-end side of things we've looked at the customizations on the login page and two-factor Authentication and so on and so forth now let's look at how to secure the backend server now the concepts that I'm about to discuss are slightly Advanced you need to have an understanding of node.js and express server to proceed further but I'll try my best to explain things and keep it as simple as possible now if you're familiar with node.js and express server you know that securing an application is not just about securing your front end but also securing the routes that you offer in your backend server now you can secure your routes using keyclock if you go to realm settings and go to keys here you can access the public key of the of this realm so you can use this public key to restrict access to the routes and also tailor the content of the route to the login user before we go ahead and delve into the code I want to take some time explaining how the private and public key works so private key is used to create a token whereas public key is used to verify the token so in this case there's a public key and private key map to this realm but key clock doesn't reveal the private key to us we don't need to know the private key uh the less we know the better because the way this works is whenever a user logs in key cloak takes the private key and it creates a token for us and then in the backend server we can use this public key to verify the token now the token that got generated no other private key can generate the token only the key that's mapped to this realm can generate this token so that way we can be sure that if the token is valid that means the user did log into the application so that that validates the authentication side of things and then using the public key we can verify two things we can verify if the token is expired or not so if the token is expired that means we force the user to log in we also get the user that the token is created for so that way we can take the user ID and tailor the content of the route to that particular user I hope it makes sense if not don't worry about it once we implement the code all of this is going to make sense to you I'm just going to set up a very basic Express server I'm not going to explain too much because it's going to take a lot of time so I'll quickly create a simple Express server with a route that returns some documents okay let's get going all right I've just created a simple backend server and I started the server using node mod so that whenever I make changes to the code it's automatically restarted and let's now create the express server as you can see the express server started on Port 5000 now let's create that out okay I just created this route called documents that returns some documents that I just stored in an array ideally you would be getting documents from a database but to keep it simple I'm just returning the data from this variable as you can see the route Works we're able to see the data when we call the API now let's go to the react app and pull in this data I need to install a package called axios to make the API call so let me just install it I'm gonna start the server again I'm going to use use effect to implement that API call and we also need userf to make sure that user effect only runs once just like we did before for now I'm just calling this API and just logging the data onto the console let's see if this works I need to log in to test this stay protected let's open the console as you can see there's an error right so a react app is running on Port 5173 whereas our backend server is running on Port 5000. we need to specify the proxy connection so that the API calls go through 5000 Port so let's do that we specify the proxy through the wheat config file in the react app what this means is whenever we use the documents route the API calls are forwarded to this URL so that means you can have different routes using different URLs so that's the beauty of wheat right you can configure multiple proxies for the same app so that's really convenient now let's close this let's go back to the app and hit refresh looks like I need to restart the server to take this into effect let's let's go back to the server hit refresh awesome so that works so we now see the data logged to the console now what I want to do is instead of logging the data to the console I want to show them on the screen you'll understand in a short while why I'm implementing it this way so let's first show these values on the UI great so now you can see the data being displayed on the UI now what I want to do is instead of showing the standard records for all the users I want to assign different records to different users and depending on which user had logged in I want to show the records that are pertaining to that user so this is how we do it so whenever we log in uh key clock generates a token for us so in the react app first thing to do is get the token and then we need to include the token in every API call and in the backend server we will extract the token and identify if the token is valid and whether the user has logged in and then we provide the content that's specific to the user so let's do it so the first step is to get the token we're going to go to the use auth hook that we created and extract the token so that's it so we created a new state for the token and after the login we assign the token and we updated the return state so instead of just returning login we're returning the token and the login and in the main app module we're passing the token to this protected module and here we are passing the token with the API call now there's a better way of doing it instead of drilling down the props you can have some kind of centralized State Management but yeah because this is a simple react app I just want to quickly get it done with now if you go to the API call that we did and if you go to the request headers you can see we have included the authorization Bearer space the token so here is where you can see the token now let's go to the backend server and implement the authentication as in you know decoding the token and identifying which user it is I need to install a package called Json web token to handle the authentication so let's install and restart the server inside the routes I'm going to create a file called authenticate and here is where I'm going to implement the functionality for authentication I'm going to use it across all the routes so for now I just want to lock the token to the console so let's import this authenticate module and include it in the route since this is a middleware we can just pass it along with the route so so whenever the API hits the server it first goes through this authenticate code block and only when it's successful it goes through the documents uh the route where we provide the documents so let's go back to the page hit refresh now let's go to the console awesome so you can now see the token that is logged here now we need to decode the token so for that we need the public key so let's get that go to realm settings keys we need the RSA public key RSA 256 here just click on public key copy this and I'm going to pass it through environment variable this is the format to properly store public key so I just pasted it we're getting the public key from this environment variable now we need to decode the token using the public key so this is how we decode the token so earlier remember we took the public key of rs256 so that's the algorithm we are passing here and let's log the decoded value to the console and see what happens refresh the page so this is the decoded value let me expand this section a bit so this is the decoded value you have all this information available and what we're interested in is the email address right so you can see the email is Sam bankman gmail.com and this is how we identify the user that's logged in okay if the token was obsolete this verify step would have failed so that's how we fail the authentication and we force the user to log in again but yeah now that we have the decoder token let's assign uh the username to request.user and then in the document section we will have access to the username and then we can tailor the content to the user that's logged in we need to call next so that the code then moves on to this documents section where we provide the documents now here let's try that now let's get the email address here so constant email is equal to request.user again let's console log the value let's refresh this page awesome you have this email address here so now let's create some documents for each user so similarly let's create some more records for Carolyn that's it so now that we have different records for different users let's update this API to provide the data that's specific to the user that's logged in it's quite simple so instead of just sending the data we just send data off email that's it save if you go back to the UI and I just hit refresh so yeah I think this is what we see for Sam so if we go to the keyclock and the user section Sam let's log him out sessions here let's log out and if I log in now we see the documents for Sam if I log in as Carolyn hit refresh let's login as Carolyn awesome so now you see the document see a different set of documents right these are a gallon so the UI looks a bit crude but you get the point right this is how we Implement authentication in the backend server and tailor the content of the route specific to the user that's logged in finally I want to show you how to take a backup of key clock server most likely you'll be running keyclock on some kind of cloud provider like AWS and in worst case scenario if the AWS region goes down your server would crash and you would lose the data so it's a good practice to take a backup there is a drawback in key cloak in that it doesn't allow you to take a complete backup so let's look at the standard way to take a backup from the admin panel so if we go to realm settings under action there's a button called partial export when you click this you can select things that you want to include and hit export so here in this export it includes the realm settings groups roles and groups and clients hit export yeah it takes an export the drawback with this approach is you know it doesn't include users right so this is a big risk right you need to take a backup of users right you cannot afford to lose this one workaround for this is when you start the key clock server there is an option to connect key clock server to a dedicated database like postgres we didn't do it in this tutorial because I want to keep it simple but ideally it is recommended to have a dedicated database that makes the key clock server stateless and even if it goes down the users are still stored on the dedicated database but what if you're running it in this mode right and you still want to take a backup well there is a workaround it took me about a week to figure out there's no proper documentation on how to do it but yeah I'll show you the workaround so to take the backup we need to go to the docker container and go to the terminal go to the opt folder geek log bin and here you have the key clock shell script so we're going to use this script to do the export so this is the command to take the export I leave this command in the description I want to change the file name to all users and we just we give this flag same file so that all the users are exported into the same Json file so hit enter it takes a few seconds to do the export that's it now let's go to the folder yeah you see this file all users.json so that's the exported file now we need to bring it out of the docker container now to bring that file out of Docker we can use a Docker copy command and for that I need to know the container ID so we can get it by running the command Docker PS that gives me the container ID now the command to copy is Docker copy and then the container ID and colon and first we specify the source path and then we specify the destination path just want to give the file name as well and hit enter so you will see this allusers.json file here and you can see all the users exported from all the Realms so we know that the default realm is Masters so you will see the users in masterl and also the realm that we created importing the users is really easy let's delete all the users right so delete users yes so now we don't have any users so importing is really easy go to realm settings click on partial input and let's select the file and choose three users hit on import that's it close if we go to users the users are back and they are created with the same password as before so that's it so that's how you take a backup of users and import them back in the event of a crash there are a few things that I couldn't cover in this video like using roles and groups to implement some kind of access control and also social media integration if you go to Identity providers you can see that you can integrate Google or you know so many social media platforms into your web app directly so this is another thing that I couldn't cover in this video it's already quite long so let me know if you want me to cover these topics I'll try to make a video that's it for this video and I'll talk to you in the next one bye
Info
Channel: DeKay
Views: 31,996
Rating: undefined out of 5
Keywords: keycloak, authentication, nodejs, react, bitcoin, ftx
Id: 5z6gy4WGnUs
Channel Id: undefined
Length: 44min 25sec (2665 seconds)
Published: Sat Jan 21 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.