Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
251 changes: 194 additions & 57 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,93 +1,230 @@
# authenticator
# Secure Authentication Service

**Spring Boot · JWT · TOTP · PostgreSQL · Docker · Thymeleaf**

## Overview

## Getting started
This application is a secure authentication service built with **Spring Boot**, implementing **JWT-based authentication** with **TOTP (Time-based One-Time Password) multi-factor authentication** using **Google Authenticator**.

To make it easy for you to get started with GitLab, here's a list of recommended next steps.
It provides:

Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
* Stateless authentication using JWT
* Two-factor authentication via TOTP (RFC 6238)
* Server-side rendered UI using **Thymeleaf**
* Local development environment via **Docker Compose**
* API-first development using **OpenAPI Generator**

## Add your files
---

- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command:
## Key Features

* **JWT Authentication**

* Access and refresh token support
* Stateless security architecture

* **TOTP / 2FA Authentication**

* QR code generation for enrollment
* Compatible with Google Authenticator and similar apps
* One-time codes validated server-side

* **PostgreSQL**

* Supports PostgreSQL **version 15 or earlier**
* Managed via Docker for local development

* **Thymeleaf UI**

* Login, enrollment, and verification flows
* Server-side rendering with Spring MVC

* **Dockerized Development**

* One-command startup using Docker Compose
* Environment variables externalized via template

* **OpenAPI-Driven Development**

* API contract defined in `doc/api.yml`
* Java client generated via OpenAPI Generator

---

## Technology Stack

| Layer | Technology |
| ----------------- | -------------------------------------- |
| Backend | Spring Boot |
| Security | Spring Security, JWT |
| 2FA | TOTP (Google Authenticator compatible) |
| Database | PostgreSQL (≤ 15) |
| UI | Thymeleaf |
| API Specification | OpenAPI 3 |
| Build Tool | Gradle |
| Containerization | Docker, Docker Compose |

---

## Authentication Flow (High Level)

1. User logs in with username/password
2. If TOTP is enabled:

* User must provide a valid one-time code
3. On success:

* JWT token is issued
4. JWT is used for subsequent API requests

---

## TOTP Enrollment Flow

1. User requests TOTP enrollment
2. Server generates:

* Shared secret
* QR code
3. User scans QR code using Google Authenticator
4. User submits a generated TOTP code for verification
5. TOTP is activated for the account

---

## Sequence Diagram (TOTP Authentication)

```mermaid
sequenceDiagram
participant User
participant UI (Thymeleaf)
participant Auth API
participant Database

User->>UI (Thymeleaf): Login (username/password)
UI->>Auth API: POST /auth/login
Auth API->>Database: Validate credentials
Auth API-->>UI (Thymeleaf): TOTP required

User->>UI (Thymeleaf): Enter TOTP code
UI->>Auth API: POST /auth/totp/verify
Auth API->>Database: Validate TOTP secret
Auth API-->>UI (Thymeleaf): JWT issued
```
cd existing_repo
git remote add origin https://git.inge.re/hasina.vagno/authenticator.git
git branch -M main
git push -uf origin main

---

## Local Development Setup

### Prerequisites

* Docker & Docker Compose
* Java 17+
* Gradle

---

### Environment Configuration

1. Copy the environment template:

```bash
cp env.template .env
```

2. Update values as needed (database credentials, JWT secrets, etc.).

> **Note:** All sensitive configuration is managed via environment variables.

---

### Running Locally

```bash
docker compose up -d
```

## Integrate with your tools
This will start:

- [ ] [Set up project integrations](https://git.inge.re/hasina.vagno/authenticator/-/settings/integrations)
* PostgreSQL
* The Spring Boot application

## Collaborate with your team
---

- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/)
## Database

## Test and Deploy
* PostgreSQL **15 or lower**
* Schema managed via application startup (or migration tool if configured)
* Data persisted via Docker volume

Use the built-in continuous integration in GitLab.
---

- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
## API Development Workflow

***
### OpenAPI Contract

# Editing this README
* API specification lives in:

When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
```
doc/api.yml
```

## Suggestions for a good README
### ⚠ Important: After Editing `doc/api.yml`

Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
Because this project uses **OpenAPI Generator** to generate the Java client:

## Name
Choose a self-explaining name for your project.
```bash
./gradlew clean assemble
```

This ensures:

* Client code is regenerated
* Build artifacts stay in sync with the API contract

## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
---

## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Testing Strategy

## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
### Current Coverage

## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
* Unit tests for authentication logic
* Integration tests for API endpoints

## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
### Recommended Improvements

## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
* Add **more integration tests**, especially for:

## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
* JWT validation
* TOTP enrollment and verification
* Authentication edge cases (expired tokens, invalid codes)
* Consider Testcontainers for PostgreSQL integration tests

## Contributing
State if you are open to contributions and what your requirements are for accepting them.
---

For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
## Project Structure (Simplified)

You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
```
├── doc/
│ └── api.yml
├── src/
│ ├── main/
│ │ ├── java/
│ │ └── resources/
│ │ ├── templates/ # Thymeleaf UI
│ │ └── application.properties
│ └── test/
├── docker-compose.yml
├── env.template
├── build.gradle
└── README.md
```

## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
---

## License
For open source projects, say how it is licensed.
## Security Notes

## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
* JWT secrets must be strong and never committed
* TOTP secrets are stored securely and never exposed
* HTTPS is strongly recommended for production
* Consider rate-limiting authentication endpoints
3 changes: 3 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ dependencies {
implementation 'io.jsonwebtoken:jjwt-jackson:0.11.5'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'commons-codec:commons-codec:1.16.0'
implementation 'com.google.zxing:core:3.5.2'
implementation 'com.google.zxing:javase:3.5.2'
implementation 'app.esiroi:auth-gen:1.0.0'
implementation 'org.flywaydb:flyway-core'
compileOnly 'org.projectlombok:lombok'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import app.esiroi.auth.endpoint.mapper.UserRestMapper;
import app.esiroi.auth.endpoint.rest.model.AuthUser;
import app.esiroi.auth.endpoint.security.AuthProvider;
import app.esiroi.auth.service.UserService;
import app.esiroi.auth.service.AuthService;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
Expand All @@ -14,7 +14,7 @@
@Controller
@AllArgsConstructor
public class AuthenticationController {
private final UserService service;
private final AuthService service;
private final UserRestMapper mapper;

@GetMapping("/")
Expand Down Expand Up @@ -42,8 +42,8 @@ public String logout(HttpServletResponse response) {
@PostMapping("/register")
public String register(@ModelAttribute AuthUser toRegister) {
var toSave = mapper.toDomain(toRegister);
service.saveUser(toSave);
return "redirect:/validateOTP";
var email = service.saveUser(toSave).getEmail();
return "redirect:/qrcode?email=" + email;
}

@GetMapping("/register")
Expand All @@ -57,6 +57,13 @@ public String validateOTP() {
return "otp";
}

@GetMapping("/qrcode")
public String qrcode(@RequestParam("email") String email, Model model) {
var qrCode = service.setupTotp(email);
model.addAttribute("qrCode", qrCode);
return "qrcode";
}

@GetMapping("/profile")
public String profile(Model model) {
var email = AuthProvider.getAuthenticatedUserEmail();
Expand All @@ -66,8 +73,12 @@ public String profile(Model model) {

@PostMapping("/validateOTP")
public String validate(@RequestParam("otp") String otp) {
service.validateOTP(otp);
return "redirect:/profile";
try {
service.validateOTP(otp);
return "redirect:/profile";
} catch (Exception e) {
return "redirect:/validateOTP";
}
}

private Cookie putTokenInCookie(String token) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
import app.esiroi.auth.endpoint.rest.model.AuthUser;
import app.esiroi.auth.endpoint.rest.model.User;
import app.esiroi.auth.endpoint.security.Encryptor;
import java.security.SecureRandom;
import lombok.AllArgsConstructor;
import org.apache.commons.codec.binary.Base32;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

Expand All @@ -26,12 +28,20 @@ public User toRest(app.esiroi.auth.model.User user) {

public app.esiroi.auth.model.User toDomain(AuthUser user) {
var hashedPass = passwordEncoder.encode(user.getPassword());
var encryptedSecret = encryptor.getInstance().encrypt("test".getBytes());
var encryptedSecret = encryptor.getInstance().encrypt(generateSecret().getBytes());
return app.esiroi.auth.model.User.builder()
.id(randomUUID().toString())
.email(user.getEmail())
.passwordHash(hashedPass)
.otpSecret(encryptedSecret)
.build();
}

private String generateSecret() {
SecureRandom random = new SecureRandom();
byte[] bytes = new byte[20]; // 160 bits
random.nextBytes(bytes);
Base32 base32 = new Base32();
return base32.encodeToString(bytes);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ public SecurityFilterChain configure(HttpSecurity http) throws Exception {
.authenticated()
.requestMatchers(POST, "/validateOTP")
.authenticated()
.requestMatchers(GET, "/qrcode")
.permitAll()
.requestMatchers(GET, "/profile")
.authenticated()
.anyRequest()
Expand Down
Loading