SPRING SECURITY / 03

Structure and code walkthrough

What each folder contains and why these layers exist.

Folder map

text
.
├── .env.example              # plantilla de configuración
├── compose.yml               # aplicación completa en Docker
├── .dockerignore             # exclusiones del contexto Docker
├── backend/
│   ├── pom.xml
│   └── src/
│       ├── main/
│       │   ├── java/com/example/security/
│       │   │   ├── SecurityLabApplication.java
│       │   │   ├── auth/
│       │   │   │   ├── AuthController.java
│       │   │   │   ├── application/JwtService.java
│       │   │   │   └── dto/                 # contratos de login y registro
│       │   │   ├── config/                  # seguridad y cuentas iniciales
│       │   │   ├── user/
│       │   │   │   ├── UserController.java
│       │   │   │   ├── application/UserService.java
│       │   │   │   ├── domain/              # entidad y roles
│       │   │   │   ├── dto/                 # contratos de usuario
│       │   │   │   └── repository/UserRepository.java
│       │   │   └── common/                  # errores compartidos
│       │   └── resources/
│       │       ├── application.yml
│       │       └── db/migration/V1__create_users.sql
│       └── test/             # integración + perfil H2
├── frontend/
│   ├── package.json / pnpm-lock.yaml
│   ├── index.html / vite.config.js
│   └── src/
│       ├── main.jsx / App.jsx / styles.css
│       ├── auth/AuthContext.jsx
│       ├── lib/api.js
│       ├── jsdoc.json / JSDOC.md
│       └── pages/            # pantallas con consultas y formularios
├── docker/                  # Dockerfiles y configuración de Nginx
└── docs/
    ├── COMO_FUNCIONA.md / peticiones.http
    ├── html/                 # este manual y sus diagramas SVG
    ├── javadoc/              # documentación generada del backend Java
    └── reactdoc/             # documentación generada del frontend React

backend/target/ contains Maven compilation output, JAR and reports. frontend/node_modules/ contains dependencies; frontend/dist/ contains the static build. These outputs can be regenerated: edit src, not those files.

Explained inventory

File (link to code)Responsibility
backend/pom.xmlJava dependencies and build: Spring Web, Security, Resource Server, JPA, Validation, MySQL and Flyway; H2 and test utilities are test-only.
backend/src/main/java/com/example/security/SecurityLabApplication.java@SpringBootApplication entry point; starts Spring Boot and component scanning.
backend/src/main/java/com/example/security/auth/AuthController.javaPOST login and registration. Login delegates to AuthenticationManager; registration saves USER with BCrypt.
backend/src/main/java/com/example/security/auth/dto/LoginRequest.javaCredential DTO with Jakarta Validation and the BCrypt byte limit.
backend/src/main/java/com/example/security/auth/dto/RegisterRequest.javaPublic registration DTO: name, email and password, with no role choice.
backend/src/main/java/com/example/security/auth/dto/AuthResponse.javaOutput record: accessToken, tokenType, expiresIn and UserResponse.
backend/src/main/java/com/example/security/auth/application/JwtService.javaIssues HS256 JWTs with issuer, subject, issue time, expiration and role.
backend/src/main/java/com/example/security/config/SecurityConfig.javaBeans for BCrypt, UserDetailsService, AuthenticationManager, key, encoder/decoder, filters and CORS.
backend/src/main/java/com/example/security/config/DemoData.javaConditional CommandLineRunner to create missing demo accounts.
backend/src/main/java/com/example/security/user/domain/AppUser.javaJPA entity for app_users; stores hash and status. Protected no-argument constructor required by JPA.
backend/src/main/java/com/example/security/user/domain/Role.javaUSER / ADMIN enum, persisted as text with EnumType.STRING.
backend/src/main/java/com/example/security/user/repository/UserRepository.javaJpaRepository<AppUser, Long> interface. Spring Data creates its implementation; email lookup and checks.
backend/src/main/java/com/example/security/user/application/UserService.javaTransactional CRUD, email normalisation, duplicates and protection of the acting account.
backend/src/main/java/com/example/security/user/UserController.java/me and /users endpoints. Receives the already verified Jwt as principal.
backend/src/main/java/com/example/security/user/dto/UserRequest.javaAdministration DTO; password optional when editing, role and status required.
backend/src/main/java/com/example/security/user/dto/UserResponse.javaPublic DTO: id, name, email, role and enabled; from transforms the entity and excludes the hash.
backend/src/main/java/com/example/security/common/ApiError.javaError contract record: status, message and errors map.
backend/src/main/java/com/example/security/common/ApiException.javaBusiness exception with HttpStatus and message.
backend/src/main/java/com/example/security/common/GlobalExceptionHandler.java@RestControllerAdvice for validation, credentials, invalid JSON, duplicates and business errors.
backend/src/main/resources/application.ymlPort, datasource, HikariCP, Flyway, JPA validation and variable import.
backend/src/main/resources/db/migration/V1__create_users.sqlInitial migration: table, unique index and role constraint.
backend/src/test/java/com/example/security/SecurityIntegrationTest.javaMockMvc tests exercising the real chain with signed JWTs, H2 and Flyway.
backend/src/test/resources/application-test.ymlIsolated test configuration, H2, test key and disabled demo initialiser.
backend/src/test/resources/mockito-extensions/org.mockito.plugins.MockMakerConfiguration of the mock generator used in tests.
frontend/package.jsondev/build/preview scripts, dependencies and pnpm version 10.33.4.
frontend/pnpm-lock.yamlDependency resolutions for reproducible installation with --frozen-lockfile.
frontend/index.htmlEntry document and container where React mounts the application.
frontend/vite.config.jsReact/Tailwind plugins, port 5173, strictPort and local /api proxy.
frontend/src/main.jsxReact entry point and navigation, query and authentication providers.
frontend/src/App.jsxRoutes /login, /registro, /, /usuarios and /aprender; /me profile, protected layout and ADMIN guard.
frontend/src/auth/AuthContext.jsxIn-memory session, login/logout, timer and exit on 401; clears the cache.
frontend/src/lib/api.jsAxios instance, baseURL, 10-second timeout, in-memory token and Authorization interceptor.
frontend/src/pages/LoginPage.jsxCredential form and useMutation for login; saves the session on completion.
frontend/src/pages/RegisterPage.jsxPublic registration form; receives JWT and starts the session.
frontend/src/pages/WelcomePage.jsxWelcome and authenticated account details.
frontend/src/pages/UsersPage.jsxList, in-memory search, creation/edit form, activation, roles and deletion confirmation.
frontend/src/pages/LearnPage.jsxExplanation of the application's authentication flow.
frontend/src/styles.cssInterface styling with Tailwind CSS 4 and lab classes.
compose.ymlFull deployment: MySQL, Spring Boot and React with Nginx; healthchecks, restart and persistent volume.
.dockerignoreExcludes secrets and generated files from the build context.
backend.DockerfileBuilds and tests the JAR with Java 21 and Maven cache; runs as user spring.
frontend.DockerfileBuilds React with pnpm and serves static files with Nginx.
nginx.conf/api proxy to backend:7070, React fallback and /healthz route.
.env.examplePublic variable template. .env contains private local values and is not linked here.
docs/COMO_FUNCIONA.mdAn educational walkthrough of a request from start to finish.
docs/peticiones.httpExample HTTP request collection.

Generated documentation

Technical documentation is regenerated from sources. Run mvn -f backend/pom.xml javadoc:javadoc and copy backend/target/reports/apidocs to docs/javadoc to update the backend Javadoc. Run pnpm --dir frontend docs to update the frontend JSDoc. Frontend configuration is in frontend/jsdoc.json and its guide in frontend/JSDOC.md.

How the layers connect

In CRUD, the controller translates HTTP into Java calls and returns DTOs. The service decides business rules and defines transaction boundaries. The repository expresses persistence operations; Hibernate implements JPA access and MySQL stores state. This separation lets a business rule change without rewriting the screen.

Authentication has its own flow: AuthController uses AuthenticationManager for login and the repository directly for registration; there is no separate AuthService. Do not assume layers absent from the code. SecurityConfig configures Spring objects; it exposes no endpoints.

Annotations worth recognising

Annotation / conceptWhat to look for in this project
@SpringBootApplicationStartup and component discovery.
@Configuration / @BeanDeclaration of components such as SecurityFilterChain or PasswordEncoder.
@RestController / @RequestMappingClass handling routes and serialising JSON responses.
@Valid / @RequestBodyMandatory input JSON deserialisation and validation.
@Service / @TransactionalBusiness rules and unit of work; reads marked readOnly.
@Entity / @Id / @GeneratedValueTable mapping and autogenerated key.
@AuthenticationPrincipal JwtAccess to the validated token associated with the request.
recordImmutable data object used for DTOs.
Constructor injectionSpring supplies each class's dependencies instead of controllers creating them with new.

A reading order to stay oriented

  1. AuthController.login → SecurityConfig.authenticationManager → userDetailsService.
  2. JwtService.issue → jwtKey → jwtEncoder → jwtDecoder.
  3. securityFilterChain → JWT converter → UserController.me.
  4. AppUser → SQL migration → UserRepository → UserService.
  5. api.js → AuthContext → App.jsx → UsersPage.
  6. SecurityIntegrationTest: each test is an executable example of a rule.
CV & portfolio · ES / EN
EspañolEnglish