CodeGym /Courses /Module 5. Spring /Lecture 228: Secret and Security Management in Microservi...

Lecture 228: Secret and Security Management in Microservices

Module 5. Spring
Level 23 , Lesson 7
Available

Imagine: you're heading into an interview, and the interviewer asks, "How do you protect your secrets in microservices?" You're sweating because just yesterday you accidentally committed your application.properties with the DB login and password to a public GitHub repo. Sounds scary, right? But that happens even to experienced developers.

In the world of microservices secrets are everywhere: environment variables, config files, databases, API keys, access tokens, and more. The main problems include:

  • Leakage of sensitive data. When secrets are stored in code or version control (yes, that's a bad idea).
  • The need to manage secrets centrally. Imagine you have 50 microservices and you need to rotate an API key. Nightmare? Yeah.
  • Access security. Even if you set up secret management correctly, you still need to control who can fetch what.

Task: set up secure secret management

We've already met HashiCorp Vault and learned how to integrate it. Now let's look at approaches and tools that help secure your data.


Main approaches and tools

1. Keep secrets out of code

The most basic rule. Secrets must not be in code repositories in any form! Instead, use:

  • HashiCorp Vault — centralized storage.
  • AWS Secrets Manager or Azure Key Vault for cloud services.
  • Environment variables. Yep, sometimes acceptable, but be careful.

Example of a bad practice:

// Big mistake: never do this!
String dbPassword = "super_secret_password";

Example of a better practice using environment variables:

String dbPassword = System.getenv("DB_PASSWORD");

Or using Vault via Spring:

// Configuration is read automatically thanks to Spring Cloud Vault
@Value("${db.password}")
private String dbPassword;

2. Minimize access to sensitive data

Let's use an analogy. You wouldn't let all your friends access your bank account, right? Same goes for secrets. Use:

  • Rolling tokens. Allow you to rotate secrets frequently.
  • Role-based access control (RBAC). For example, in HashiCorp Vault you can configure services to only access what's necessary.
  • Access auditing. Any access to secrets should be logged. If Petya accidentally requested the production DB password, you should know about it.

Example policy configuration in Vault:


path "secret/data/my-service" {
  capabilities = ["read"]
}

3. Encrypt secrets

If secrets are transmitted or stored, they must be encrypted. Use:

  • Spring Cloud Vault to read encrypted values.
  • BCrypt or AES for local encryption.

Example: client-side encryption.


import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class EncryptionExample {
    public static void main(String[] args) throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        SecretKey secretKey = keyGen.generateKey();

        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        String plaintext = "This is a secret!";
        byte[] encryptedData = cipher.doFinal(plaintext.getBytes());

        System.out.println("Encrypted: " + new String(encryptedData));
    }
}

4. Use secret versioning

HashiCorp Vault, AWS Secrets Manager and other tools support secret versioning. This lets you safely update tokens.

Example:

  1. Updated the secret in Vault.
  2. Microservices automatically switched to the new version.

5. Update secrets on the fly

Use Spring Cloud Bus and event-driven approaches to notify other services when a secret changes.

Example:


@RefreshScope // Automatically refreshes fields when configuration changes
@RestController
public class ExampleController {
    @Value("${some.secret}")
    private String someSecret;

    @GetMapping("/secret")
    public String getSecret() {
        return someSecret;
    }
}

Problems with storing secrets and how to solve them

How often do we hear: "I committed a secret to the repo"? This happens even to experienced developers. Here's what to do:

  1. Scan repositories for secret leaks using tools like GitGuardian or TruffleHog.
  2. Remove secrets from Git history automatically if it happened. For example:

git filter-branch --force --index-filter \
'repo-cleanup-command' --prune-empty --tag-name-filter cat -- --all

Tools and methods for ensuring security

Using secret providers

  • HashiCorp Vault for centralized management.
  • AWS Secrets Manager — optimal for AWS cloud infra.
  • Kubernetes Secrets for Kubernetes clusters.

Security best practices

  • Role separation: different tokens for dev, test, and production.
  • Autonomous services: each microservice manages only its own secrets.
  • Don't use "default secrets". That's like leaving your house keys under the doormat.

Example: working with HashiCorp Vault in Spring

Vault setup

  1. Install and run Vault.
  2. Create a secret:
    vault kv put secret/myapp db.password=supersecretpassword
    
  3. Configure Spring Boot to work with Vault:
    spring:
    cloud:
      vault:
        uri: http://127.0.0.1:8200
        authentication: TOKEN
        token: <your token>
    
  4. Read the secret in code:
    
    @Value("${db.password}")
    private String dbPassword;
    
    @GetMapping("/password")
    public String getPassword() {
        return dbPassword;
    }
    

Common mistakes and how to avoid them

One of the most common mistakes is committing a secret to the repo. Use .gitignore or specialized scanners to prevent this.

Another mistake is giving permissions to everyone and anyone. Always limit access and use RBAC policies.

And of course, don't forget to rotate secrets regularly. A token that hasn't been rotated in years is a massive mistake.


By now you should understand how to manage secrets and secure microservices. Now you're ready for the next step — diving deep into Spring Boot configuration profiles!

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION