Implementation Example: Service-to-Service Authentication with JWT and mTLS
// Spring Boot service with JWT authentication for outbound requests
@Service
public class SecureApiClient {
private final RestTemplate restTemplate;
private final TokenService tokenService;
public SecureApiClient(RestTemplate restTemplate, TokenService tokenService) {
this.restTemplate = restTemplate;
this.tokenService = tokenService;
}
public ResponseEntity<ProductResponse> getProduct(String productId) {
// Get service-to-service JWT token
String token = tokenService.getServiceToken("product-service");
// Create headers with token
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(token);
// Create request entity
HttpEntity<Void> requestEntity = new HttpEntity<>(headers);
// Make authenticated request
return restTemplate.exchange(
"https://product-service/products/" + productId,
HttpMethod.GET,
requestEntity,
ProductResponse.class
);
}
}
// Configuration for mTLS
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() throws Exception {
// Load client certificate and key
Resource keyStoreFile = new ClassPathResource("keystore.p12");
char[] keyStorePassword = "password".toCharArray();
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(keyStoreFile.getInputStream(), keyStorePassword);
// Set up SSL context with client certificate
SSLContext sslContext = SSLContextBuilder.create()
.loadKeyMaterial(keyStore, keyStorePassword)
.loadTrustMaterial(null, new TrustSelfSignedStrategy())
.build();
// Create SSL connection factory
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
sslContext,
new String[] { "TLSv1.2", "TLSv1.3" },
null,
NoopHostnameVerifier.INSTANCE);
// Create HTTP client with SSL support
HttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(socketFactory)
.build();
// Create request factory with HTTP client
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory(httpClient);
// Create and return RestTemplate
return new RestTemplate(requestFactory);
}
}
2. API Security
APIs are the primary interface for distributed systems and require comprehensive Zero Trust protection.
Implementation Example: API Gateway with OAuth 2.0, Rate Limiting, and Request Validation
# Kong API Gateway configuration
_format_version: "2.1"
_transform: true
services:
- name: user-service
url: http://user-service:8080
routes:
- name: user-routes
paths:
- /api/users
plugins:
- name: jwt
config:
claims_to_verify:
- exp
- nbf
- name: rate-limiting
config:
minute: 60
policy: local
- name: request-validator
config:
body_schema:
name: "string"
email: "string"
age: "number"
- name: cors
config:
origins:
- https://example.com
methods:
- GET
- POST
- PUT
- DELETE
headers:
- Authorization
- Content-Type
exposed_headers:
- X-Auth-Token
credentials: true
max_age: 3600
- name: ip-restriction
config:
allow:
- 192.168.1.0/24
- 10.0.0.0/8
consumers:
- username: frontend-app
jwt_secrets:
- algorithm: RS256
key: "frontend-app-key"
rsa_public_key: |
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyFDN...
-----END PUBLIC KEY-----
3. Data Access Security
Zero Trust requires fine-grained control over data access, with continuous verification of access rights.
Implementation Example: Row-Level Security in PostgreSQL
-- Create users table with row-level security
CREATE TABLE users (
id SERIAL PRIMARY KEY,
username TEXT NOT NULL,
email TEXT NOT NULL,
department TEXT NOT NULL,
data JSONB NOT NULL
);
-- Enable row-level security
ALTER TABLE users ENABLE ROW LEVEL SECURITY;
-- Create policy for department-based access
CREATE POLICY department_isolation ON users
USING (department = current_setting('app.current_department', TRUE))
WITH CHECK (department = current_setting('app.current_department', TRUE));
-- Function to set department context based on JWT claims
CREATE OR REPLACE FUNCTION set_user_context() RETURNS VOID AS $$
DECLARE
jwt_claims JSONB;
BEGIN
-- In a real implementation, this would extract and validate JWT from request
jwt_claims := current_setting('request.jwt.claims', TRUE)::JSONB;
-- Set department from JWT claims
PERFORM set_config('app.current_department', jwt_claims->>'department', FALSE);
-- Set additional context variables as needed
PERFORM set_config('app.user_id', jwt_claims->>'sub', FALSE);
END;
$$ LANGUAGE plpgsql;
-- Example usage in application code
-- 1. Call set_user_context() at the beginning of each transaction
-- 2. Then perform regular queries that will be automatically filtered
4. Device Trust and Endpoint Security
Zero Trust extends to the devices accessing your systems, requiring verification of device security posture.
Implementation Example: Device Posture Check with Azure AD Conditional Access
{
"displayName": "Require compliant device for all applications",
"state": "enabled",
"conditions": {
"clientAppTypes": ["all"],
"applications": {
"includeApplications": ["All"]
},
"users": {
"includeGroups": ["all_users"],
"excludeGroups": ["emergency_access_accounts"]
},
"locations": {
"includeLocations": ["All"],
"excludeLocations": ["AllTrusted"]
},
"platforms": {
"includePlatforms": ["all"]
}
},
"grantControls": {
"operator": "AND",
"builtInControls": ["compliantDevice", "domainJoinedDevice"]
},
"sessionControls": {
"applicationEnforcedRestrictions": {
"isEnabled": true
},
"cloudAppSecurity": {
"isEnabled": true,
"cloudAppSecurityType": "monitorOnly"
},
"signInFrequency": {
"value": 4,
"type": "hours",
"isEnabled": true
},
"persistentBrowser": {
"isEnabled": true,
"mode": "never"
}
}
}
Zero Trust Implementation Patterns
Several patterns have emerged for implementing Zero Trust in distributed systems. Let’s explore the most effective ones.