Spring Boot OAuth 2.0 Client Implementation + MySQL Integration

Overview

Spring Boot OAuth 2.0 Client + MySQL


1. What is OAuth 2.0 ?

The OAuth 2.0 authorization framework enables a third-party application to obtain limited access to an HTTP service.

2. How does OAuth 2.0 work ?

img.png

  • Resource Owner

    An entity capable of granting access to a protected resource. When the resource owner is a person, it is referred to as an end-user.
    > In other words , it's the end-user that accepts the authorization request.

  • OAuth 2.0 Client

    An application making protected resource requests on behalf of the resource owner and with its authorization.

  • Authorization server

    The server issuing access tokens to the client after successfully authenticating the resource owner and obtaining authorization.
    > This access token will be used later to retrieve the protected resource.

  • Resource Server

    The server hosting the protected resources, capable of accepting and responding to protected resource requests using access tokens.

In our example , we will be interested only to the client side of OAuth 2.
That is , registering the user in our mysql database after getting information from the OAuth2 Provider ( Google , Github)

> OAuth2 Client is our spring application.
> Resource Owner is the user.
> Authorization/Resource Server is the OAuth2 provider.

3.Technologies

Spring Boot Web

Spring Data JPA

Spring Security

Spring OAuth2 Client

MySQL Database

Docker ( Optional )

4. File Structure

img_3.png

  • WebSecurityConfig

Extending the WebSecurityConfigurerAdapter class which , along with @EnableWebSecurity annotation , provides web based security and allows us to do some configurations like restricting some URL's for authentication , rejecting requests or maybe a defining a custom firwall .

  • AppController

Playing the role of a controller of requests in the MVC architecture thanks to Spring MVC.
We defined an endpoint "/user" to show the json data sent by the oauth provider after the login success.

  • User and CustomOauth2User

The class User is our Model , in the MVC architecture , marked with @Entity JPA annotation to make the object ready for storage in the database.
The class CustomOauth2User will be used to get attributes of the data retrieved from the oauth provider.

  • UserRepository

Extending the JpaRepository class which makes database access very easy and allows us to perform creation , deletion , update and searching of users.

  • UserService and CustomOauth2UserService

Classes that contains the @Service annotation and used to write business logic like finding a user by email or loading the user from the OauthProvider.

  • OAuth2LoginSuccessHandler

Extends the class SimpleUrlAuthenticationSuccessHandler which is used to specify any custom logic after the success of the authorization .
This class is needed to store the user in tha database after the login.

5. How to run the project

Step 1 : OAuth 2.0 credentials from the Google API Console

Create a new project and get a new pair of OAuth 2.0 clientId and clientSecret.
you'll need them for spring security oauth configuration in application.yaml

spring:
  security:
      oauth2:
        client:
          registration:
            google:
              clientId: PASTE_GOOGLE_CLIENT_ID_HERE
              clientSecret: PASTE_GOOGLE_CLIENT_SECRET_HERE
              scope:
                - profile
                - email

Scope are the information needed from the oauth provider .
In our case we need general profile information and also the email ( will be used later ) Also we need to set the URL callback to /oauth2/authorization/google

Step 2 : Creating a MySQL Database Instance

Using docker is not necessary here , you can use our local MySQL.
In our case we can use docker compose to create our database container.

docker-compose.yaml:

version: "3.7"

services:
  mysql:
    image: mysql:8.0
    ports:
      - "3306:3306"
    environment:
      MYSQL_ROOT_PASSWORD: MYSQL_ROOT_PASSWORD
      MYSQL_DATABASE: demo

Here we are using the version 3.7 of the docker compose . Then we are fetching the image of mysql version 8.0 from the Docker Registry. We also expose the port 3306 of the machine ( so we can access the container ) and the port 3306 of the container. Finally we set the root password and the name of the database that we want to create ( for example demo ).

Also we need to configue Spring JPA to use our mysql container.
application.yaml:

spring:
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
  datasource:
    username: MYSQL_ROOT_USERNAME
    password: MYSQL_ROOT_PASSWORD
    url: jdbc:mysql://localhost:3306/demo

Last but not least , we run the command below to create the database instance.

$ cd spring-boot-oauth2-mysql
$ docker compose up

Step 3 : Running the spring application


DEMO

Let's demonstrate with our oauth 2.0 client implementation with some basic html template.

img_1.png

Before we proceed to the authorization server , let's show our current state of the database :

img_2.png

As we can see our user table is currently empty and our goal is to create a new user after the login success.

img_3.png

After clicking the link , we are redirected to a google page for authorization.

And we can hit the endpoint "/user" to take a peak about the data send to us by google.

img_4.png

And Boom , we obtained the full name and email address , that's exactly what we configured in the application.yaml

So now that we have the data we can actually display the name of the user , as well as registering him in the database .

img_5.png

Here we can see the user registered successfully thanks to the class OAuth2LoginSuccessHandler .

And also we updated to front page to show the name of current logged-in user.

img_6.png

You might also like...

ProxySql, MySQL Replication, Spring Boot

ProxySql, MySQL Replication, Spring Boot

MySQL Replication with ProxySQL In this documentation, we will cover Problem Discussion Common Database problems and solutions. What is Database Repli

Dec 23, 2022

Kafka integration with Java Spring-boot: producer-consumer model

Kafka integration with Java Spring-boot with one application serving as a producer and the other consuming the messages

Apr 26, 2022

A high availability shopping(ecommerce) system using SpringBoot, Spring Cloud, Eureka Server, Spring Cloud Gateway, resillience4j, Kafka, Redis and MySQL.

A high availability shopping(ecommerce) system using SpringBoot, Spring Cloud, Eureka Server, Spring Cloud Gateway, resillience4j, Kafka, Redis and MySQL.

High-availability-shopping-system A high availability shopping(ecommerce) system using SpringBoot, Spring Cloud, Eureka Server, Spring Cloud Gateway,

Oct 26, 2022

An integration solution for Spring Cloud and Tencent middleware - Spring Cloud和腾讯中间件的集成方案

Spring Cloud Tencent English | 简体中文 Introduction Spring Cloud Tencent contains components distributed micro-service applications need during developin

Dec 29, 2022

Hi, Spring fans! In this installment we look Spring Integration's support for MQTT and the HiveMQ broker

Spring Integration MQTT & HiveMQ Hi, Spring fans! In this installment we look Spring Integration's support for MQTT and the HiveMQ broker. I'm joined

Nov 21, 2022

Zero-Dependency RFC 8252 OAuth 2.0 Authorization Flow

Tiny OAuth2 Client This is a minimal zero-dependency implementation of the RFC 8252 OAuth 2.0 for Native Apps, relying on Loopback Interface Redirecti

Jun 17, 2022

The in-game login system for Grasscutter is based on oauth and GCAuth.

GCAuth OAuth The in-game login system for Grasscutter is based on oauth and GCAuth. Current Features: Use Twitter oauth to login Custom pages Importan

Nov 14, 2022

Kafdrop configured for Openshift, with OAuth proxy

Kafdrop configured for Openshift, with OAuth proxy

Deploying Kafdrop to Openshift This repo takes the original Kafdrop and extends it to deploy it on Openshift. Integration with Kafka Clusters managed

Jul 17, 2022

The in-game login system for Grasscutter is based on oauth and GCAuth.

GCAuth OAuth The in-game login system for Grasscutter is based on oauth and GCAuth. Current Features: Use Twitter oauth to login Custom pages Importan

Aug 3, 2022
Owner
Salah Eddine Zemmouri
Software Engineer Student
Salah Eddine Zemmouri
Spring Boot Login and Registration example with MySQL, JWT, Rest Api - Spring Boot Spring Security Login example

Spring Boot Login example with Spring Security, MySQL and JWT Appropriate Flow for User Login and Registration with JWT Spring Boot Rest Api Architect

null 58 Jan 5, 2023
循序渐进,学习Spring Boot、Spring Boot & Shiro、Spring Batch、Spring Cloud、Spring Cloud Alibaba、Spring Security & Spring Security OAuth2,博客Spring系列源码:https://mrbird.cc

Spring 系列教程 该仓库为个人博客https://mrbird.cc中Spring系列源码,包含Spring Boot、Spring Boot & Shiro、Spring Cloud,Spring Boot & Spring Security & Spring Security OAuth2

mrbird 24.8k Jan 6, 2023
Search API with spelling correction using ngram-index algorithm: implementation using Java Spring-boot and MySQL ngram full text search index

Search API to handle Spelling-Corrections Based on N-gram index algorithm: using MySQL Ngram Full-Text Parser Sample Screen-Recording Screen.Recording

Hardik Singh Behl 5 Dec 4, 2021
This module explains about the example of Spring MVC + Database Integration with MySQL using Hibernate ORM with practical coding example and required JAR dependencies

SpringMVC-Database-Integration This module explains about the example of Spring MVC + Database Integration with MySQL using Hibernate ORM with practic

GowthamRaj K 3 Nov 2, 2021
开源论坛、问答系统,现有功能提问、回复、通知、最新、最热、消除零回复功能。功能持续更新中…… 技术栈 Spring、Spring Boot、MyBatis、MySQL/H2、Bootstrap

码问社区 在线演示地址 www.mawen.co 功能列表 开源论坛、问答系统,现有功能提问、回复、通知、最新、最热、消除零回复功能。功能持续更新中…… 技术栈 技术 链接 Spring Boot http://projects.spring.io/spring-boot/#quick-start

小匠 2.3k Dec 30, 2022
Docker-compose-integration-tstst - An exploration of how to run integration tests against an application that has inconvenient external dependencies (e.g. a SQL database).

Tstst? it was supposed to be docker-compose-integration-tests but i was too lazy to fix it at the outset, and now im trying to convince myself its fun

null 1 Jan 4, 2022
Framework for automated integration tests with focus on messaging integration

Citrus Integration Testing Welcome to Citrus Citrus is a test framework written in Java that is able to create fully automated end-to-end use case tes

Citrus Framework 373 Dec 27, 2022
基于 Spring Security OAuth 的统一账号管理平台

基于 Spring Security OAuth 的统一账号管理平台 前后端演示地址: https://tao.flizi.cn 支持密码模式演示 输入账号 123456, 密码: 123456, 以及验证码后点击登录 支持授权登录演示 输入手机号 123456, 密码: 123456, 以及验证码

知一 132 Nov 9, 2022
一个基于vue3.0+antd+less+spring boot +mybatis+mysql+maven基础权限管理平台

cc-project vue 版本 angular版本请到 https://github.com/myopenresources/cc-project 这里看 详细文档 请到 cc-project详细文档 介绍 cc-project-vue 是一个前后端分离的项目,前端使用的是vue3.0,后端使用

河马开源-hippo 21 Jun 23, 2022
Spring Boot Simple Login & Registration + MyBatis + MySQL

springboot-mybatis-security-login-register A simple security login & registration module using Spring Boot, Spring Security, MyBatis Framework and MyS

Desmond 4 May 31, 2022