Java Application Security Practices
⚡️ Secure by Design: Empowering Java Developers with Best Practices. ⚡️
This repository provides practical examples and code snippets aimed at helping Java developers implement security best practices. It covers key topics such as security design principles, authentication and authorization, API security, Java process security, common attack mitigations, and security testing - all essential for building secure Java applications.
These examples are designed to complement the curriculum of the 📚 Application Security for Java Developers Course.
If you're looking to take your skills to the next level, 🎓 enroll now and master the art of secure coding in Java!
For more resources and insights, feel free to visit my website.
Content
Security Concepts
Among the security concepts demonstrated in this project:
- Security Design Principles
- Least privilege
- Defense in depth
- Fail securely
- Compartmentalization
- OAuth 2.0 Grant Types:
- Password Flow
- Client Credentials Flow
- Authorization Code Flow
- Authorization Code Flow with Proof Key for Code Exchange (PKCE)
- API and Microservices Security
- Token introspection
- JSON Web Key Set (JWKS)
- Roles-based access control
- Symmetric and Asymmetric Encryption
- Symmetric Encryption
- Asymmetric Encryption
- Hashing
- Message Hashing
- Hash-Based Message Authentication
- Password Hashing
- Java Process Security
- Input data validation and sanitization
- Handling input files from external sources
- Security logging best practices
- Content Security Policy (CSP)
- Cross-Origin Resource Sharing (CORS)
- HTTP security headers (e.g., Strict-Transport-Security, X-XSS-Protection, X-Frame-Options)
- Java deserialization
- Security Testing
- Software Composition Analysis (SCA)
- Static Application Security Testing (SAST)
- Dynamic Application Security Testing (DAST)
Publications
Current publications that further describe the concepts presented in this repository can be found at:
Project Modules
Below is a breakdown and description of each module in the current project.
| Module |
Description |
pizza-order-*, pizza-cooking-*, pizza-delivery-* |
These modules represent 3 microservices and their APIs (Pizza Cooking, Delivery, and Order) that demonstrate various OAuth 2.0 flows (e.g., token introspection, JWKS, client credentials), roles-based access control and security logging concepts. |
security-feign-logger-enricher |
Enriches and enables standard Feign client logging with additional custom Mapped Diagnostic Context (MDC) attributes (e.g., correlation ID) using SLF4J's MDC. |
security-slf4j-logger-enricher |
Enriches SLF4J-based logging with security-specific attributes (e.g., remote host, remote port, user agent, request URI, request method, correlation ID) using SLF4J's MDC. |
security-token-client-credentials-fetcher |
Fetches tokens from the Identity Provider (IdP) using the client credentials flow. |
security-token-introspection |
Introspects and validates access tokens using the IdP's token introspection endpoint. Additionally, it disables security for specific /public endpoints (e.g., OpenAPI definition endpoint), configures CORS and Content Security Policy (CSP), adds HTTP security headers, and parses JWT claim roles, adding them as granted authorities. |
security-token-jwks |
Handles JSON Web Key Set (JWKS) validation and signature verification of JWT tokens using the IdP's JWKS endpoint. Additionally, it disables security for specific /public endpoints (e.g., OpenAPI definition endpoint) and parses JWT claim roles, adding them as granted authorities. |
serialization-deserialization |
Demonstrates security risks in serialization and deserialization, including exploits like Java class deserialization attacks, XML external entities, YAML bombs, and ZIP bombs. |
encryption-decryption |
Provides essential cryptographic techniques for securing data, including symmetric and asymmetric encryption, message hashing, HMAC, password hashing, and digital signatures. It offers practical examples for ensuring confidentiality, integrity, and authenticity in applications, such as verifying JWTs and safeguarding sensitive information. |
Architectural Diagrams
Software Architecture Diagram
This software architecture diagram illustrates the microservices as components within the system and highlights key security aspects, including OAuth 2.0 flows (e.g., Token introspection, JWKS) and endpoint roles checks.
Sequence Diagram
sequenceDiagram
actor User
User->>IdP: Authenticate and fetch JWT (authorization code flow)
User->>Pizza Order Service: Submit order with JWT as HTTP Bearer token
Pizza Order Service->>IdP: Introspect JWT to verify validity
Pizza Order Service->>Pizza Order Service: Check user roles/permissions
Pizza Order Service->>Pizza Cooking Service: Submit cooking order with JWT as HTTP Bearer token
Pizza Cooking Service->>IdP: Fetch JWKS keys (if missing or expired) for local JWT validation
Pizza Cooking Service->>Pizza Cooking Service: Validate JWT signature using JWKS
Pizza Cooking Service->>Pizza Cooking Service: Check user roles/permissions
Note right of Pizza Cooking Service: Pizza is cooked ...
Pizza Cooking Service->>IdP: Fetch JWT (client credentials flow)
Pizza Cooking Service->>Pizza Delivery Service: Submit delivery order with JWT as HTTP Bearer token
Pizza Delivery Service->>IdP: Fetch JWKS keys (if missing or expired) for local JWT validation
Pizza Delivery Service->>Pizza Delivery Service: Validate JWT signature using JWKS
Pizza Delivery Service->>Pizza Delivery Service: Check user roles/permissions
Pizza Delivery Service->>Pizza Delivery Service: Confirm order delivered
Pizza Delivery Service->>Pizza Order Service: Send order status update
Pizza Order Service->>IdP: Introspect JWT to verify validity
Pizza Order Service->>Pizza Order Service: Check user roles/permissions
Pizza Order Service->>Pizza Order Service: Update order status
Technology Stack
This project includes the following technologies, frameworks, and libraries:
SetUp
Tools to Download and Install
Please ensure you have properly downloaded, installed, and configured the following tools:
The course is developed to work best on GNU/Linux. However, if you prefer to use a Windows machine, you can use one of the following alternatives to properly execute the bash scripts:
Compile, Run Tests, and Package
To compile the project, run tests, and package it, use the following command:
./mvnw clean package
Bootstrap Services with Docker
Note: Please ensure that the Docker daemon is running; otherwise, the commands will not execute successfully.
Run the following command to start the Keycloak service in Docker:
./bootstrap-keycloak.sh
To start the Pizza application, which includes multiple microservices running in Docker, execute:
./bootstrap-pizza-application.sh
Next, run the following command to start the OWASP WebGoat application in Docker:
./bootstrap-webgoat.sh
Finally, check that all Docker containers are up and running by executing:
docker ps -a
Keycloak Configuration
To set up a basic Keycloak configuration, run the following script:
./keycloak-init.sh
The script creates OAuth 2.0 clients, users, and roles under the master realm and assigns the roles to the users:
| Type |
Name |
Password |
Purpose |
| User |
demo_user |
Test1234! |
Used for authorization code flow with PKCE. |
| Client ID |
demo_public_client |
6EuUNXQzFmxu6xwPHDvvoh56z1uzrBMw |
Used for authorization code flow. |
| Client ID |
demo_private_client |
6EuUNXQzFmxu6xwPHDvvoh56z1uzrBMw |
Used for client credentials flow. |
This setup utilizes Keycloak's REST API to perform these operations and provides output at each step, ensuring efficient user and client management within the Keycloak environment.
Services Overview via UI
Open a browser and navigate to http://localhost:9090 to access the Keycloak UI (using the credentials admin:admin).
Open a browser and navigate to http://localhost:9090/realms/master/.well-known/openid-configuration to access the Keycloak OpenID Connect configuration.
Open a browser and navigate to http://localhost:18080/public/swagger-ui/index.html to access the Pizza Order OpenAPI definition.
Open a browser and navigate to http://localhost:28080/public/swagger-ui/index.html to access the Pizza Cooking OpenAPI definition.