This tutorial will walk you through the steps of creating a Single Sign On (SSO) Example with JSON Web Token (JWT) and Spring Boot

What you'll build

You'll build 3 separated services:

  • 1 Authentication Service: will be deployed at localhost:8080.

  • 2 Resource Services (to simplify, we use the same code base): will be deployed at localhost:8180 and localhost:8280.

What you'll need

  • JDK 1.7+
  • Maven 3+

Stack

  • Java
  • Single Sign On
  • JSON Web Token
  • Spring Boot
  • Freemarker

Build Authentication Service

Project structure

├── src
│   └── main
│       ├── java
│       │   └── com
│       │       └── hellokoding
│       │           └── sso
│       │               └── auth
│       │                   ├── CookieUtil.java
│       │                   ├── JwtUtil.java
│       │                   ├── LoginController.java
│       │                   └── WebApplication.java
│       └── resources
│           └── templates
│               └── login.ftl
└── pom.xml

Project dependencies


CookieUtil

JWT Token'll be saved and extracted from browser cookies.


cookie.setSecure(secure): secure=true => work on HTTPS only.

cookie.setHttpOnly(true): invisible to JavaScript.

cookie.setMaxAge(maxAge): maxAge=0: expire cookie now, maxAge<0: expire cookiie on browser exit.

cookie.setDomain(domain): visible to domain only.

cookie.setPath("/"): visible to all paths.

JwtUtil

We use JJWT to generate/parse JWT Token.


LoginController


To simplify, we use a HashMap (credentials) as user database.

View Template


Application Configuration


Run

mvn clean spring-boot:run

Build Resource Service

Project structure

├── src
│   └── main
│       ├── java
│       │   └── com
│       │       └── hellokoding
│       │           └── sso
│       │               └── resource
│       │                   ├── CookieUtil.java
│       │                   ├── JwtFilter.java
│       │                   ├── JwtUtil.java
│       │                   ├── ResourceController.java
│       │                   └── WebApplication.java
│       └── resources
│           ├── templates
│           │   └── protected-resource.ftl
│           └── application.properties
└── pom.xml

Project dependencies


JwtFilter

JwtFilter enforces SSO. If JWT Token's not existed (unauthenticated), redirects to Authentication Service. If JWT Token's existed (authenticated), extracts user identity and forwards the request.


ResourceController


View Template


Application Configuration



Run

Resource Service 1

mvn clean spring-boot:run -Dserver.port=8180

Resource Service 2

mvn clean spring-boot:run -Dserver.port=8280

Source code

https://github.com/hellokoding/hellokoding-courses/tree/master/springboot-examples/springboot-single-sign-on-jwt