From 28fdfbbaf73e83698c84a94400fbb2a0076ad152 Mon Sep 17 00:00:00 2001 From: Ny Hasina Vagno Date: Mon, 22 Dec 2025 00:28:11 +0400 Subject: [PATCH 1/4] chore: qrcode generator deps --- build.gradle | 3 +++ 1 file changed, 3 insertions(+) diff --git a/build.gradle b/build.gradle index fc174ab..8ae4712 100644 --- a/build.gradle +++ b/build.gradle @@ -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' From e8c3e379f8d5cf7426f3426eab66cf83d455b33b Mon Sep 17 00:00:00 2001 From: Ny Hasina Vagno Date: Mon, 22 Dec 2025 00:57:12 +0400 Subject: [PATCH 2/4] feat: generate qrcode for totp --- .../controller/AuthenticationController.java | 15 +++++--- .../auth/endpoint/mapper/UserRestMapper.java | 12 ++++++- .../auth/endpoint/security/SecurityConf.java | 2 ++ .../auth/endpoint/security/TOTPConf.java | 12 +++---- .../{UserService.java => AuthService.java} | 26 +++++++++++++- src/main/resources/templates/profile.html | 2 +- src/main/resources/templates/qrcode.html | 34 +++++++++++++++++++ ...{UserServiceIT.java => AuthServiceIT.java} | 6 ++-- 8 files changed, 92 insertions(+), 17 deletions(-) rename src/main/java/app/esiroi/auth/service/{UserService.java => AuthService.java} (63%) create mode 100644 src/main/resources/templates/qrcode.html rename src/test/java/app/esiroi/auth/integration/service/{UserServiceIT.java => AuthServiceIT.java} (87%) diff --git a/src/main/java/app/esiroi/auth/endpoint/controller/AuthenticationController.java b/src/main/java/app/esiroi/auth/endpoint/controller/AuthenticationController.java index 0a21a87..9c362fe 100644 --- a/src/main/java/app/esiroi/auth/endpoint/controller/AuthenticationController.java +++ b/src/main/java/app/esiroi/auth/endpoint/controller/AuthenticationController.java @@ -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; @@ -14,7 +14,7 @@ @Controller @AllArgsConstructor public class AuthenticationController { - private final UserService service; + private final AuthService service; private final UserRestMapper mapper; @GetMapping("/") @@ -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") @@ -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(); diff --git a/src/main/java/app/esiroi/auth/endpoint/mapper/UserRestMapper.java b/src/main/java/app/esiroi/auth/endpoint/mapper/UserRestMapper.java index bbf4e8e..e188576 100644 --- a/src/main/java/app/esiroi/auth/endpoint/mapper/UserRestMapper.java +++ b/src/main/java/app/esiroi/auth/endpoint/mapper/UserRestMapper.java @@ -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; @@ -26,7 +28,7 @@ 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()) @@ -34,4 +36,12 @@ public app.esiroi.auth.model.User toDomain(AuthUser user) { .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); + } } diff --git a/src/main/java/app/esiroi/auth/endpoint/security/SecurityConf.java b/src/main/java/app/esiroi/auth/endpoint/security/SecurityConf.java index 2ce39ed..ae7ec71 100644 --- a/src/main/java/app/esiroi/auth/endpoint/security/SecurityConf.java +++ b/src/main/java/app/esiroi/auth/endpoint/security/SecurityConf.java @@ -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() diff --git a/src/main/java/app/esiroi/auth/endpoint/security/TOTPConf.java b/src/main/java/app/esiroi/auth/endpoint/security/TOTPConf.java index 26edce7..f9c433b 100644 --- a/src/main/java/app/esiroi/auth/endpoint/security/TOTPConf.java +++ b/src/main/java/app/esiroi/auth/endpoint/security/TOTPConf.java @@ -21,8 +21,10 @@ public class TOTPConf { private static final int DEFAULT_TOTP_DIGITS = 6; private static final int DEFAULT_TOTP_PERIOD = 30; // in seconds - public String generateTOTP(String secret) { - return generateTOTP(secret, DEFAULT_TOTP_DIGITS, DEFAULT_TOTP_PERIOD); + public String getTotpUri(String secret, String account, String issuer) { + return String.format( + "otpauth://totp/%s:%s?secret=%s&issuer=%s&algorithm=SHA1&digits=6&period=30", + issuer, account, secret, issuer); } public String generateTOTP(String secret, int digits, int period) { @@ -57,11 +59,7 @@ public String generateTOTP(String secret, int digits, long counter) { } public boolean validateTOTP(String secret, String otp) { - return validateTOTP(secret, otp, DEFAULT_TOTP_DIGITS); - } - - public boolean validateTOTP(String secret, String otp, int digits) { - String expectedOTP = generateTOTP(secret, digits, DEFAULT_TOTP_PERIOD); + String expectedOTP = generateTOTP(secret, DEFAULT_TOTP_DIGITS, DEFAULT_TOTP_PERIOD); return expectedOTP.equals(otp); } } diff --git a/src/main/java/app/esiroi/auth/service/UserService.java b/src/main/java/app/esiroi/auth/service/AuthService.java similarity index 63% rename from src/main/java/app/esiroi/auth/service/UserService.java rename to src/main/java/app/esiroi/auth/service/AuthService.java index b0dea10..091bb21 100644 --- a/src/main/java/app/esiroi/auth/service/UserService.java +++ b/src/main/java/app/esiroi/auth/service/AuthService.java @@ -9,7 +9,14 @@ import app.esiroi.auth.model.exception.ForbiddenException; import app.esiroi.auth.model.exception.NotFoundException; import app.esiroi.auth.repository.UserRepository; +import com.google.zxing.BarcodeFormat; +import com.google.zxing.client.j2se.MatrixToImageWriter; +import com.google.zxing.common.BitMatrix; +import com.google.zxing.qrcode.QRCodeWriter; +import java.io.ByteArrayOutputStream; +import java.util.Base64; import lombok.AllArgsConstructor; +import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; @@ -17,7 +24,7 @@ @Service @AllArgsConstructor @Slf4j -public class UserService { +public class AuthService { private final UserRepository repository; private final PasswordEncoder encoder; private final JWTConf jwtConf; @@ -57,4 +64,21 @@ public User validateOTP(String otp) { } throw new ForbiddenException("OTP Invalid"); } + + @SneakyThrows + private String generateQrCode(String otpAuthUrl, int width, int height) { + QRCodeWriter qrCodeWriter = new QRCodeWriter(); + BitMatrix bitMatrix = qrCodeWriter.encode(otpAuthUrl, BarcodeFormat.QR_CODE, width, height); + ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream(); + MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream); + byte[] pngData = pngOutputStream.toByteArray(); + return Base64.getEncoder().encodeToString(pngData); // Base64 pour HTML + } + + public String setupTotp(String email) { + var authUser = getUserByEmail(email); + var decryptedSecret = new String(encryptor.getInstance().decrypt(authUser.getOtpSecret())); + String otpAuthUrl = totpConf.getTotpUri(decryptedSecret, authUser.getEmail(), "Authentify"); + return generateQrCode(otpAuthUrl, 200, 200); + } } diff --git a/src/main/resources/templates/profile.html b/src/main/resources/templates/profile.html index ac72561..d01860e 100644 --- a/src/main/resources/templates/profile.html +++ b/src/main/resources/templates/profile.html @@ -57,7 +57,7 @@

Welcome

- +
diff --git a/src/main/resources/templates/qrcode.html b/src/main/resources/templates/qrcode.html new file mode 100644 index 0000000..421271f --- /dev/null +++ b/src/main/resources/templates/qrcode.html @@ -0,0 +1,34 @@ + + + + + Profil + + + +
+

Scan

+ QR Code TOTP +
+ + diff --git a/src/test/java/app/esiroi/auth/integration/service/UserServiceIT.java b/src/test/java/app/esiroi/auth/integration/service/AuthServiceIT.java similarity index 87% rename from src/test/java/app/esiroi/auth/integration/service/UserServiceIT.java rename to src/test/java/app/esiroi/auth/integration/service/AuthServiceIT.java index 7608925..7b56296 100644 --- a/src/test/java/app/esiroi/auth/integration/service/UserServiceIT.java +++ b/src/test/java/app/esiroi/auth/integration/service/AuthServiceIT.java @@ -5,14 +5,14 @@ import app.esiroi.auth.ITestConfiguration; import app.esiroi.auth.model.User; import app.esiroi.auth.repository.UserRepository; -import app.esiroi.auth.service.UserService; +import app.esiroi.auth.service.AuthService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -public class UserServiceIT extends ITestConfiguration { +public class AuthServiceIT extends ITestConfiguration { @Autowired UserRepository userRepository; - @Autowired UserService subject; + @Autowired AuthService subject; @BeforeEach void setUp() { From 04c5a4f4e892f9ae0dd83f8bb718a8b77b5b4250 Mon Sep 17 00:00:00 2001 From: Ny Hasina Vagno Date: Mon, 22 Dec 2025 01:09:20 +0400 Subject: [PATCH 3/4] chore: navigate to login after qrcode scan --- .../controller/AuthenticationController.java | 8 ++++++-- src/main/resources/templates/qrcode.html | 14 +++++++++++++- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/main/java/app/esiroi/auth/endpoint/controller/AuthenticationController.java b/src/main/java/app/esiroi/auth/endpoint/controller/AuthenticationController.java index 9c362fe..8b415d6 100644 --- a/src/main/java/app/esiroi/auth/endpoint/controller/AuthenticationController.java +++ b/src/main/java/app/esiroi/auth/endpoint/controller/AuthenticationController.java @@ -73,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) { diff --git a/src/main/resources/templates/qrcode.html b/src/main/resources/templates/qrcode.html index 421271f..3dc0dc5 100644 --- a/src/main/resources/templates/qrcode.html +++ b/src/main/resources/templates/qrcode.html @@ -22,13 +22,25 @@ width: 250px; } - + button { + width: 100%; + padding: 10px; + background: #4CAF50; + border: none; + color: white; + font-weight: bold; + border-radius: 4px; + cursor: pointer; + }

Scan

QR Code TOTP +
+ +
From 3109c737186f9bdf0fe138cf137d7a25ceb2540d Mon Sep 17 00:00:00 2001 From: Ny Hasina Vagno Date: Mon, 22 Dec 2025 01:17:56 +0400 Subject: [PATCH 4/4] chore: readme --- README.md | 251 +++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 194 insertions(+), 57 deletions(-) diff --git a/README.md b/README.md index e3b5ba3..71dab11 100644 --- a/README.md +++ b/README.md @@ -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