Budget Proof Key for Code Exchange (PKCE) implementation using Java Spring-boot

Overview

Low Budget Proof Key for Code Exchange (PKCE) Implementation using Java Spring-boot

Just for fun, low budget implementation of PKCE Auth Flow using a single Spring-boot application that exposes APIs to act as an authorization and resource server both.

Screen Recording showing Auth Flow (62 Seconds)

Budget-PKCE-Recording.mov

Authorization Code Flow with Proof Key for Code Exchange (PKCE)

1.) Configure Client-id and Redirect-URI in application.properties file as per PkceConfigurationProperties.class

com.behl.ehrmantraut.security.client-id= <Client-id goes here>
com.behl.ehrmantraut.security.redirect-uri= <Redirect-URI to send code to, after successfull authentication>
com.behl.ehrmantraut.security.response-type=code
com.behl.ehrmantraut.security.code-challenge-method=S256
com.behl.ehrmantraut.security.grant-type=authorization_code
com.behl.ehrmantraut.security.code-expiration-minutes=2

2.) Create the code verifier and challenge

Before each authentication request, the client app should generate a code verifier and a code challenge.

  • The code verifier is a cryptographically random string between 43 and 128 characters in length. It can contain letters, digits, underscores, periods, hyphens, or tildes.
  • In order to generate the code challenge, the client should hash the code verifier using the SHA256 algorithm. Then, base64url encode the hash that is generated.
  • Sample Code verifier and code Challenge for demo (Not to be kept static and should be dynamically calculated before every request)
    • Code Verifier
    dcFKDCmdcYmcmW6DXu2BfSrkGB1cKwFAI5Jv7he9RDo
    
    • Code Challenge
    Ijcr0PLd8HvnhB9AZXlhmPPJjyLyaPkianM0ERzD860
    

3.) Hit /authenticate POST API with the below data in the request body (Sample JSON given)

{
  "emailId": "[email protected]",
  "password": "noHalfMeasures",
  "clientId": "<Client-id as configured in .properties file>",
  "responseType": "code",
  "redirectUri": "<Redirect-URI as configured in .properties file>",
  "codeChallengeMethod": "S256",
  "codeChallenge": "<Set to the code challenge that was calculated in step 2>",
  "state": "<Optional: This can be used to mitigate cross-site request forgery attacks>"
}

4.) Recieve code and state in the request parameter of the provided redirect-URI after successfull authentication

  • This code is a one-time-use commodity to exchange token(s) from the server
  • The redirection is done through ResponseEntity.class
return ResponseEntity.status(HttpStatus.FOUND).location("attach query params (code and optional state to redirect-uri)").build();
  • Hit /token POST API with the below data in the request body (Sample JSON given)
{
  "clientId": "<Client-id as configured in .properties file>",
  "grantType": "authorization_code",
  "code": "<Code recieved in parameter of redirect-uri goes here>",
  "redirectUri": "<Redirect-URI as configured in .properties file>",
  "codeVerifier": "<The value of this key must match the value of the code_verifier that your app generated in step 2.>"
}

5.) On success, the response will have a 200 OK status and the following Sample JSON data in the response body

{
    "accessToken": "eyJhbGciOiJIUzI1NiJ9.eyJlbWFpbF9pZCI6Im1pa2UuZWhybWFudHJhdXRAZ21haWwuY29tIiwic3ViIjoibWlrZS5laHJtYW50cmF1dEBnbWFpbC5jb20iLCJhY2NvdW50X2NyZWF0aW9uX3RpbWVzdGFtcCI6IjIwMjEtMTAtMTZUMTQ6NDM6MTguMDQ1MDgwIiwidXNlcl9pZCI6ImZiNTRhNjdlLWI5NWItNDM2OS1iNjExLTdmYjRlYTA0NGQ4NiIsImV4cCI6MTYzNDM5OTAyMiwiaWF0IjoxNjM0Mzk1NDIyfQ._hUb127nUzI-GTkMIUbstTa21tuqRpsanektHnqzwCQ",
    "tokenType": "Bearer",
    "refreshToken": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJtaWtlLmVocm1hbnRyYXV0QGdtYWlsLmNvbSIsImV4cCI6MTYzNTY5MTQyMiwiaWF0IjoxNjM0Mzk1NDIyfQ.Lf7dQNSDZ9NUp6W4a8HwtZb0dWrgy9wpsxH4Pjb2VOg",
    "expiresIn": 3600
}
  • The recieved accessToken allows the client to make requests to the Server on behalf of the logged in-user using the Authorization Bearer Mechanism.

6.) A request to refresh an access token can be sent to the same /token endpoint with the below data in the request body (Sample JSON given)

{
    "clientId": "<Client-id as configured in .properties file>",
    "grantType": "refresh_token",
    "refreshToken": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJtaWtlLmVocm1hbnRyYXV0QGdtYWlsLmNvbSIsImV4cCI6MTYzNTY5MTQyMiwiaWF0IjoxNjM0Mzk1NDIyfQ.Lf7dQNSDZ9NUp6W4a8HwtZb0dWrgy9wpsxH4Pjb2VOg"
}

PRs welcome, Star repository to show support

Tech stack used

  • Java 17
  • Spring-boot 2.5.5
  • Spring-Security and JJWT
  • Spring-JPA/Hibernate
  • H2 in-memory DB
  • Lombok
  • LoadingCache (in Guava) to store userAuthenticationDetails in memory

Local Setup

  • Install Java 17 (recommended to use SdkMan)

sdk install java 17-open

  • Install Maven (recommended to use SdkMan)

sdk install maven

  • Clone the repo and Go to application.properties under src/main/resources and configure properties as required

  • Run the below command in core

mvn clean install

  • To start the application, run any of the below 2 commands

mvn spring-boot:run &

java -jar /target/budget-pkce-0.0.1-SNAPSHOT.jar

  • Access the swagger-ui

http://localhost:8080/swagger-ui.html

You might also like...

An extension for Keycloak, that enables web-based sign in with Apple and token exchange

Apple Identity Provider for Keycloak 🍎 This repository represents an extension for Keycloak, which enables Sign in with Apple for web-based applicati

Dec 29, 2022

How to configure Replica Set with Embedded Mongo using Spring Boot and Flapdoodle for unit testing code that uses mongodb transactions

Spring Boot Embedded Mongo with Replica Set This project defines a basic rest service that allows users to update records of a Person (name and email)

Nov 1, 2022

A code sharing platform built using spring boot, hibernate and JPA as ORM with PostgreSQL which also follows a RESTful architecture.

Snap-Snippet A code sharing platform built using spring boot, hibernate and JPA as ORM with PostgreSQL which also follows a RESTful architecture. Tech

Nov 29, 2022

about learning Spring Boot via examples. Spring Boot 教程、技术栈示例代码,快速简单上手教程。

about learning Spring Boot via examples. Spring Boot 教程、技术栈示例代码,快速简单上手教程。

Spring Boot 学习示例 Spring Boot 使用的各种示例,以最简单、最实用为标准,此开源项目中的每个示例都以最小依赖,最简单为标准,帮助初学者快速掌握 Spring Boot 各组件的使用。 Spring Boot 中文索引 | Spring Cloud学习示例代码 | Spring

Jan 1, 2023

spring boot 实践学习案例,是 spring boot 初学者及核心技术巩固的最佳实践。另外写博客,用 OpenWrite。

spring boot 实践学习案例,是 spring boot 初学者及核心技术巩固的最佳实践。另外写博客,用 OpenWrite。

推荐工具: 微信公众号 Markdown 编辑器 - OpenWrite:Markdown 微信编辑器是一款专业强大的微信公众平台在线编辑排版工具,提供手机预览功能,让用户在微信图文 、文章、内容排版、文本编辑、素材编辑上更加方便。 - 更多介绍 博客群发平台 一、支持泥瓦匠 Spring Boot

Jan 5, 2023

Spring-Boot-Plus is a easy-to-use, high-speed, high-efficient,feature-rich, open source spring boot scaffolding

Spring-Boot-Plus is a easy-to-use, high-speed, high-efficient,feature-rich, open source spring boot scaffolding

Everyone can develop projects independently, quickly and efficiently! What is spring-boot-plus? A easy-to-use, high-speed, high-efficient, feature-ric

Dec 31, 2022

Two Spring-boot applications registering themselves to an spring-boot-admin-server application as separate clients for the purpose of monitoring and managing the clients

Two Spring-boot applications registering themselves to an spring-boot-admin-server application as separate clients for the purpose of monitoring and managing the clients

Spring-boot-admin implementation with 1 Server and 2 clients Creating a Server application to monitor and manage Spring boot applications (clients) un

Dec 6, 2022

Rate limiting private REST APIs using Java Spring-boot, spring-security and bucket4j

Rate limiting REST APIs using Spring-security filter and Bucket4J Deployed Application (Swagger-ui on heroku) Inspired from: Baeldung Article Applicat

Jul 18, 2022

Code katas for learning Spring® and Spring Boot.

What is the spring-course? The Spring course consists of two related tutorials that teach developers about Spring Framework and then Spring Boot. The

Nov 20, 2022
Owner
Hardik Singh Behl
Java Web Developer
Hardik Singh Behl
循序渐进,学习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
Create your Java crypto trading bot in minutes. Our Spring boot starter takes care of exchange connections, accounts, orders, trades, and positions so you can focus on building your strategies.

Quick Start | Documentation | Discord | Twitter Create and run your java crypto trading bot in minutes Our Spring boot starter takes care of exchange

Cassandre 442 Jan 3, 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
Spring Boot Migrator (SBM) - a tool for automated code migrations to upgrade or migrate to Spring Boot

Spring Boot Migrator uses and is compatible to OpenRewrite, a powerful mass refactoring ecosystem for Java and other source code.

Spring Projects Experimental 231 Jan 2, 2023
The Spring Boot Sample App on K8S has been implemented using GKE K8S Cluster, Spring Boot, Maven, and Docker.

gke-springboot-sampleapp ?? The Spring Boot Sample App on K8S has been implemented using GKE K8S Cluster, Spring Boot, Maven, and Docker. Usage To be

KYEONGMIN CHO 1 Feb 1, 2022
Public proof-of-concept obfuscator using the MapleIR framework designed by cts & bibl

Skidfuscator: Obfuscation like never seen before. Join the discord: https://discord.gg/QJC9g8fBU9 ??️ What is Skidfuscator? Skidfuscator is a proof of

Shanyu Juneja / Thibaut Gautier 386 Jan 5, 2023
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
Daily mail subscription implementation using Java Spring-boot and Quartz Scheduler

Daily Mail Subscription Service POC Implemented using Java Spring-boot and Quartz Scheduler Working Application Exposing 3 endpoints /subscription/cre

null 16 Jun 3, 2022
Spring Boot JdbcTemplate example with SQL Server: CRUD Rest API using Spring Data JDBC, Spring Web MVC

Spring Boot JdbcTemplate example with SQL Server: Build CRUD Rest API Build a Spring Boot CRUD Rest API example that uses Spring Data Jdbc to make CRU

null 7 Dec 20, 2022
Currency Exchange Rate Rest Api

Spring Boot Currency Exchange Project This is a currency exchange Rest Api application which is developed using Spring Boot Framework. How to Run This

null 1 Jan 21, 2022