π Security β Detailed Answers¶
1. How do you implement security in microservices?¶
You donβt bolt on security at the end. You weave it through every layer.
πΉ Core Approach I Follow¶
π‘οΈ 1. API Gateway Security¶
- All requests pass through a gateway
-
Handles:
- Authentication
- Rate limiting
- Logging
π Acts like a border checkpoint
π 2. Token-Based Authentication (JWT)¶
- User logs in once
- Receives a token
- Token is sent with every request
π Services donβt store session state
π 3. Centralized Identity Provider¶
Use tools like:
- Keycloak
- OAuth 2.0
- OpenID Connect
π Handles login, roles, permissions
π 4. Service-to-Service Security¶
- Use mutual TLS (mTLS) or internal tokens
- Prevent unauthorized internal calls
π 5. Role-Based Access Control (RBAC)¶
-
Define roles like:
- ADMIN
- USER
- Restrict APIs accordingly
π¦ 6. Secure Communication¶
- Always use HTTPS
- Encrypt sensitive data
π― Interview Answer¶
βI secure microservices using an API Gateway, JWT-based authentication, and a centralized identity provider like Keycloak. For internal communication, I use mTLS or secure tokens, and enforce authorization using RBAC.β
2. What is JWT authentication?¶
JWT is like a digitally signed passport π Once issued, every service can verify it without calling the authority again.
πΉ What is JWT?¶
JWT (JSON Web Token) is a compact, self-contained token used for authentication.
πΉ Structure of JWT¶
A JWT has 3 parts:
π§± 1. Header¶
- Algorithm used (e.g., HS256)
π¦ 2. Payload¶
- User data (claims)
π 3. Signature¶
- Ensures token is not tampered
π Flow¶
- User logs in
- Server generates JWT
- Client stores token
- Client sends token in header:
β Advantages¶
- Stateless
- Scalable
- No session storage needed
β οΈ Considerations¶
- Token expiry required
- Donβt store sensitive data in payload
π― Interview Answer¶
βJWT is a stateless authentication mechanism where a signed token containing user claims is issued after login and validated by services on each request.β
3. Difference between authentication and authorization?¶
This is the classic βWho are you vs What can you doβ question π
πΉ Authentication (AuthN)¶
π Verifies identity
- Are you really the user you claim to be?
-
Example:
- Username + Password
- OTP
- Token validation
πΉ Authorization (AuthZ)¶
π Determines permissions
- What are you allowed to access?
-
Example:
- Admin can delete users
- User can only view data
βοΈ Side-by-Side¶
| Aspect | Authentication | Authorization |
|---|---|---|
| Purpose | Identity check | Access control |
| Happens when | First | After authentication |
| Example | Login | Role check |
| Data used | Credentials | Roles/permissions |
π― Perfect Interview Answer¶
βAuthentication verifies the userβs identity, while authorization determines what actions that authenticated user is allowed to perform.β
π Quick Memory Hook¶
- Security = Gateway + JWT + Identity Provider
- JWT = Stateless identity token
- AuthN = Who you are
- AuthZ = What you can do