Email ico
Oauth Spring Boot

Login to Spring boot application via OAuth2 google account

Devendra Nationalwala | 25 Sept 2022

This tutorial will launch a spring boot application and restrict an endpoint with google authentication.

Let's create a new spring project through https://start.spring.io/

In dependencies, we need to add three dependencies: Spring Web, Spring Security & Oauth2 Client

Hit Generate button at the bottom to download the project. Import downloaded maven project in an IDE. Create a new class IndexController.java in your default package.

In index controller, welcome() method can be accessed without login on the following endpoint http://localhost:8080/ However to access restricted() method, you will be prompted for Google account login.

Let's create SecurityConfig.java class to secure the endpoints.

In application.properties, add google client id and secret.

To get this id and secret, login to google cloud console, click on Create Credentials

Select OAuth client ID in the drop down.

In Application type select Web Application. And enter name of application.

In Authorized redirect URIs, enter http://localhost:8080/login/oauth2/code/google and hit Create button.

You will see your client id and client secret on the next screen. Copy this id and secret in application.properties file.

Now you can run the spring application class SpringGoogleLoginApplication and try to access the following url: http://localhost:8080/restricted This url should redirected to google login page to authenticate.

You may download this Spring boot application here: https://github.com/devendrant/SpringGoogleLogin