Use google authentication for your application (Oauth2)

Authentication is the most important part of the each and every web application. There are two ways that can be used to do authentication. First one is to maintain your own database and authenticate users from your own authentication provider. We have to do additional works to implement and maintain those code and databases. Next option is to authenticate users by external authenticators like Google Sign-In and Facebook. The main advantage of this is that, you don’t have to manually create users in your databases and also it will take less amount of time rather than creating your own authentication provider.

This is the logic behind the google OAuth2 Authentication

Let’s start the tutorial.

First, Register your application in google

  1. log into Google API Console with your email address.
  2. Choose Credentials on menu
  3. Then click Create a project button.
  4. Create credentials for your OAuth client ID by clicking the appropriate button.
  5. Provide URLs to your application that are authorized to request signing in through Google Sign-In. If you want to test it locally, typing http://localhost:8080 should work.
  6. Now you will see Client ID and Client secret. Cope them into some secure place. you will need this later.

Now go to Spring Initializr page and create spring boot project with following dependencies (Web, Security, Cloud OAuth2).

First, create class which contains all the configuration that we need to do.

Now, I will create new Rest Controller call which return authenticated user details.

We need to create application.yml file inside the resources directory. Which contains your client secret, client id, server running port and etc.

Index.html file

Now we have finished the implementation. Let’s run the application.

First try to click get user button. It will show an error. Next Click login button and then try get user button. Now it should show authenticated user details.



Software Engineer at Creative Software

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store