Spring Boot with Google Sign-In

This article provides basic steps to enable google sign-in with a simple spring boot web application. You will learn how to enable google sign-in authentication with spring security.

The code for this example can be found in my Github repository

You need the following prerequisite

A text editor or IDE

JDK 1.8 or the latest

Gradle 4+ or Maven 3.2+

Google account

Basic understanding of OAuth 2.0 Authentication process

There are two ways to enable authentication and authorization to web applications. The first option is to implement, create, and maintain a user database with the Authentication process, the second option is to use an external authentication framework.

OAuth2 Authentication

OAuth 2.0 is the industry-standard protocol for authentication and authorization. OAuth 2.0 grant a third-party web site or application access to the user’s protected resources. The below diagram explains how the authentication process works.

When the user requests an API through a web client which requires an authenticated user is redirected to the Google Sign-In page. One of the request parameters is the client ID, so google knows which registered application the user tries to Sign-In. If the authentication process is successful, the user agrees on the scope of data to be shared with the application. The browser received an authorization code. at the moment browser knows the user has successfully signed in, but again API application validates the authorization code sent from the browser. Google sign-in system confirms the code and sends backs an access token. This token will be used by the browser or client application to query the requests.

Register the Application in the Google Sign-in portal

To use Google OAuth 2.0 as an authentication provider, let us create a web client in Google cloud console. To enable google auth with spring boot you need a client identifier and shared secret which needs to be passed as a configuration parameter to the application.

1) log in to the Google API console using your Google account.

2) Enable Gmail service, Analytics services, and Google+ service APIs in Google cloud console.

3) After enabling the above services, navigate to the credentials section on the left menu, and choose the OAuth client ID option.

4) If you're accessing this service for the first time, then you need to create a project.

5) After selecting the OAuth client ID next, choose the application type as “Web application” which will provide the authorized javascript origins and authorized redirect URIs form.

6) After choosing the application type, let's provide the application name, Authorized javascript origins, authorized redirect URIs, and select the create option.

7) finally, you will find the Client ID and Client secret in the OAuth client created section. Copy the client id and client secret for later use to configure the web application.

8) Now we have successfully created the auth client in the google cloud console.

Simple Web Application

Generate Spring application using Spring Initializer. The Spring Initializer helps to generate a spring boot application quickly with needed dependencies. This project needs the spring web, Thymeleaf, spring-security, and spring oauth2 client. The above image shows the configurations set up for this project. After generating the project, you will get a zip file with the given artifact name. Unzip the project file and open it using an IDE. This project uses Maven as the build tool. You can use Maven or Gradle to build the project. The following image shows the project structure and pom.xml file that got created for the Maven project.

The dependency section shows a list of selected dependencies for this project.

Add an Index Page

Before moving into the security section, let us create a simple web application with an index.html home page. You can use the Thymeleaf template to create the views. Create the index.html file inside the following location: src/main/resources/templates/index.html

After creating the template view needs to configure the pages based on Spring MVC. Let us create a view controller and configure the Spring MVC. Create MvcConfig.java file in the following location: src/main/java/com/example/googledemo/MvcConfig.java The following code shows the implementation of Spring MVC configuration

This class overrides the method of the WebMvcConfigure class addViewControllers() method and binds the views with the controller. Now lets us enable the spring security and secure this web application with the user login.

Now all the users can view the index page. Suppose if you want to secure and restrict the index page from unauthorized users, the index page access needs to be secured by forcing the user to the google login page.

Spring Security dependencies are already added to the pom.xml file during the project generation.

Secure the application with Spring Security

Let's create a SecurityConfig.java class and annotate it with @EnableWebSecurity to enable the Spring web security support to the Spring MVC. After enabling the spring security, run the application and access it in the browser. You will see the spring default login form.

Now you need to override the spring default security methods to apply the application authentication logic. You need to extend WebSecurityConfigurerAdapter class and overrides a couple of its methods to set some custom specific security access configurations. The configure(HttpSecurity) method needs to override to define which URLs need to be secured and which not.

Enable Google Sign-in

Now we need to configure the generated client credentials to the application.properties file in the resources folder. The spring security-related prefixes start with “spring.security.oauth2.client.registration” and follow with client-related custom properties.

After adding the above application properties for the google client, this will enable all the required beans for OAuth 2 login.

Protect API Endpoints

The above SecurityConfig.java class provides the implementation of the security configuration. here you can notice oauth2Login() element which provides a number of configuration options to enable the customized OAuth 2 logins for different providers. The above configuration shows that all the endpoints and URL paths are protected with authentication and the user will be redirected to the login page by default if not authorized. Finally, the logout URL is also configured with logout() which clears the current session of the user if the “/logout” URL endpoint is triggered and redirected to the base path again after successful logout which will again navigate the user to the login page.

The index.html page contains the logout function which will trigger the “/logout” endpoint and navigates the user to the login page after the successful logout.

Whitelisting the home page public

We can whitelist any views from the authentication by providing the permitAll() permission as shown in the bellow configuration.

Build and Run the application

Last you need to Build and Run the application. You can run the main class using the IDE from the location: src/main/java/com/example/googledemo/GoogledemoApplication.java

You will get the following console output with a successful application startup.

Build the executable JAR

You can build the executable from the command line using the Maven build command. You can build a jar with all the necessary dependencies, classes, and resources files to run the demo app. Use the following command to run the application.

mvnw spring-boot:run

You can package and build the jar using the following command.

mvnw clean package

Console output of the successful build

After building the jar then run the build jar from the target folder location.

java -jar target/googledemo-0.0.1.jar

Once the application starts executed, access the URL in the browser.

http://localhost:8080

The application will redirect the user to the Google login screen and provide Gmail login details.

If login successful, the User will be redirected to index home view

After accessing the welcome page you can able to sign out by clicking on the sign-out. Spring security revokes the authentication and you logged out from the web application. After logged out the application will redirect the user to the Google login page.

Summary

This article discusses basic google authentication with spring security for Web Applications in spring boot. By following the steps you can build a simple web application with Google login and learn how to configure basic authentication to web applications. The code for this example can be found in my Github repository.

Written by

Senior Software Engineer at Zone24x7

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