Spring Boot with Google Sign-In
By: Yatheesan Chandreswaran
Tags: Spring Boot, Authentication, Google Sign In, Web Applications, Spring Security

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.

authentication process

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.

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.

Google cloud console

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.

Google cloud console

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

Google cloud console

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.

Google cloud console

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

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.

pom.xml file

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"

xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">

<head>

<title>Welcome</title>

</head>

<body>

<h1>Welcome Page</h1>

<p>Welcome to Spring Security</p>

<form th:action="@{/logout}" method="post">

<input type="submit" value="Sign Out"/>

</form>

</body>

</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

package com.example.googledemo;



import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;



@Configuration

public class MvcConfig implements WebMvcConfigurer {



@Override

public void addViewControllers(ViewControllerRegistry registry){

registry.addViewController("/index").setViewName("index");

}

}

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.

Spring default login page

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.

application property file

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

Protect API Endpoints

package com.example.googledemo;



import org.springframework.security.config.annotation.web.builders.HttpSecurity;

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;



@EnableWebSecurity

public class SecurityConfig extends WebSecurityConfigurerAdapter {



@Override

public void configure(HttpSecurity httpSecurity) throws Exception {

httpSecurity.csrf().disable().antMatcher("/**").authorizeRequests()

.antMatchers("/", "/index.html").authenticated()

.anyRequest().authenticated()

.and()

.oauth2Login().permitAll()

.and().

logout().logoutSuccessUrl("/");

}

}

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.

index.html file

Whitelisting the home page public

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

.antMatchers("/home").permitAll()

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

GoogledemoApplication.java file

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

Console output

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

Build console output

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.

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

Google sign-in page

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

Web app index page

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.

Google sign-in 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.