Microservices offer scalability and flexibility but increase the attack surface. Securing Spring-based microservices requires a layered approach covering client, API gateway, services, data, and infrastructure.
1️⃣ Authentication & Authorization
-
Authentication – Verifies the identity of a user or system.
Example: Logging in with username/password or OAuth token. -
Authorization – Determines what a verified user can access (roles, permissions).
Example: Admins can access/admin/**
, users cannot.
Authentication Approaches in Spring
Authentication verifies who a user is. Spring provides multiple ways to implement it depending on your needs: stateless, session-based, enterprise directories, or external providers.
1) OAuth 2.0 / OpenID Connect
-
Definition: Token-based authentication via an external Identity Provider (IdP). Supports single sign-on and microservices.
-
Example IdPs: Keycloak, Okta, Auth0, AWS Cognito, Azure AD.
-
Token Type: Usually JWT.
-
How it Works:
-
Client requests login via IdP.
-
IdP authenticates and issues JWT access token.
-
Token sent with API requests (
Authorization: Bearer <token>
).
-
-
Spring Example (Resource Server):
-
Use Case: Microservices needing centralized authentication.
2) JWT (Stateless Token Authentication)
-
Definition: Self-contained token carrying user claims; no server session needed.
-
Usage:
Authorization: Bearer <token>
header. -
Advantages: Lightweight, scalable, can store roles/permissions.
-
Spring Example (Creating JWT):
-
Use Case: Stateless APIs and microservices.
3) Basic Authentication
-
Definition: Simple HTTP auth using username/password encoded in Base64.
-
Spring Example:
-
Use Case: Quick prototyping or internal APIs (always use HTTPS in production).
4) LDAP Authentication
-
Definition: Authenticate against Lightweight Directory Access Protocol (LDAP) server (e.g., corporate directories).
-
Spring Example:
-
Use Case: Corporate environments using centralized directories like Active Directory.
5) SAML (Security Assertion Markup Language)
-
Definition: XML-based protocol for single sign-on (SSO) in enterprise environments.
-
How it Works:
-
User logs in via Identity Provider (IdP).
-
IdP sends a SAML assertion to the Service Provider (SP).
-
SP validates and grants access.
-
-
Spring Example:
Use spring-security-saml2-service-provider dependency:
-
Use Case: Enterprise apps needing SSO across multiple systems.
6) API Key Authentication
-
Definition: Simple token-based access where clients include an API key in headers or query params.
-
Spring Example:
-
Use Case: Public APIs, microservices, or internal apps needing simple token access.
7) Form-Based Login
-
Definition: Traditional username/password login with session-based authentication.
-
Spring Example:
-
Use Case: Web applications with server-side session management.
Comparison Table of Authentication Approaches
Approach | Stateless | Token Type / Session | Use Case |
OAuth 2.0 | Yes | JWT | Centralized microservice auth |
JWT | Yes | JWT | Stateless API auth |
Basic Auth | No | None | Internal APIs, quick prototyping |
LDAP | No | None | Corporate directory auth |
SAML | No | XML Assertion | Enterprise SSO |
API Key | Yes | API key | Public/internal APIs |
Form Login | No | Session | Web apps, traditional login forms |
Authorization Approaches in Spring
Authorization determines what a user is allowed to do. Spring provides several ways to implement it, from roles to fine-grained permissions.
1) Role-Based Access Control (RBAC)
-
Definition: Grant access to resources based on user roles (e.g., ADMIN, USER).
-
How it Works:
-
Assign roles to users during authentication.
-
Use Spring Security to check roles when accessing endpoints.
-
-
Spring Example:
-
Use Case: Applications with simple role hierarchies, e.g., Admin vs Regular User.
2) Method-Level Security
-
Definition: Protect specific methods in controllers or services using annotations rather than only URL paths.
-
Annotations:
-
@PreAuthorize
– evaluates Spring Expression Language (SpEL) expressions before method execution. -
@PostAuthorize
– evaluates after method execution.
-
-
Spring Example:
-
How it Works: Only users with the required role can invoke the method; others get a 403 Forbidden response.
-
Use Case: When URL-based authorization is insufficient or you need method-specific control.
3) Permission-Based Authorization (Fine-Grained Control)
-
Definition: Instead of broad roles, use specific permissions or authorities (e.g.,
USER_READ
,USER_WRITE
). -
How it Works:
-
Assign authorities to roles or directly to users.
-
Use
@PreAuthorize
or@Secured
annotations to check permissions.
-
-
Spring Example:
-
Use Case: Applications needing fine-grained access control, e.g., editing vs reading data.
Quick Comparison Table
Authorization Type | Level | Example Use Case |
Role-Based (RBAC) | Endpoint / URL | Admin vs User access |
Method-Level Security | Method | Protect controller or service methods |
Permission-Based | Method / Endpoint | Fine-grained control (read/write access) |
2️⃣ API Gateway Security
API Gateway (Spring Cloud Gateway, Kong, Istio Ingress) is the entry point for requests.
Features & Examples
-
Token Validation: Verify JWT before routing.
-
Rate Limiting: Limit requests per IP/user.
-
Throttling: Slow down excessive requests.
-
IP Whitelisting: Allow access only from trusted networks.
-
CORS Control: Restrict cross-origin requests.
3️⃣ Service-to-Service Security
-
Definition: Internal microservices must trust each other.
-
mTLS (Mutual TLS): Both client & server authenticate using certificates.
-
Service Mesh (Istio/Linkerd): Automates mTLS, traffic rules, zero-trust policies.
4️⃣ Data Security
-
Transport Security: Enforce HTTPS/TLS 1.2+.
-
Secret Management: Use Vault to store credentials.
-
Password Hashing: Store passwords securely.
5️⃣ Secure Coding Practices
-
Prevent SQL Injection
-
Disable stack traces in production.
-
CSRF protection for session-based apps (disable for JWT APIs).
-
Content Security Policy (CSP) headers to reduce XSS risk.
6️⃣ Monitoring & Auditing
-
Spring Security Audit Logging
-
Centralized Monitoring:
-
Logs → ELK/EFK or Loki + Promtail + Grafana
-
Metrics → Prometheus + Grafana
-
Traces → Jaeger / Zipkin
-
7️⃣ Infrastructure & Container Security
-
Docker Security
-
Kubernetes Security
-
RBAC – restrict who can access resources.
-
Network Policies – control pod communication.
-
-
Secrets: Store credentials securely (encrypted).
-
Pod Security: Non-root, read-only filesystem.
-
Image Scanning: Trivy / Clair / Anchore.
8️⃣ Stable Tech Stack
Layer | Recommended Tech |
Security Core | Spring Boot + Spring Security |
API Gateway | Spring Cloud Gateway |
Authentication | Keycloak / Okta / Auth0 |
Secrets | HashiCorp Vault + Spring Cloud Config |
Service Mesh | Istio / Linkerd |
Monitoring | Prometheus + Grafana + Loki + Jaeger |
Containerization | Docker + Kubernetes |
Final Checklist
✔ OAuth2 + JWT for user identity
✔ Centralized API Gateway (rate limiting, CORS, IP whitelisting)
✔ Service-to-service trust (mTLS/service mesh)
✔ Secrets stored in Vault
✔ Encrypt data in transit & at rest
✔ Secure coding practices (SQL injection, password hashing, CSRF)
✔ Centralized monitoring & audit logging (ELK/Loki alternative)
✔ Hardened infrastructure (non-root Docker, K8s RBAC, network policies)