Kotlin - 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 Kotlin + Spring Boot application with Gradle build.

More Spring Security practice:


 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 Kotlin, Spring Security and Google OAuth2

Project Structure:



Project Dependency(build.gradle.kts)

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
id("org.springframework.boot") version "2.5.4"
id("io.spring.dependency-management") version "1.0.11.RELEASE"
kotlin("jvm") version "1.5.21"
kotlin("plugin.spring") version "1.5.21"
}

group = "com.knf.dev.demo"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_11

repositories {
mavenCentral()
}

dependencies {
implementation("org.springframework.boot:spring-boot-starter-oauth2-client")
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.springframework.boot:spring-boot-starter-thymeleaf")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
implementation("org.thymeleaf.extras:thymeleaf-extras-springsecurity5")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.springframework.security:spring-security-test")
}

tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "11"
}
}

tasks.withType<Test> {
useJUnitPlatform()
}

Enable Google Sign-in

spring:
security:
oauth2:
client:
registration:
google:
client-id: <client-id>
client-secret: <client-secret>

Create Spring Web Mvc Configurer  (WebMvcConfig.kt)

package com.knf.dev.demo.kotlinspringOauth2google.config

import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry

@Configuration
class WebMvcConfig : WebMvcConfigurer {
override fun addViewControllers(registry: ViewControllerRegistry) {
registry.addViewController("/").setViewName("index")
registry.addViewController("/index").setViewName("index")
}
}

Create Spring  Security Configurer Adapter (SecurityConfig.kt)

package com.knf.dev.demo.kotlinspringOauth2google.config

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import kotlin.Throws
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import java.lang.Exception

@EnableWebSecurity
class SecurityConfig : WebSecurityConfigurerAdapter() {
@Throws(Exception::class)
public override fun configure(httpSecurity: HttpSecurity) {
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>Kotlin + 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>

Driver Class(Main class)

package com.knf.dev.demo.kotlinspringOauth2google

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication

@SpringBootApplication
class KotlinspringOauth2googleApplication

fun main(args: Array<String>) {
runApplication<KotlinspringOauth2googleApplication>(*args)
}

Run

Start Spring Boot with the default embedded Tomcat gradle bootRun.

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.

Popular posts from this blog

Spring boot video streaming example-HTML5

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

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

DataTable-Pagination example with Spring boot, jQuery and ajax

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Node JS mini projects with source code - free download

Spring boot web project free download:User Registration System

Java - Blowfish Encryption and decryption Example