{"id":19283550,"url":"https://github.com/ionutbalosin/java-application-security-practices","last_synced_at":"2025-04-22T02:33:12.056Z","repository":{"id":259048227,"uuid":"870037258","full_name":"ionutbalosin/java-application-security-practices","owner":"ionutbalosin","description":"Application security best practices and code implementations for Java developers. This project is intended for didactic purposes only, supporting my training course.","archived":false,"fork":false,"pushed_at":"2025-04-13T07:57:42.000Z","size":4075,"stargazers_count":37,"open_issues_count":0,"forks_count":9,"subscribers_count":4,"default_branch":"main","last_synced_at":"2025-04-13T08:42:34.666Z","etag":null,"topics":["api-security","authorization-code-flow","authorization-code-flow-with-pkce","client-credentials-flow","cors","csp","dast","java-process-security","json-web-key-set","jwks","oauth-grant-types","password-flow","roles-based-access-control","sast","sca","security-design-principles","security-logging","security-testing","token-introspection"],"latest_commit_sha":null,"homepage":"https://ionutbalosin.com/training/application-security-for-java-developers-course","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ionutbalosin.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"license/LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"security-feign-logger-enricher/pom.xml","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-10-09T10:32:19.000Z","updated_at":"2025-04-13T07:57:46.000Z","dependencies_parsed_at":"2024-10-25T15:53:10.805Z","dependency_job_id":"b6ef1c86-75c6-49d3-a8a2-009bb482ac63","html_url":"https://github.com/ionutbalosin/java-application-security-practices","commit_stats":null,"previous_names":["ionutbalosin/java-application-security-practices"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ionutbalosin%2Fjava-application-security-practices","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ionutbalosin%2Fjava-application-security-practices/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ionutbalosin%2Fjava-application-security-practices/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ionutbalosin%2Fjava-application-security-practices/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ionutbalosin","download_url":"https://codeload.github.com/ionutbalosin/java-application-security-practices/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250163819,"owners_count":21385320,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api-security","authorization-code-flow","authorization-code-flow-with-pkce","client-credentials-flow","cors","csp","dast","java-process-security","json-web-key-set","jwks","oauth-grant-types","password-flow","roles-based-access-control","sast","sca","security-design-principles","security-logging","security-testing","token-introspection"],"created_at":"2024-11-09T21:33:41.308Z","updated_at":"2025-04-22T02:33:12.036Z","avatar_url":"https://github.com/ionutbalosin.png","language":"Java","readme":"\u003cp align=\"center\"\u003e\n  \u003cimg alt=\"eCommerce\" title=\"eCommerce\" src=\"assets/images/hedgehog_logo_200.png\"\u003e\n\u003c/p\u003e\n\n\u003ch1 align=\"center\"\u003eJava Application Security Practices\u003c/h1\u003e\n\u003ch4 align=\"center\"\u003e⚡️ Secure by Design: Empowering Java Developers with Best Practices. ⚡️\u003c/h4\u003e\n\n---\n\nThis 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.\n\nThese examples are designed to complement the curriculum of the 📚 [Application Security for Java Developers](https://ionutbalosin.com/training/application-security-for-java-developers-course) Course. \n\nIf you're looking to take your skills to the next level, 🎓 [enroll now](https://ionutbalosin.com/training/application-security-for-java-developers-course) and master the art of secure coding in Java!\n\nFor more resources and insights, feel free to visit my [website](https://ionutbalosin.com).\n\n---\n\n## Content\n\n- [Security Concepts](#security-concepts)\n- [Publications](#publications)\n- [Project Modules](#project-modules)\n- [Architectural Diagrams](#architectural-diagrams)\n  - [Software Architecture Diagram](#software-architecture-diagram)\n  - [Sequence Diagram](#sequence-diagram) \n- [Technology Stack](#technology-stack)\n- [SetUp](#setup)\n- [Security Checks](#security-checks)\n  - [OWASP Dependency-Check](#owasp-dependency-check)\n  - [SpotBugs with FindSecBugs Plugin](#spotbugs-with-findsecbugs-plugin)\n  - [Zed Attack Proxy (ZAP)](#zed-attack-proxy-zap)\n- [License](#license)\n\n## Security Concepts\n\nAmong the **security concepts** demonstrated in this project:\n\n- Security Design Principles\n  - Least privilege\n  - Defense in depth\n  - Fail securely\n  - Compartmentalization\n- OAuth 2.0 Grant Types:\n  - Password Flow\n  - Client Credentials Flow\n  - Authorization Code Flow\n  - Authorization Code Flow with Proof Key for Code Exchange (PKCE)\n- API and Microservices Security\n  - Token introspection\n  - JSON Web Key Set (JWKS)\n  - Roles-based access control\n- Symmetric and Asymmetric Encryption\n  - Symmetric Encryption\n  - Asymmetric Encryption\n- Hashing\n  - Message Hashing\n  - Hash-Based Message Authentication\n  - Password Hashing\n- Java Process Security\n  - Input data validation and sanitization\n  - Handling input files from external sources\n  - Security logging best practices\n  - Content Security Policy (CSP)\n  - Cross-Origin Resource Sharing (CORS)\n  - HTTP security headers (e.g., Strict-Transport-Security, X-XSS-Protection, X-Frame-Options)\n  - Java deserialization\n- Security Testing\n  - Software Composition Analysis (SCA)\n  - Static Application Security Testing (SAST)\n  - Dynamic Application Security Testing (DAST)\n\n## Publications\n\nCurrent publications that further describe the concepts presented in this repository can be found at:\n- [Core Application Security for Java Developers](https://ionutbalosin.com/2025/03/core-application-security-for-java-developers)\n- [API Web Application Security for Java Developers](https://ionutbalosin.com/2025/03/api-web-application-security-for-java-developers)\n- [Security Application Testing for Java Developers](https://ionutbalosin.com/2025/03/security-application-testing-for-java-developers)\n\n## Project Modules\n\nBelow is a breakdown and description of each module in the current project.\n\nModule                                                  | Description                                                                                                                                                                                                                                                                                                                                             |\n------------------------------------------------------- |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n`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.                                                                                                   |\n`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.                                                                                                                                                                                          |\n`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.                                                                                                                                                                             |\n`security-token-client-credentials-fetcher`             | Fetches tokens from the Identity Provider (IdP) using the client credentials flow.                                                                                                                                                                                                                                                                      |\n`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.           |\n`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.                                                              |\n`serialization-deserialization`                         | Demonstrates security risks in serialization and deserialization, including exploits like Java class deserialization attacks, XML external entities, YAML bombs, and ZIP bombs.                                                                                                                                                                         |\n`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.   |\n\n## Architectural Diagrams\n\n### Software Architecture Diagram\n\nThis 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.\n\n\u003cimg src=\"assets/diagrams/software-architecture-diagram.svg\"\u003e\n\n### Sequence Diagram\n\n```mermaid\nsequenceDiagram\nactor User\nUser-\u003e\u003eIdP: Authenticate and fetch JWT (authorization code flow)\nUser-\u003e\u003ePizza Order Service: Submit order with JWT as HTTP Bearer token\nPizza Order Service-\u003e\u003eIdP: Introspect JWT to verify validity\nPizza Order Service-\u003e\u003ePizza Order Service: Check user roles/permissions\nPizza Order Service-\u003e\u003ePizza Cooking Service: Submit cooking order with JWT as HTTP Bearer token\nPizza Cooking Service-\u003e\u003eIdP: Fetch JWKS keys (if missing or expired) for local JWT validation\nPizza Cooking Service-\u003e\u003ePizza Cooking Service: Validate JWT signature using JWKS\nPizza Cooking Service-\u003e\u003ePizza Cooking Service: Check user roles/permissions\n\nNote right of Pizza Cooking Service: Pizza is cooked ...\n\nPizza Cooking Service-\u003e\u003eIdP: Fetch JWT (client credentials flow)\nPizza Cooking Service-\u003e\u003ePizza Delivery Service: Submit delivery order with JWT as HTTP Bearer token\nPizza Delivery Service-\u003e\u003eIdP: Fetch JWKS keys (if missing or expired) for local JWT validation\nPizza Delivery Service-\u003e\u003ePizza Delivery Service: Validate JWT signature using JWKS\nPizza Delivery Service-\u003e\u003ePizza Delivery Service: Check user roles/permissions\nPizza Delivery Service-\u003e\u003ePizza Delivery Service: Confirm order delivered\nPizza Delivery Service-\u003e\u003ePizza Order Service: Send order status update\nPizza Order Service-\u003e\u003eIdP: Introspect JWT to verify validity\nPizza Order Service-\u003e\u003ePizza Order Service: Check user roles/permissions\nPizza Order Service-\u003e\u003ePizza Order Service: Update order status\n```\n\n## Technology Stack\n\nThis project includes the following **technologies, frameworks, and libraries**:\n\n- [Spring Boot](https://spring.io/projects/spring-boot)\n- [Spotless](https://github.com/diffplug/spotless) as a code formatter\n- [Docker compose](https://docs.docker.com/compose/)\n- [Keycloak](https://www.keycloak.org/) as an Identity and Access Management solution\n- [OWASP Dependency-Check](https://owasp.org/www-project-dependency-check) as a Software Composition Analysis (SCA) tool\n- [Spotbugs](https://spotbugs.github.io/) with [FindSecBugs plugin](https://find-sec-bugs.github.io/) as a Static Application Security Testing (SAST) tool\n- [The Zed Attack Proxy (ZAP)](https://github.com/zaproxy/zaproxy) as a Dynamic Application Security Testing (DAST) tool\n- [OWASP WebGoat](https://owasp.org/www-project-webgoat) a deliberately insecure application\n\n## SetUp\n\n### Tools to Download and Install\n\nPlease ensure you have properly downloaded, installed, and configured the following tools:\n\nTool                         | Link                                                                                              |\n---------------------------- |---------------------------------------------------------------------------------------------------|\nJDK 21                       | [Download](https://projects.eclipse.org/projects/adoptium.temurin/downloads) _(i.e., latest LTS)_ |\nDocker                       | [Download](https://docs.docker.com/engine/install/)                                               |\nPostman                      | [Download](https://www.postman.com/)                                                              |\n`curl` command line          | [Download](https://everything.curl.dev/install/index.html)                                        |\n`jq` command line            | [Download](https://jqlang.github.io/jq/download/)                                                 |\n\n\nThe 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: \n- [GIT bash](https://git-scm.com/downloads)\n- [Cygwin](https://www.cygwin.com/)\n- Windows Subsystem for Linux (WSL)\n \n### Compile, Run Tests, and Package\n\nTo compile the project, run tests, and package it, use the following command:\n\n```bash\n./mvnw clean package\n```\n\n### Bootstrap Services with Docker\n\n**Note:** Please ensure that the Docker daemon is running; otherwise, the commands will not execute successfully.\n\n1. Run the following command to start the `Keycloak` service in Docker:\n\n    ```bash\n    ./bootstrap-keycloak.sh\n    ```\n\n2. To start the `Pizza` application, which includes multiple microservices running in Docker, execute:\n   \n    ```bash\n    ./bootstrap-pizza-application.sh\n    ```\n\n3. Next, run the following command to start the `OWASP WebGoat` application in Docker:\n   \n    ```bash\n    ./bootstrap-webgoat.sh\n    ```\n\n4. Finally, check that all Docker containers are up and running by executing:\n\n    ```bash\n    docker ps -a\n    ```\n\n### Keycloak Configuration\n\nTo set up a basic Keycloak configuration, run the following script:\n\n```bash\n./keycloak-init.sh\n```\n\nThe script creates OAuth 2.0 clients, users, and roles under the `master` realm and assigns the roles to the users:\n\n Type         | Name                  | Password                           | Purpose                                     |\n--------------|-----------------------|------------------------------------|---------------------------------------------|\n User         | `demo_user`           | `Test1234!`                        | Used for authorization code flow with PKCE. |\n Client ID    | `demo_public_client`  | `6EuUNXQzFmxu6xwPHDvvoh56z1uzrBMw` | Used for authorization code flow.           |\n Client ID    | `demo_private_client` | `6EuUNXQzFmxu6xwPHDvvoh56z1uzrBMw` | Used for client credentials flow.           |\n\nThis setup utilizes [Keycloak's REST API](https://www.keycloak.org/docs-api/latest/rest-api/index.html) to perform these operations and provides output at each step, ensuring efficient user and client management within the Keycloak environment.\n\n### Services Overview via UI\n\nOpen a browser and navigate to http://localhost:9090 to access the **Keycloak UI** (using the credentials `admin:admin`).\n\nOpen a browser and navigate to http://localhost:9090/realms/master/.well-known/openid-configuration to access the **Keycloak OpenID Connect configuration**.\n\nOpen a browser and navigate to http://localhost:18080/public/swagger-ui/index.html to access the **Pizza Order OpenAPI definition**.\n\nOpen a browser and navigate to http://localhost:28080/public/swagger-ui/index.html to access the **Pizza Cooking OpenAPI definition**.\n\nOpen a browser and navigate to http://localhost:38080/public/swagger-ui/index.html to access the **Pizza Delivery OpenAPI definition**.\n\nOpen a browser and navigate to http://localhost:48080/WebGoat/login to access the **OWASP WebGoat UI**.\n\n### Local Tests with Postman\n\n1. Open `Postman` and import the [Postman collections](postman).\n2. To simulate a basic test scenario, follow these steps in the given sequence:\n  - a) Fetch the JWT token using either:\n    - The **Password Flow**:\n       ```\n       POST http://localhost:9090/realms/master/protocol/openid-connect/token\n       ```\n    - Or the **Client Credentials Flow**:\n       ```\n       POST http://localhost:9090/realms/master/protocol/openid-connect/token\n       ```      \n    - Or the **Authorization Code Flow with PKCE**:\n       ```\n       POST http://localhost:9090/realms/master/protocol/openid-connect/auth\n       ```   \n  - b) Initiate an order request to the `pizza-order-service`:\n       ```\n       POST http://localhost:18080/pizza/orders\n       ```\n\n## Security Checks\n\n### OWASP Dependency-Check\n\n[OWASP Dependency-Check](https://owasp.org/www-project-dependency-check) is an open-source **Software Composition Analysis (SCA)** tool that identifies vulnerabilities in project dependencies, helping reveal and address known security risks.\n\nTo check for potential dependency vulnerabilities, execute the following command:\n\n```bash\n./mvnw clean compile org.owasp:dependency-check-maven:check\n```\n\n**Note:** The first run of this command might take a significant amount of time (e.g., from a couple of minutes to even tens of minutes, depending on the internet connection) to initially download the [NVD Data Feeds](https://nvd.nist.gov/vuln/data-feeds) hosted by NIST. \n\n### SpotBugs with FindSecBugs Plugin\n\n[Spotbugs](https://spotbugs.github.io/) is an open-source static analysis tool that detects bugs in Java programs by analyzing bytecode.\n\nWith the help of the [FindSecBugs plugin](https://find-sec-bugs.github.io/) plugin, it can be used as a **Static Application Security Testing (SAST)** tool to identify security vulnerabilities in Java applications.\n\nTo check for potential code vulnerabilities, execute the following command:\n\n```bash\n./mvnw clean compile spotbugs:check\n```\n\n### Zed Attack Proxy (ZAP)\n\n[The Zed Attack Proxy (ZAP)](https://github.com/zaproxy/zaproxy) is an open-source **Dynamic Application Security Testing (DAST)** tool specifically designed for identifying vulnerabilities in applications during runtime.\n\nTo check for API security vulnerabilities, execute the following command:\n\n```bash\n./zap-scan.sh\n```\n\nThe command starts ZAP in Docker, launches an API scan using the [zap-api-scan rules](zap/zap-api-scan-rules.conf) against one of the services, and saves the scan report in the [./zap/reports](zap/reports) folder.\n\n## License\n\nThis project is licensed under the Apache License, Version 2.0.\n\nPlease see the [LICENSE](license/LICENSE) file for full license.\n\n```\n/*\n * Application Security for Java Developers\n *\n * Copyright (C) 2025 Ionut Balosin\n * Website:      www.ionutbalosin.com\n * Social Media:\n *   LinkedIn:   ionutbalosin\n *   Bluesky:    @ionutbalosin.bsky.social\n *   X:          @ionutbalosin\n *   Mastodon:   ionutbalosin@mastodon.social\n *\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n```","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fionutbalosin%2Fjava-application-security-practices","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fionutbalosin%2Fjava-application-security-practices","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fionutbalosin%2Fjava-application-security-practices/lists"}