Kotlin - Spring Security - GitHub OAuth2 Login - Example

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

More Spring Security practice:

1. Log in to GitHub: https://github.com/settings/apps

2. Navigate to the OAuth apps section on the left menu, and select New OAuth App

3. Then, provide Application name, Home Page URL, Authorization callback URL, and register application
4. After clicking the register button, System will generate the Client ID and Client Secret.

Now we have successfully created the auth client in the GitHub

Creating a Simple Web Application

Now we are going to develop a simple web application using Kotlin, Spring Security, and GitHub 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 GitHub Sign-in

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

Create Spring Web Mvc Configurer  (WebMvcConfig.kt)

package com.knf.dev.demo.kotlinspringgithuboauth2.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.kotlinspringgithuboauth2.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 OAuth2 Login with Github - 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>
</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.kotlinspringgithuboauth2

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

@SpringBootApplication
class Kotlinspringgithuboauth2Application

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

Run

Start Spring Boot with the default embedded Tomcat gradle bootRun.

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