• +94712452807
  • pubudu2013101@gmail.com
  • No 39, 2nd Lane, Dikhenapura, Horana
Spring Boot
How to Implement google authentication for your application (Oauth2)

How to Implement google authentication for your application (Oauth2)

Authentication is the most important part of each and every web application. There are two ways that can be used to do authentication. The 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 codes and databases. The 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
https://developers.google.com/identity/protocols/OAuth2. It is licensed under the Creative Commons Attribution 3.0 license.

Let’s start the tutorial.

First, Register your application in google

  1. log in to 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 OAuthConfig.java class which contains all the configuration that we need to do.

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

We need to create application.yml file inside the resources directory. Which contains your client secret, client id, the 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 the login button and then try to get the user button. Now it should show authenticated user details.

Leave a Reply

Your email address will not be published.