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
Let’s start the tutorial.
First, Register your application in google
- log in to Google API Console with your email address.
- Choose Credentials on menu
- Then click Create a project button.
- Create credentials for your OAuth client ID by clicking the appropriate button.
- 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.
- 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.
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.