Pre-requisites:
- Setup project info in Google API Console. If you dont have any projects, add a new one.
- Make sure your OAuth Consent Screen have been configured correctly. If not, then now is the right time.
- Choose user type 'External' and click Create.
- Fill up your project's details. Make sure to use your real project name.
- You will need to insert a link for your application's terms of service & privacy policy. Fortunately, you can just use google drive links for these files.
- Unless you know what you're doing, only select these scope.
- Add test users.
- Review your changes and go back to the dashboard.
- Click Create credentials > OAuth client ID.
- Select Web application to create a new client ID.
- Add your server URLs in Authorized JavaScript origins or it wont work. In my case, adding localhost does nothing and I needed to test my project on the server with working URL instead.
- Go back to the Credentials menu. Click copy client id on the OAuth 2.0 Client IDs table.
Front-end Code:
- Make sure to load the required library
<script src="https://accounts.google.com/gsi/client" async defer></script>
- Then insert the button wherever you need it. Make sure to replace DATA_CLIENT_ID with the client id you copied earlier.
<div id="g_id_onload" data-client_id="{DATA_CLIENT_ID}" data-callback="onSignIn"></div>
<div class="g_id_signin" data-type="standard"></div>
- The attribute data-callback="onSignIn" is referring to my javascript function I've set below. You can replace it with your own function.
Back-end Code:
- Basically the onSignIn function have already received the response we need from Google. The back-end function just needs to process it into manageable array form before we insert/update it into our database.
- You can see below that I have split the response ($credential) into three variables. The one we need is the payload that contains the user's data. Since the data is encoded in base64 form, I made sure to decode it and turn the json string into an object first.
- After this function return its values back to onSignIn function, it will redirect the user to the login page. In this page, we actually check for the session's google_signin value and set the user as logged in without needing for passwords.
References:
- https://developers.google.com/identity/gsi/web/guides/fedcm-migration
- https://www.codexworld.com/login-with-google-account-using-javascript/
Comments
Post a Comment