Spring Boot - Spring Security - Google OAuth2 Login - Example

Hello everyone, Today we are going to learn how to integrate the Google OAuth2 Sign-In by utilizing the Spring Boot application.

 Generate Google OAuth2 credentials from Google developer console

1. Log in to the Google developer console using your Google account

2. Navigate to the Credentials section on the left menu, and choose the OAuth client ID option


3. Choose the application type, In our case "Web application".


4. Then, provide application name, Authorized javascript origins, authorized redirect URIs, and select the create option


5. After clicking the create button, one modal will pop up with the Client ID and Client Secret.


Now we have successfully created the auth client in the google developer console

Creating a Simple Web Application

Now we are going to develop a simple web application using Spring Security and Google OAuth2

Project Structure:



Project Dependency(pom.xml)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.knf.dev.demo</groupId>
<artifactId>springOauth2google</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springOauth2google</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>


Enable Google Sign-in

We need to configure the generated client credentials to the "application.yaml" file.
spring:
security:
oauth2:
client:
registration:
google:
client-id: <client-id>
client-secret: <client-secret>


Create Spring Web Mvc Configurer  (WebMvcConfig.java)

package com.knf.dev.demo.config;

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 WebMvcConfig implements WebMvcConfigurer {

@Override
public void addViewControllers(ViewControllerRegistry registry){
registry.addViewController("/").setViewName("index");
registry.addViewController("/index").setViewName("index");
}
}


Create Spring  Security Configurer Adapter (SecurityConfig.java)

package com.knf.dev.demo.config;

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").authenticated()
.anyRequest().authenticated()
.and()
.oauth2Login().permitAll()
.and()
.logout()
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutSuccessUrl("/");
}
}


View(index.html)

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
          xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3"
xmlns:th="https://www.thymeleaf.org">
<head>
<title>Spring Boot OAuth2 Login with Google - Demo</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
               </script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js">
                 </script>
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<button class="navbar-toggle" data-target="#myNavbar"
                              data-toggle="collapse" type="button">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Logo</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">

<form method="post" th:action="@{/logout}">
<li><a href="#"><span class="glyphicon glyphicon-log-in">
<input type="submit" value="Logout "/></span></a>
</li>
</form>
</ul>
</div>
</div>
</nav>

<div class="container-fluid text-center">
<div class="row content">
<div class="col-sm-2 sidenav">
</div>
<div class="col-sm-8 text-left">
<h1>Welcome</h1>
<p>You have been successfully logged in</p>
</div>
</div>
</div>
</body>
</html>


Spring Boot Main Driver

package com.knf.dev.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringOauth2googleApplication {

public static void main(String[] args) {
SpringApplication.run(SpringOauth2googleApplication.class, args);
}
}


Run

$ mvn spring-boot:run 

Access the URL in  the browser


The application will redirect the user to the Google login screen 

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



You can able to log out by clicking on the Log-out button. After logged out the application will redirect the user to the login page.


More Spring Security Examples:

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete