Securing Your React Website with Google reCAPTCHA: Step-by-Step Tutorial on v2 and v3

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys welcome back to another video I am niage and in today's tutorial we will be unlocking the secrets of Google recapture if you have ever wondered how to protect your website from Bots while also keeping it userfriendly then Google recapture is your friend so recapture is Google's security service that protects your website from spam and abuse it uses Advanced risk analysis techniques to tell human and Bots apart so why is recapture that important well if you want to be able to successfully distinguish between real users and Bots that's where recapture steps in to save the day now the important thing is how can you keep your site secured without annoying your users with excessive and annoying bot checks for your real users that's the beauty of recapture it offers security without sacrificing user experience let's dive into how recapture versions 2 and three make that possible so recapture V2 or version two is the familiar I'm not a robot checkbox sometimes it asks you to identify images it's userfriendly but can be a bit intrusive in this video you will see how you can add this to your website recapture V3 however is a newer more adaptive solution it run runs in the background and assigns a score to each users's interaction determining if it's likely to be a human or a bot this means no more puzzles for your real users I will now walk you through a stepbystep guide to implement both recapture V2 and V3 in a front end application which also has a back end that we will use to verify the recapture tokens but the first thing that we need to do is we need to set up the recapture keys for both V2 and V3 to do that you will just have to open up the homepage of Google recapture and then click on this V3 admin console on this top navigation bar when you will click on it then a page will open up which will prompt you to register a new site so you have to enter a label value I am just going to enter my recapture and the type that I'm going to select is the V2 because we are going to implement the I am not a robot checkbox first into our react front end and for domain I'm just going to add Local Host for now because we will be testing our code locally and we will not be deploying it on a server yet so let's click on submit so that the V2 type of recapture site will be created now when a recapture site is created then we are given two keys the first one is a site key the second one is a secret key let me just zoom this in so the site key is meant to be present in our front end code that we will send to Google along with all the requests the secret key is going to be saved or restored on This Server site which we will use to verify the tokens that the users will generate with their interaction with our front end now when we have the site keys with us let's take a look at the existing project template that we are going to modify to integrate Google recapture into the existing code so in this project there is react in the front end and Firebase serverless functions in the back end the front end you know why we need it it is the presentation layer for the users to interact with our application and the back end is to do any kind of stuff that needs to be done on the backend side so I'm just going to run this application on a local server so that you will see what is already there so let's type npm start so while the application is starting on a local server let's also emulate the fase function locally so that we will not have to deploy our changes every single time we are making a change in the function code so for that there's a command which I have created which is Firebase emulate so I will create another video to show you how to set up a basic template with react in the front end and fase in the back end and that same template is the one which I'm using for this tutorial video but for now just understand that we will be using the back end to verify the tokens or to confirm the tokens with Google to know that the token which has been generated on the front end is indeed a correct one all right so both front end and the backend functions are now available for testing on our Local Host so this is a login page or a login component right now there is no functionality associated with this component and when we will click on the login button then a request will be made to the Firebase function it will simply return that the request is successful and we will see a message login successful now where does Recapture comes into this picture what we need to do is when someone is logging into our website then we need to make sure that they are a real person and not a bot so let's get started integrating recapture V2 having a I am not a robot checkbox widget with our login component so the first thing that we need to do to render the widget is to create the widget itself now it's not like the widget is going to be created manually by ourselves Google has already done that what we need to do is we need to create a component in react which when used will render the widget so now let's first create the recapture Widget the first thing that I will do is I will create a new folder in the components folder with the name re capture now let's create a new file in it with the name index. jsx now in this index. jsx X first I will create a simple component and let's just name it as re capture now this component is going to accept a bunch of props but I will come to that later the first thing that we need to do is to load the recapture script into the browser from this component and to do that we are going to use use effect hook So within use effect we are going to run a function when the component loads for the first time now the first thing that we need to do we need to check if the window. G recapture object is available or not if it is not available then we are going to create a new script element and then add it to the documents head as soon as that is done the browser will start to download the recapture script so for that let's first create a script element so con script equals to document. create element this is just basic HTML and JavaScript code so the tag name is a script next we need to set the script. SRC value so the SRC value is the URL of the Javascript file that the browser needs to download and then execute for Google recapture you can find that URL in the document mentation or I can save you some trouble and paste it directly over here which is this one now we need to provide some parameters for this URL or for this SRC the first one is going to be an onload call back so this call back is essential because we need to know when the script is done executing and the gapture object is available with the window to be safely used to render the widget so for onload we have to provide the name of a function which is available globally in the window object I mean that's the important thing not in the react context but in the browser's context so I'm just going to call this function as on recapture load there is also one more parameter that we have to use which is render with the value explicit now let's set script dot async equals to true so that it's nonblocking and finally let's add script. defer equals to True again so that the browser will load truly important script first before it loads this one but if there is nothing else to load then it will simply prioritize loading the recapture script now finally we have to add um I'm sorry sorry document dot head. append child and we have to provide the reference of the script now if the recapture um object is not available with the window then we are doing this thing we are creating a new script element and then appending it to the head but if it's available then what we have to do is else if window do G recapture is available and let's also check one more thing with this and that is the availability of render method or render function just to be sure if it's available then we will simply set the state of our recapture component which will reflect that yes recapture object is available so to do that I'm just going to create a new state variable so const is recapture loaded and then um let me just fix this spelling first to recapture yep I think that's the correct one so set is recapture loaded equals to use State let's set the initial value to false when the component code has confirmed that it is loaded or it is already already loaded then it will set it to true so again let's come back to the else part so if jury capture is already available then we will set this state variable to true now remember I mentioned about the onload call back which should be available on the Windows context or the globally scope now what we can do is we can bind a react function with the globally available on recapture load function so that when the script will done executing then instead of the globally available function in the window our react function is going to be called so for that I'm first going to create a new function let's just name it as const on recapture load and what I will do is I will simply write window. on recapture load equals to to uh this on recapture load now when this on recapture load will be called then again we have to set this state variable to True which will simply indicate that the uh recapture widget has been loaded but because we are assigning something to the window there can be a possibility of memory leaks so when we will be returning from this effect function then we simply have to return a function which is going to unbind the windows um on the capture load function and set it to null so there goes your cleanup with the recapture component now when we will know that the um is recapture loaded State variable is set then we can use another effect hook so use effect this is going to run when this state variable will change and if it is true or or set then we can call Window do gapture do render but how do we render it where where do we store the rendered component and for that what we can do is we can create a new ref so for that um let's create a new const re capture ref equals to use ref with the initial value of null now what we can do is we can simply provide this ref as an argument so recapture f. current and we will also have to provide some options the options are going to be the site key so remember the site key and secret key which Google gave us for recapture V2 that site key we have to use over here so site key and we also need to provide the value of a call back so the call back is going to be the function so when the user will interact with this widget then a token will be generated by Google indicating the state of the interaction so that token will be received as an argument in this callback function and this site key and the Callback we are going to provide them as props so that this recapture component can be truly usable across our entire website now after this is done the only thing which is left is to return the recapture do current from this component and that's pretty much everything that we have to do for the recapture component now let's get back to our login component and integrate the recapture with our login component so the first thing that I will do is I will import the recapture component and then it's time to make some modifications the first thing is we will need to place the widget somewhere I'm just going to place it above the button which should be a close and enough um place for the user to interact with the widget so div class name let's set the margin top as four like other divs and then recapture the first thing that we need to do is we need to provide a site key site key right the site key is going to be our site key let me just copy it from the um recapture dashboard so click on this copy site key and paste it over here now for call back I'm going to create another function to receive the token let's call the call back function as um const handle token equals to token and now how do we or where do we store the token actually the question should be where do we store the token how do we manage it and for that I am just going going to create a new state variable for the token which can be called as const token set token equals to use State let's set the initial value as an empty string now while we are added let let's also create a new state variable for the um enabled or disabled state of the button because we only want to enable the submit button after the user has interacted with the widget and we have received um the the token to be submitted along with the email and password to the server or to our serverless function let's call it as submit enabled or set submit enabled equals to use State let's set it initially to I think false okay so now we have token and set Tok token so over here I'm just going to call set token and provide the value of token over here now when we have the token then what we want to do is we want to um you know set submit enable to true because we have the tokens value so use effect um let's provide the effect function this will be called when the token will be changed so if token has a length then we are going to set submit enabled to true and we can use this um set submit enabled value over here so submit enabled now as you can see we have a bunch of different attributes on this button like disabled onclick type class name but we also have to update the um the visual state of the button while the button is enabled or disabled now for that uh we can just make some change to the class name so these are all the Tailwind classes if you're wondering U what are all these values so if it is enabled then we have to provide a set of classes otherwise we have to provide another set of classes so if it is enabled then I'm just going to provide the uh background and H classes rest are common if it is not enabled then I can just provide a different background let's provide gray background let's also set the um cursor appropriately so cursor not allowed all right I'm just going to save it now and what else yep we need to provide the Callback so call back um not this one call back equals to Now call back is the handle token function so handle token and I guess that's everything we need to do now let's check if the widget is being rendered or not now it says recapture placeholder element must be an element or ID so let me check what went wrong with our code okay so there are a bunch of mistakes that I have done over here U while quickly walking you through along with the code so first first of all we cannot directly return the ref as um as a return value or as a renderable HTML so we have to set the ref property of this div and over here we have to provide this recapture ref as a value so what we intend to do is we intend the Google to use this div to render the widget and for that we have to provide the reference of this div so I have Associated this ref with this div so that that um its current is going to point towards this HTML div itself when it will be rendered now let's see if our code is working or not yep now it's working you can see the wiget is here and we also have the login button let's click on the I am not a robot checkbox now when it's checked it simply means that we have got the token and when the token is available then this login button is now enabled now it's time to send the token to the server and to do that um there is a handle submit function which is already um calling the Firebase serverless function so I'm just going to provide the token as an additional argument over here and that's pretty much everything we need to do from front end now we need to provide the implementation on the back end side and that is for the login.js function so over here right now nothing is happening only a valid true is being returned what we have to do is we have to return valid true or false based on upon the um checking of the validity of the token which we will do so the first thing that I will do is I will destructure the um all the different values that we are getting with the data so const email password and token although we don't need email and password for this tutorial but still let's just destructure everything next we will create a variable and let's just call it as success let's set the initial value as false now it's time to um store the secret key now the standard way to store Keys is in either environment variables or in a dedicated key manager but for the sake of this tutorial video I'm just going to save it in the code itself now when we have the key then we can simply call um const um recapture response but before we can call the Google's API to verify the token first let's download exos as well that we will use to uh make a post request so to do that I'm just going to create a new terminal and then CD functions npm install exos now while exos is installing I am just going to fetch it so con ex equals to require exos now let's get back to our um previous code so const recapture response equals to await exos um why is my keyboard not working not sure okay exos do Post because it's going to be a post request and then we have to Pro provide the URL that we can use to verify and the URL for that is this one again I'm saving you the trouble of you know going to the documentation and then finding out what the URL is but in any case this is the URL but we also have to provide the secret with the URL which is our um the secret key for v2 and we also have to provide the token which needs to be provided with the response um parameter so let's do that as well so response equals to token which we destructured okay now we have provided the key and token now it's time to check the U the validity of the token so for that I'm just going to check if recapture response. data do success is true or not if it's true then I'm just going to set this success equals to true and for valid we are just going to return success as a value now let's just save it so that the emulation will pick up the um the recent changes that we have done actually let's check if it's you know correctly loaded or not yep it's loaded correctly okay so now let's try and test our code if it's working so let me refresh this page again to refresh the widget as well now let's click on I am not a robot let's click on login and it says login unsuccessful so I guess the reason that the login is unsuccessful is because we have still not provided the secret key so let's copy the secret key from the dashboard and paste it in our code so I'm just going to paste it over here let's save it again now refresh the page click on the checkbox click on login now it says login successful with simp simply means that our token is now verified by Google and our back end has confirmed that the token that was generated was indeed generated by a legitimate person and not by a bot now let's come to implementing recapture V3 so recapture V2 provides us a widget it's an extra step um which the user has to interact with but with recapture V3 we can silently check if the user is legit or not in the background while we are making any request to the server so let's just do that the first thing that we need to do is to create a new site for recapture V3 and what I'm going to do is let's get back to the um you know what let's just start again okay let's click on plus over here I think that's how we can create another one yep so label is going to be my recapture I think it should be unique so I'm just going to use V3 now the type is going to be score based V3 score simply means that when the token will be generated after the call Google service to generate the token for the user interaction um then we will get a score and based on that score we can evaluate if the interaction is by a legitimate user or not for domain again I'm going to provide Local Host now let's click on submit so we have our site key and secret key again the same thing but this time we will not create a component to render a widget but we will need to silently check in the background and generate a token and for that I'm going to create a react hook so again getting back to our code and I will create a new folder in the components and let's call it as hooks now let's create another folder let's just call it as re capture V3 let's create a new index. GSX file in here okay so let's generate a template which is this one now I'm just going to call it as use recapture V3 okay now some of the things are similar to how we were building the recapture V2 component we have to load the script if it's not available and we have to do some things which are different as well so what we will do first is we will simply check if the recapture is ready or not so for that we are just going to create a state variable with the name is recapture ready let's provide the function name as well set is recapture ready equals to use State let's set the initial value to false and then same stuff use effect for effect function and then it will run uh when the component or the hook is Run for the first time so first we will simply check if window. G recapture is available or not if it's available then we will simply set set E Capture ready to true I think this spelling is not correct but I mean it doesn't really matter so and in the else part same stuff that we were doing in the recapture component so I'm just going to copy this entire code from over here and then paste it over here we will create a new script element but this time um the parameters are going to be different we don't need the onload um parameter for the call back and we also don't need this render explicit the only thing that we will need is a render parameter and its value is going to be the site key okay so let me just convert it into a template string the site key is going to be the prop so that this hook can be reusable and let's set async equals to true we don't need defer equals to true anyways and then append the script to the head but we will also need one more thing is when the script is loaded then we will assign a call back to a script load event so let's just do that when the script is loaded then we will simply set this set is recapture ready to true to let us know that this script is uh loaded now and let's do one more thing the site key can change so what I can do is I can simply use site key as the dependency for executing this effect function now the next thing that we will need is another function to execute recapture silently in the background for that I am just going to create a new function which is called as execute um execute recapture equals to let's use use callback because this hook can be reused so we can cache this functions implementation so use callback it's going to be an async function so async this is going to accept an argument for the action so we can associate the um you know silent fetching of token by using recapture V3 with an action so in our case our action is the login action I will show you how this can be done so action now in this function if uh we have to check if is um recapture ready if recapture is ready or not if it's ready let's also check for window. G recapture as well because there might be a RIS condition so let's just do that just to be safe so we will simply call return await um let's just paste it window. recapture do execute now we have to provide the site key and we have to provide the action as you know as an option it's optional you don't have to provide the action but if you want to uh you know be sure with which action the token was associated with then you can do that okay so now we will finally return the execute recapture and that is pretty much everything that we have to do let's return recapture V3 from over here let's just save the hook and now it's time to integrate this hook with our login component so let's open up the login component and what I'm going to do is I am just going to first you know comment out everything related to V2 so comment out this one as well let's also import um use recapture V3 and we don't need this token State variable let's also set the I mean we can you know enable the button all the time because we are going to do the silent background checking of the users legitimacy now um let's fetch a reference to the execute recapture function by simply calling const execute recapture equals to use um recapture V3 now we have to provide the site key as an argument now similar to V2 we can get the site key from the dashboard so click on copy site key and then paste it over here and next thing that we need to do is in our handle submit function before we you know call the backend function we simply need to call execute recapture to get a recapture token and for that I'm just going to write const um re capture token equals to await execute recapture and we can provide an action value I'm just going to provide login so when that is done we can simply set the value of token as recapture token and that's pretty much everything I guess we need to do on the front end side let me check again if there is anything else uh Noe I think this will do but we also have to make some changes on the backend function side as well so let's just do that so on the backend side um I'm just going to make some changes the first one is going to be the value of the success variable let's just set it to true if the um if if the confirmation with Google fails then we can set it to false and we will need to change this V2 to V3 and we need to use the v3's secret key which is this one so let me just paste it over here and then for recapture response I think it should be similar yeah recapture response should be similar to V2 apart from just using the correct key and what else yep over here we have to check if it's not successful but along with that we can also check if the recapture response. data do score is less than I think 0.5 can be used as a safe is score to verify if it's a user interaction or not or if a bot is trying to log in into our website we can check one more thing and that is the action that we used so if the action is not login if it's a different action if a malicious user is trying to you know generate the token from some other place then also we can set to success as false again same thing returning the value of success let's just save it let's see if there are no errors over here oh yeah there are actually errors um I think there is uh the need for some kind of Cleanup in our login component so let's just do that yeah that's what I was thinking I mean I must have missed something yep first of all we don't need this handle token function and then we also need we also don't need this use effect call over here and so yep let's not test our code so now I will click on the login button to see if our code is working it says login successful so we have covered a lot today from the basics of recapture to implementing both V2 and V3 on your website remember the right choice depends on your specific needs and user experience goals if you want to use V2 or V3 it depends on what your exact requirements are in the end if you found this tutorial helpful then please consider subscribing and hitting the like button share your thoughts or any questions in the comments below stay tuned for more content like this and I will see you in the next one
Info
Channel: Code Radiance
Views: 1,247
Rating: undefined out of 5
Keywords: Google reCAPTCHA, reCAPTCHA v2, reCAPTCHA v3, Web Security, Bot Protection, CAPTCHA Integration, Website Spam Prevention, reCAPTCHA Tutorial, Invisible CAPTCHA, User Authentication
Id: _JnaVeXIYEc
Channel Id: undefined
Length: 36min 38sec (2198 seconds)
Published: Sat Dec 30 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.