Building a Public OAuth2 Client - Single Page Application using Javascript and Keycloak

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone welcome to javaras in the previous video we created a confidential oath to client application also known as server side o to client and we used spring boot there is another category of oath to clients which is public client and public clients is an O client which cannot store client secret confidentially or securely the source code of public client is accessible to the user directly or indirectly for example the single page applications and mobile applications both are public clients and since these types of apps cannot store the client secret securely so that's why we don't use client secret for them in this video we will build a single page application which will be a public o to client there are many JavaScript Frameworks to build single page applications or SPS like angular react view we can create it using vanilla JavaScript as well that that means without using any JavaScript framework and that is what we are going to do in this video but before that first of all we need to register our single page application with any authorization server or o provider so let's do that in the next part of the video Welcome everyone to the first part of the video in which we will register a new single page application to the authorization server in the previous video we used GitHub as authorization server or oath provider for cont confidential client I would like to use the same application as single page application as well but I was not able to do that since GitHub required client ID and client secret to give access token and since we don't want to use client secret we cannot use gab as o provider for single page application then I considered OCTA for single page application it is possible to use OCTA as o provider for your single page applications without using client secret OA uses one more security measure which is pkc Pixy that means proof key for code excange but I wanted to cover pixie in the later videos so I cannot use OCTA also as oath provider so I looked at Key clock as an authorization server which allows single page applications without client secret and without pixie mechanism you can go to key clo.org to view the instructions on using keylock first of all we need to download and install key clock and key clock requires Java in order to run but we will use another way we will use Docker container to run the key clock so click on get started and then click on Docker here you will find a command to run the key clock inside a Docker container below this command you will find all the details which you should know in order to configure the authorization server I will not run this command since I have already done that I can use Docker PS command to see all the running containers and we can see this container so this is the container which is running key clock inside it and by default and by default it is running on port 8080 so I can go in the browser and go to Port Local Host 8080 now here click on Administration console and the default username and password for admin is admin and password is admin now we are inside key clock authorization server admin UI in the top left corner we can see a drop down so from this drop down we can choose the realm now what a realm is so irm is a collection of applications and resource servers and authorization server which contains the same set of users that means a user can can access all the application using the same account there is this default realm which is master so you should never use this master realm to create the applications you should always create another realm so click on this drop down and click on create realm so you're just give the realm name and it it will create a new realm for you I have already created a realm called o to demo so I will select it from drop down and now I am inside o to demo real now click on clients so here you can see all the clients which you have in under this real some of these clients were already there in order to create a new client click on create client button here now since we will be using all two so for the client type we need to select open ID connect and you can give any client ID I will give public client and here here you can give the any suitable name description for your client and click on next now since we are building single page application and we don't want to use client secret so we will keep client authentication off and since client authentication is off so there is no point in client authorization now let's look at authentication flow so this standard flow means authorization code flow and we want to uh activate it so keep it marked keep it checked now there is another flow which is direct access grants we don't want to use that direct access grants means your application will store username and passwords of the users and whenever you need an access token you will send username and password to the authorization server and you will get back one access token we don't want to do that so I will uncheck this box and click on next now here you you can specify any root and home URL so let's just specify example.com uh this doesn't matter but ideally this should be the URL of your web application now we need to enter some valid redirect uis this is where uder will be redirected back after successful login so let's define HTTP Local Host since we are developing application in our machine now we need to specify the port as well so I know that my application will run on Port 50001 so I will specify 50001 here and all call back so you don't need to specify them here once your application is up running then also you can specify the redirect Ur let's add another redirect Ur which is HTTP now instead of Local Host I want to register 127.0.0.1 as well 50001 or so that if the user visits our page on this or this URL then both should work now we need to specify the valid post log out redirect uis as well so I will specify the same here but I will remove all call back from the URL copy it and paste it here and remove it now web origin now this is very important since we are using single phage applications and in order to get the access token we will send the request from our browser Now browser or our application is on different origin and the authorization server is running on different origin since the these two Origins are different so there will be a process called course that means course cross origin resource sharing and by default browser doesn't allow same sending requests to some other origin unless the course is enabled now here the course will be enabled on the server side now here we need to tell the server that for which Origins it should allow the course so here we need to is specify the our website origin since our web app will run on this URL so we need to WID list this URL we should be able to send fetch requests to authorization server from these URLs 7.0.0 point1 if we don't specify these here then we will get course error now after specifying all the details which just click on save button and one client application will get created I already did that so if you go to clients so this is the client application which I have created public client so here you can see all the basic details of the application all the URL configurations and everything is here so you can modify the details here as well now that we have registered our single page application on authorization server now let's go ahead and build the actual single page application that we will do in the second part of the video Welcome everyone to the second part of the video where we will create the o to client application in the previous part we have already registered our application in the authorization server so this is the ID of our application now since it is a single page application or in other words it will be a public o to client so we don't have client Secret now let's go ahead and build the actual application so we are going to build a single page application or Spa we are not going to use any framework to do that we will build it using vanilla JavaScript but in order to serve our single page application we still need a server when you deploy your single page application on any uh web hosting service then that takes care of that server but here we actually need to start a server that will our single page application for that I'm going to use Python so I have Python 3 installed so if I type command Python 3 m HTTP do server help so this using this command we can uh start a simple HTTP server and we can specify the port and many other things first of all let's create a directory well where we will store our single page application so I inside o to directory let's create a directory called public client spa and let's go inside this directory now I I will use Vim in order to work on this project but you can use any ID you want so I just created an index.html file now let's write something inside it okay so I have created one index.html file inside public client ASP directory now let's uh in the another window I will go to that public L HP directory and I will use this command python 3-m HTTP do server to start a web server now we can give a port so I want to use port 50001 because we have registered Port 51 here and I want to serve the files which are in current directory so I will say d dot now the server is serving all the files which are in the current directory now we can verify that so let's go here and open a new tab go to Local Host 5001 and you can see hello there being printed here okay now let's start working on it so we want to have one D element here so here I can just say welcome to both to public client demo app and after this I wanted do with ID content and let's not put anything inside it I created a directory called assets inside that directory called JS inside JS there is a file called MJS and let's include this main.js insert index.html file so just before closing of body tag we can have script tag here so let's do that script I will choose module type and Source will be Source will be assets Js men. Js is okay now let's go to main.js and here say let's access the DU with ID content content D equal to document do get element by ID and the ID is ID is content and after that let's try to change the content inside content de content do inner HTML equal to it is changing just that and let's go here refresh the page and you can see it is changing so that means uh this is working now we need to we need to create a link there which will say like uh link your account or something like that but before that we need to check whether we already have an access token or not if we don't have any access token we saw a link to uh connect the account so for that we can access we can we can store access token either in local storage or in session storage so here I want to use a local storage so let's do that con access to equal to locally storage. get item and item the key is access token so if access token that means if we already have an access token in that case for for now let's just print the access token so content d content. inner HTML will be and say access token equal to access token otherwise but it will be false because initially there is no access token otherwise we will create an authorization URL and after that we will create a link so so uh let's do that for example let's say count authorization URL so this is the URL where users should be redirected and after that content D do inner HTML will be it will be a href will be authorization URL authorization URL and here I can say connect your account and I will close the add tag now I want to have a .js file which will have all the utility methods so let's uh go here and create a new file called .js and inside .js let's create a method called generate authorization URL so I will say export generate authorization URL so this will be a method and it will return the authorization URL for authorization URL we need few things like we need redirect URL we need client ID we need State and we need authoriz and fund now it's good to put them in a file in a separate file so let's create a file so here I will create a file called constants doj in constants in constants do JS file we need to have some constants so first of all we will create some constants which are related to the authorization server so let's put a commment here related to both server and let's export const authorized endpoint now if you go to key clock server here in under config there is realm settings here you will find all the settings which are related to your realm you can change the settings and since we are using o two let's go to open ID Ando configuration and here you can see all the configuration which we need for authorization server now here we have authorization endpoint we have token endpoint so these are the two endpoints which we will be using so let's copy authorization endpoint from here and put it here now the another variable will be const token end point so it should be const and its value will be this toorent point so let's copy it and paste it here now after that we need some constants which are related to client application so which will be client ID and redirect Ur So so let's do that so let's put a commment related to client server client application the first is client ID so in this case we have created a client and the ID of the client is client public client so this is the client ID here we uh gave the client ID our but in most of the cases the client ID is generated by the authorization server so let's put the client ID here and after that export const let's create a redirect URI suffix redirect URI suffix and which is O call back so so this is what we have provided here o call so what we will do is we will uh append this redirect URS suffix after the current domain of the application and then we will have the full redirect URL okay so we'll save it and now let's go to .js Method so here we want to create this generate authorization URL method now let's generate the redirect URI const redirect URI will be so first of all we need to get the uh current domain or origin where the our single page application is running so we can get that using window. location. origin window dot location do origin and after that we can append the redirect URI suffix redirect URI suffix and you can see it has been automatically imported from constant so let's put do JS here we have redirect URI now we need to create state so in order to create a state uh we need to generate a random string and then we will put that inside local storage and then we will include that state in the authorization URL so let's do that so for that let's create a method called Generate random string now let's generate a random string of uh length let's say 16 con state will be Generate random string and we need to give length let's give it length 16 and L will be default l in that case now we have state so now here here we want to clear the local storage so that there is nothing inside local storage local storage do clear and after that we want to put this state inside local storage do set item the key I want to use is State and the value will be State now let's return the string so I will return one string here it's format is authorized endpoint authorize endpoint after that we need some query parameters the first is client ID and its value is client ID which we have stored in the constants file and then it needs response type and the value of response type is code then it needs state and its value is the state which we created just now and then redirect Ur redirect underscore U and its value will be the redirect urri and after that we need some Scopes let's give open ID email and profile so we will return this authorization URL now let's go to main.js and here authorization URL will be we will call the generate authorization URL method generate authorization URL so it will generate an authorization URL and that authorization URL will be put as value for href attribute in Anchor tag and then when the user will click on connect your account link he will be redirected to the authorization URL okay we don't see anything uh there may be some errors okay we have error fail to load resource the server responded with a status 4 404 yeah because in the client side when we do this type of import we need to add do JS after that do JS and let's reload now now we can see connect your account being printed here okay you can see we have been redirected to the authoriz server in order to login but we don't have any user uh to log in so let's create that so go here and I already told that all the client application inside one realm shares the same set of users so the user is created for realm so go to users and there is this user so I created one user already if you want to create another one click on add user and you can provide all the details and you can create a new user so I will login with this username so it's username is user and it has some password so I know the password and username so user is the username and this is the password I will click on sign in now when I clicked on sign in I got back to this URL locost 5001 o and call back because this is a redirect URL and also I got some query parameters in the response like State then session State issuer and there should be code somewhere yeah and code so we are in uh in the next part of the video we will see how to handle this state and code in the query parameter and how to put them in use welcome everyone to the third part of the video in this part we will handle State and code in the query parameter of redirect URI we have been redirected to the/ or/ callback path so we need to create this path let's create a new file in the folder with you o call back and index do HTML inside body let's create a new element here I give it any ID and I will say error du and let's give style color I will say red so that if we get any error while uh getting the access token we will display that here let's create a JavaScript here and I will say o allb back. JS now here let's access that error du error du will be document dot get element by error de and now here um we have the code and get in the query parameter of the URL so we need to get that in order to do that we can say window dot location dot search so this will give us a string representation of all the query parameters and we want to convert them in url search parameters so let's do that con query equal to new URL search perms and I will pass window do location do search as a parameter now let's get the code and state const code will be query. getet code and const state will be query. get State and now for now let's uh put Cod and state in error du so error du ER inner HTML will be code equal to code and State equal to State okay let's now let's include this o call. JS inside index.html file which is inside callback uh directory so here after after this D element Let's uh write a script tag script type equal to module and Source equal to first we need to go One Directory up then another directory up and then we need to go to assets then JS and then both call do JS now let's save it let let's refresh this page and we can see redirecting being printed here so there is something something wrong so redirecting title okay so yeah so we have not closed this title tag here close it save it then refresh now you can see this is the code and this is the state and if you go to local storage so let's see let's go to St storage here then local storage and you can see this is the state uh which we created this is the random string ag1 12T a12t so this state is correct and we have this authorization code which you need to send back to the authorization server in order to get the access token so and that we will do in the next part of the video Welcome everyone to the fourth part of the video where we will use authorization code to get the access token from authorization server let's go to O call. JS and here we have the code and state now first of all let's do some validation so the code should not be empty or null or undefined so not code then error D do inner HTML will be code is not present otherwise let's if this state is not present or if state is not equal to the state which is present in the local storage so local storage. get item State both of these should be same but if they are not same then also we have error so I will say error do inner HTML equal to invalid State otherwise we will go ahead and fetch the exess token f access token now for that let's create a method so let's create a method con F access token it won't take any parameters now let's say there is already uh one access token present in the local storage so we want to invalidate that so let's do that I say local storage dot set item access token we will set its value as null now we need to create an access token URL and I will do that in another file which is .js so let's go to .js here let's create a method called generate access token URL so export const generate access token URL so it's very easy so the access to token URL is nothing else but the token Ando itself so let's just return that return token end point and we are good here so now let's uh go to uh o call. JS now here we we have the access token URL so let's do that const access token URL equal to generate access token URL now since we have access token URL now we need to send some information to access token URL in order to get the access token we need to send some uh we need to send that information as part of URL form and coded information so for that we create a new URL search parameters so const URL search perms equal to new URL search forms and here we first the first parameter is client ID and its value will be the client ID which is inside constants and don't forget to add JS after constants otherwise we will get some error okay now here the second is Grand type and it value authorization code the third is code which is the actual code and which we have access here then redirect URI and which is window dot location dot origin plus redirect U suffix so we have created URL search perms and we can send those in the um access token URL so let's do that I will say const response will be AIT F we will use f API the URL is access token URL and so there are some option so the request method should should be post and in the body we will just say URL search perms and we need some headers as well the first header is content type and the content type should be application X www form URL encoded so I will say const token response equal to response do Json and let's print that here so console do log token response and if token response dot access token so if there is a field called access token inside token response then we want to put this access token inside local storage locally storage do set item the key is access token and the value is token response dot access token and after that if everything is successful then we want to redirect the user to the homepage so window dot location do replace the new URL is window dot location do origin so we want to send the user to the homepage and this would be a sync and it is not used so let's use that here so let's just call this function so I will say fet access token let's go here if we refresh it and go to go here think here also yeah so we are importing util here and what we need to do is instead of util we need to have .js now refresh the page now we have access token equal to undefined because we have set access token here but we don't want to do do that so instead of setting access token here we want to uh clear it so locally storage do clear then let's refresh it yeah so access token is undefined initially go to local storage and let's clear the local storage delete now connect your account now again why is the access token undefined so we were getting that error because the response do J is as synchronous function so we need to use a wa here and let's refres it now connect your account and we can see the access token being printed here so we are able to get the access token from the authorization server in the next part of the video we will see how to send this access token to the resource server as part of the request in order for authorization welcome everyone to the fifth part of the video in the previous part we were able to retrieve the access token from the authorization server using authorization code now we need to send request to some resource server and I already mentioned in the previous videos that resource server and authorization server may be same as well in many of the scenarios and in the current scenario as well we will send the request to authorization server only but the process is same whether authorization server and resource server are same or not now what which resource do we want to use so we want to use this user info endpoint so many authorization server provide user info and point where you can send request with access token and you can get the uh information about the user so uh this is the user in point point so I will just copy it and I will put that Endo in constants file so let's see in the constants file and since this is also related to the o server only so you can consider consider it as related to all server resource server it's the same thing so let's make related to the resource server export const let's just say user info hand Point equal to this one now let's go to main.js now if we have access token uh we are just displaying access token here but we want to do something else as well let's create one uh method here const page user information this will be a s because it will need it needs to send some uh request and it will take something called access token so access token or we have access token so we don't want to send anything now we need to send a request to user info Endo so let's use f for that F user info point and we have imported constants do JS okay that's good user info and point and and we need to send some else as well because otherwise how we'll be able to authorize our Sal we need to send some information in order to make authorization so the first is what is the method of the URL so the method is get only and we need to send some headers headers so in order to send access token um we can send it as authorization header so the header header name is authorization authorization and its value will be b error space then the access token so access token and then we will uh uh get the respon so let's do that count response equal to a wait F this this one and after that let's convert this information into the Json so const user info response equal to a response do Json now let's print this in console as console console do log user info response Also let's display this so I will say content do do append so we want to append the user info so let's append Json do stringify user info response now let's save it but uh uh we are not using this function anywhere we need to use that so let's do that here here we can say t user information let's save it go here refresh the page I we are getting some error 401 unauthorized let's go to network so we are sending request to user info and we are sending this request order authorization be error and this thing right here but we are getting 401 unauthorized and the error is error is invalid token error description token verification failed so what we can do is go here and let's delete it and refresh the page connect to your account okay now we can see we got the user information here so this is the user information sub so sub is basically user ID kind of thing then we email verified through this is the name this is preferred username this is given name family name email so we got everything which we needed now the similar strategy Works uh if we want to send request or some other endpoint uh which is related to the resource server as well we just need to include the access token in authorization header along with bror keyword that's it for this video in this video we have seen how to build a public single page application or to client from scratch without using any library but you should never do that in real life projects you should always use some libraries which are tested and secure till now we have seen how to create client applications but we don't know what what is going on on the authorization server from the next video onwards we will try to create some authorization servers obviously we will not create fully fledged authorization servers but we will have some understanding of how the authorization servers work in nutale thank you for watching please like share and subscribe bye
Info
Channel: Java Rush
Views: 116
Rating: undefined out of 5
Keywords: oauth2, oauth1, authentication, authorization, authorization server, oauth provider, identity provider, oauth2 client, client application, public client, access token, authorization code, client secret, authorization code grant flow, redirect uri, client id, state, security, javascript, keycloak, localstorage
Id: Qi0dC3Wb-aE
Channel Id: undefined
Length: 48min 6sec (2886 seconds)
Published: Mon Mar 04 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.