Security Guide

Application Security Architecture: Azure and AWS Best Practices

A zero-trust security architecture for Java and Kubernetes workloads, with every control shown side by side for Microsoft Azure and Amazon AWS.

  • Zero Trust
  • Microsoft Azure
  • Amazon AWS
  • Kubernetes
  • Container Security
Select Cloud Provider:

1. Introduction

This document outlines a comprehensive security architecture for Java Maven applications deployed in Kubernetes on either Microsoft AzureAmazon AWS. The architecture follows a Zero Trust security model and incorporates best practices to address common security gaps and enhance overall security posture.

The recommendations are based on the principles of defense in depth, secure by design, and continuous monitoring, tailored to the specific needs of Java-based applications in a cloud-native environment.

Note: This guide is cloud-agnostic in principle but provides specific implementations for both Azure and AWS. Use the toggle above to switch between cloud provider-specific services and configurations.

2. Overall Architecture - Zero Trust Approach

Adopt a Zero Trust security model to ensure robust protection across all components. Key principles include:

  • Never trust, always verify: Authenticate and authorize all users, devices, and services before granting access.
  • Least privilege access: Grant minimal permissions necessary for each role or function.
  • Defense in depth: Implement multiple layers of security controls to mitigate risks.
  • Secure by design: Integrate security into the application and infrastructure from the outset.
  • Continuous monitoring: Regularly monitor and assess the environment for threats and vulnerabilities.

3. Client-Side Security (Object Storage)

Secure client-side interactions with object storage and frontend content delivery:

  • Enable HTTPS-only access to Azure Blob StorageAmazon S3 to ensure encrypted data transfer.
  • Implement strict Cross-Origin Resource Sharing (CORS) policies to control access to resources.
  • Use Azure Content Delivery Network (CDN) with Web Application Firewall (WAF)Amazon CloudFront with AWS WAF for secure frontend content delivery.
  • Implement Content Security Policy (CSP) headers to mitigate cross-site scripting (XSS) attacks.
  • Consider Azure Front DoorAWS Global Accelerator for enhanced protection, including global load balancing and additional WAF capabilities.

Azure-Specific Implementation

  • Enable Azure Blob Storage encryption at rest using Azure Storage Service Encryption (SSE)
  • Use Shared Access Signatures (SAS) with time-limited tokens for temporary access
  • Enable Azure Storage Analytics for monitoring and auditing
  • Implement Private Endpoints for Blob Storage to restrict public access

AWS-Specific Implementation

  • Enable S3 encryption at rest using AWS KMS or S3-managed keys
  • Use Pre-signed URLs with time-limited access for temporary object access
  • Enable S3 Access Logging and CloudTrail for monitoring
  • Implement VPC Endpoints for S3 to restrict public access
  • Use S3 Block Public Access settings to prevent accidental exposure

4. Authentication and Authorization

Strengthen authentication and authorization mechanisms:

  • Utilize Microsoft Identity Platform (Azure AD / Entra ID)Amazon Cognito or AWS IAM Identity Center for centralized identity management.
  • Implement robust token validation on all backend services to prevent unauthorized access.
  • Use OAuth 2.0 with Proof Key for Code Exchange (PKCE) for secure authentication flows.
  • Enforce JSON Web Token (JWT) validation policies at the application gateway level.
  • Apply Conditional Access policies to enable risk-based authentication, adapting to user and device risk levels.

Azure Authentication Architecture

  • Azure AD App Registrations: Create separate registrations for frontend and backend applications
  • Managed Identities: Use system-assigned or user-assigned managed identities for Azure resources
  • Conditional Access: Configure policies based on location, device compliance, and risk signals
  • Azure AD B2C: For customer-facing applications requiring social identity providers
  • Privileged Identity Management (PIM): For just-in-time administrative access

AWS Authentication Architecture

  • Amazon Cognito User Pools: Manage user directories and authentication flows
  • Amazon Cognito Identity Pools: Provide temporary AWS credentials for authenticated users
  • IAM Roles for Service Accounts (IRSA): Fine-grained permissions for Kubernetes pods
  • AWS IAM Identity Center: For workforce identity and SSO across AWS accounts
  • AWS Organizations SCP: Enforce security policies across multiple accounts

5. Application Gateway Security

Enhance security at the application gateway level:

  • Enable Web Application Firewall (WAF) protection on WAF_v2 tier Application GatewaysApplication Load Balancers (ALB).
  • Configure custom WAF rules to address Java-specific vulnerabilities, such as injection attacks and deserialization exploits.
  • Enforce TLS 1.2 or higher with secure cipher suites to protect data in transit.
  • Implement network segmentation between application tiers to limit lateral movement.
  • Enable diagnostic logging to Azure SentinelAmazon Security Lake or CloudWatch Logs for real-time threat detection and response.

Azure Application Gateway Configuration

# Enable WAF on Application Gateway
resource "azurerm_application_gateway" "main" {
  name                = "appgateway"
  resource_group_name = azurerm_resource_group.main.name
  location            = azurerm_resource_group.main.location

  sku {
    name     = "WAF_v2"
    tier     = "WAF_v2"
    capacity = 2
  }

  waf_configuration {
    enabled                  = true
    firewall_mode            = "Prevention"
    rule_set_type            = "OWASP"
    rule_set_version         = "3.2"
    file_upload_limit_mb     = 100
    request_body_check       = true
    max_request_body_size_kb = 128
  }

  ssl_policy {
    policy_type = "Predefined"
    policy_name = "AppGwSslPolicy20220101"
  }
}

AWS Application Load Balancer Configuration

# Create ALB with WAF
resource "aws_lb" "main" {
  name               = "app-lb"
  internal           = false
  load_balancer_type = "application"
  security_groups    = [aws_security_group.alb.id]
  subnets            = aws_subnet.public[*].id

  enable_deletion_protection = true
  enable_http2              = true
  enable_waf_fail_open      = false
}

# Attach WAF WebACL
resource "aws_wafv2_web_acl_association" "main" {
  resource_arn = aws_lb.main.arn
  web_acl_arn  = aws_wafv2_web_acl.main.arn
}

# Configure SSL/TLS policy
resource "aws_lb_listener" "https" {
  load_balancer_arn = aws_lb.main.arn
  port              = "443"
  protocol          = "HTTPS"
  ssl_policy        = "ELBSecurityPolicy-TLS13-1-2-2021-06"
  certificate_arn   = aws_acm_certificate.main.arn

  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.main.arn
  }
}

6. Kubernetes Security

Secure the Azure Kubernetes Service (AKS)Amazon Elastic Kubernetes Service (EKS) environment:

  • Implement Role-Based Access Control (RBAC) with least privilege principles.
  • Use Kubernetes Network Policies to restrict pod-to-pod communication.
  • Enable Azure Policy for KubernetesAWS Config with EKS Rules to enforce compliance with security standards.
  • Apply Pod Security Standards (PSS) to enforce secure pod configurations.
  • Deploy private clusters with private endpoints to minimize exposure.
  • Enable Microsoft Defender for ContainersAmazon GuardDuty for EKS to monitor and protect Kubernetes workloads.
  • Implement secrets management using Azure Key Vault with CSI driverAWS Secrets Manager with CSI driver or External Secrets Operator.

AKS Security Best Practices

  • Private Cluster: Deploy AKS with private API server endpoint
  • Azure CNI: Use Azure Container Networking Interface for advanced networking
  • Azure Policy Add-on: Enforce pod security standards using Gatekeeper
  • Workload Identity: Use Azure AD workload identity for pod-level authentication
  • Defender for Containers: Enable runtime threat detection and vulnerability scanning
  • Network Policies: Use Calico or Azure Network Policy for micro-segmentation

EKS Security Best Practices

  • Private Endpoint: Deploy EKS with private API server endpoint
  • VPC CNI: Use AWS VPC CNI plugin for pod networking with security groups
  • Pod Security Standards: Enforce PSS using admission controllers
  • IRSA: Use IAM Roles for Service Accounts for fine-grained permissions
  • GuardDuty: Enable EKS Protection for runtime threat detection
  • Calico: Deploy Calico for network policies and encryption in transit

7. Container Security

Ensure container-level security for Java applications:

  • Use minimal base images, such as Google's Distroless for Java, to reduce attack surfaces.
  • Integrate image scanning in the CI/CD pipeline using Microsoft Defender for Container RegistriesAmazon ECR Image Scanning to detect vulnerabilities.
  • Run containers as non-root users to limit privilege escalation risks.
  • Use read-only file systems for containers where feasible to prevent unauthorized changes.
  • Set resource limits (CPU, memory) to mitigate resource exhaustion attacks.
  • Use Azure Container Registry with private linksAmazon ECR with VPC endpoints for secure image storage and access.
  • Sign container images using Notation and Azure Key VaultAWS Signer.

Sample Secure Dockerfile for Java

# Multi-stage build for Java Maven application
FROM maven:3.9-eclipse-temurin-21 AS builder
WORKDIR /app
COPY pom.xml .
RUN mvn dependency:go-offline
COPY src ./src
RUN mvn clean package -DskipTests

# Use distroless for minimal attack surface
FROM gcr.io/distroless/java21-debian12:nonroot
WORKDIR /app

# Copy only the built artifact
COPY --from=builder /app/target/*.jar app.jar

# Non-root user (already default in distroless:nonroot)
USER nonroot

# Read-only filesystem
# Set in Kubernetes deployment with readOnlyRootFilesystem: true

EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]

8. Java Application Security

Secure the Java application code and dependencies:

  • Regularly update dependencies using tools like Dependabot, Renovate, or OWASP Dependency-Check.
  • Implement input validation and output encoding to prevent injection attacks (SQL, LDAP, Command, etc.).
  • Leverage Spring Security (if using Spring Framework) for authentication and authorization.
  • Implement secure logging practices, avoiding exposure of sensitive data in logs.
  • Follow OWASP Top 10 guidelines for Java to address common vulnerabilities.
  • Implement robust error handling to prevent information leakage through stack traces.
  • Use prepared statements and parameterized queries to prevent SQL injection.
  • Disable XML External Entity (XXE) processing to prevent XXE attacks.
  • Implement proper session management with secure, HTTP-only, and SameSite cookies.

Spring Security Configuration Example

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authz -> authz
                .requestMatchers("/public/**").permitAll()
                .requestMatchers("/api/**").authenticated()
                .anyRequest().denyAll()
            )
            .oauth2ResourceServer(oauth2 -> oauth2
                .jwt(jwt -> jwt
                    .jwtAuthenticationConverter(jwtAuthenticationConverter())
                )
            )
            .csrf(csrf -> csrf
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            )
            .headers(headers -> headers
                .contentSecurityPolicy("default-src 'self'")
                .frameOptions().deny()
                .xssProtection().block(true)
            )
            .sessionManagement(session -> session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            );

        return http.build();
    }
}

9. API Security

Secure APIs exposed by the application:

  • Implement rate limiting using Azure API Management or Application GatewayAWS API Gateway or ALB to prevent abuse and denial-of-service attacks.
  • Apply IP restrictions where appropriate to limit access to trusted sources.
  • Validate all API inputs using schema validation (JSON Schema, OpenAPI).
  • Enforce authentication and authorization for all API endpoints.
  • Implement API schema validation to ensure data integrity and consistency.
  • Use API versioning to manage breaking changes securely.
  • Implement comprehensive logging of API requests and responses (excluding sensitive data).
  • Apply request size limits to prevent payload-based attacks.

Azure API Management Policies

<policies>
    <inbound>
        <base />
        <!-- Rate limiting -->
        <rate-limit-by-key calls="100" renewal-period="60"
            counter-key="@(context.Request.IpAddress)" />

        <!-- Validate JWT -->
        <validate-jwt header-name="Authorization"
            failed-validation-httpcode="401">
            <openid-config url="https://login.microsoftonline.com/tenant/.well-known/openid-configuration" />
            <audiences>
                <audience>api://your-api-id</audience>
            </audiences>
        </validate-jwt>

        <!-- IP filtering -->
        <ip-filter action="allow">
            <address>10.0.0.0/8</address>
        </ip-filter>
    </inbound>
</policies>

AWS API Gateway Configuration

resource "aws_api_gateway_rest_api" "main" {
  name = "secure-api"

  endpoint_configuration {
    types = ["REGIONAL"]
  }
}

# Usage plan with throttling
resource "aws_api_gateway_usage_plan" "main" {
  name = "api-usage-plan"

  throttle_settings {
    burst_limit = 100
    rate_limit  = 50
  }

  quota_settings {
    limit  = 10000
    period = "DAY"
  }
}

# Cognito authorizer
resource "aws_api_gateway_authorizer" "cognito" {
  name          = "cognito-authorizer"
  type          = "COGNITO_USER_POOLS"
  rest_api_id   = aws_api_gateway_rest_api.main.id
  provider_arns = [aws_cognito_user_pool.main.arn]
}

# WAF for API Gateway
resource "aws_wafv2_web_acl_association" "api" {
  resource_arn = aws_api_gateway_stage.prod.arn
  web_acl_arn  = aws_wafv2_web_acl.main.arn
}

10. Monitoring and Continuous Assessment

Establish a robust monitoring and assessment framework:

Weekly Activities

  • Review WAF logs and alerts for blocked requests and attack patterns.
  • Analyze API traffic patterns for anomalies using Azure Monitor and Application InsightsCloudWatch and X-Ray.
  • Investigate security incidents and alerts from Microsoft DefenderGuardDuty and Security Hub.
  • Review authentication failures and suspicious login attempts.

Monthly Activities

  • Evaluate policy effectiveness and update security rules as needed.
  • Assess new APIs for security compliance before production deployment.
  • Review access logs and audit trails for compliance.
  • Update dependency versions and patch vulnerabilities.
  • Conduct security training and awareness sessions for development teams.

Quarterly Activities

  • Conduct comprehensive penetration testing and vulnerability assessments.
  • Perform architecture reviews to identify gaps and improvement areas.
  • Review and update disaster recovery and incident response plans.
  • Audit compliance with industry standards (PCI-DSS, SOC 2, ISO 27001, etc.).
  • Review and optimize security costs and resource allocation.

Azure Monitoring Stack

  • Azure Monitor: Centralized monitoring and alerting platform
  • Application Insights: APM for application performance and behavior
  • Log Analytics Workspace: Centralized log collection and analysis
  • Microsoft Sentinel: SIEM and SOAR for security operations
  • Microsoft Defender for Cloud: CSPM and CWPP capabilities
  • Azure Service Health: Platform health and service notifications

AWS Monitoring Stack

  • Amazon CloudWatch: Metrics, logs, and alarms
  • AWS X-Ray: Distributed tracing for applications
  • Amazon Security Lake: Centralized security data lake
  • AWS Security Hub: Aggregated security findings and compliance
  • Amazon GuardDuty: Threat detection service
  • AWS Config: Configuration compliance and change tracking
  • AWS Health Dashboard: Service health and operational events

11. Service Comparison Matrix

Security Domain Azure Service AWS Service
Identity & Access Management Azure AD / Entra ID AWS IAM, Cognito, Identity Center
Container Orchestration Azure Kubernetes Service (AKS) Elastic Kubernetes Service (EKS)
Container Registry Azure Container Registry (ACR) Elastic Container Registry (ECR)
Object Storage Azure Blob Storage Amazon S3
Application Gateway / Load Balancer Azure Application Gateway Application Load Balancer (ALB)
Web Application Firewall Azure WAF AWS WAF
CDN Azure CDN / Front Door Amazon CloudFront
Secrets Management Azure Key Vault AWS Secrets Manager / Parameter Store
Container Security Microsoft Defender for Containers GuardDuty for EKS, ECR Scanning
SIEM / Security Operations Microsoft Sentinel Amazon Security Lake
Cloud Security Posture Microsoft Defender for Cloud AWS Security Hub
Threat Detection Microsoft Defender Amazon GuardDuty
Network Policies Azure Network Policies / Calico VPC CNI Security Groups / Calico
Monitoring & Logging Azure Monitor / Log Analytics CloudWatch / X-Ray
Compliance & Governance Azure Policy AWS Config / Organizations SCP

12. Conclusion

This security architecture provides a multi-layered, defense-in-depth approach to securing Java Maven applications in Kubernetes on both Microsoft Azure and Amazon AWS. By addressing common security gaps and implementing cloud-native best practices, this architecture ensures robust protection against modern threats while maintaining scalability, performance, and operational efficiency.

Key takeaways:

  • Adopt a Zero Trust security model across all layers of the application stack.
  • Leverage cloud-native security services specific to your chosen platform.
  • Implement defense in depth with multiple security controls at each layer.
  • Automate security scanning and compliance checks in CI/CD pipelines.
  • Establish continuous monitoring and regular security assessments.
  • Maintain a strong security culture through training and awareness programs.

Continuous monitoring, regular assessments, and adaptation to emerging threats will help maintain a strong security posture as your environment evolves. Security is not a one-time implementation but an ongoing process of improvement and adaptation.

Remember: Security is a shared responsibility. While cloud providers secure the infrastructure, you are responsible for securing your applications, data, and access controls.

Document Version: 1.0 Last Updated: November 2025 Maintainer: Technical Documentation Team

Next step

Talk to a security consultant

Tell us what you are building, defending or certifying. We will tell you plainly what we would test first, what it takes, and whether you need us at all.