Back to Security & Vulnerability Analysis

aws-sdk-java-v2-secrets-manager

AWSJavaSecrets ManagerSecurityBackend DevelopmentSpring BootCredentials ManagementCloud Security
282📄 MIT🕒 2026-06-15Source ↗

Install this skill

npx skills add giuseppe-trisciuoglio/developer-kit

Works across Claude Code, Cursor, Codex, Copilot & Antigravity

The AWS SDK for Java 2.x Secrets Manager skill provides programmatic access to AWS Secrets Manager, allowing applications to store, retrieve, and manage sensitive configuration data like database credentials or API keys. By interacting directly with the Secrets Manager API, developers eliminate the need to store plaintext passwords in source code or configuration files. This implementation supports client-side secret caching, which significantly reduces network latency and API call costs by keeping frequently accessed secrets in local memory. The SDK handles authentication, secret versioning, and lifecycle management, including support for automatic secret rotation. It is essential for Java applications requiring secure, dynamic configuration retrieval and is frequently integrated with Spring Boot for transparent dependency injection of sensitive production credentials.

When to Use This Skill

  • Injecting database credentials into HikariCP or other DataSource configurations
  • Managing rotating API keys for third-party SaaS integrations
  • Sharing encrypted configuration parameters across multiple microservices
  • Implementing dynamic credential refreshing without application restarts

How to Invoke This Skill

Example prompts that trigger this skill in Claude Code, Cursor, or Antigravity:

  • retrieve database credentials from AWS Secrets Manager in Java
  • add AWS Secrets Manager SDK to my Maven project
  • how to cache secrets in Java using AWS SDK v2
  • implement secret rotation with AWS Secrets Manager and Java
  • fetch an AWS secret and map it to a Java object

Pro Tips

  • 💡Always implement secret caching in production environments to minimize latency and AWS API call costs, utilizing the recommended caching library.
  • 💡Adhere strictly to the principle of least privilege when defining IAM policies for secret access, ensuring applications or users can only access the specific secrets they require.
  • 💡Combine AWS Secrets Manager with AWS Lambda for seamless, automated secret rotation, significantly improving your security posture without manual intervention.

What this skill does

  • Programmatic CRUD operations for secrets and metadata
  • In-memory secret caching to minimize AWS API overhead
  • Support for versioning stages like AWSCURRENT and AWSPENDING
  • Automatic secret rotation scheduling and triggering
  • Integration with Jackson for deserializing JSON secret strings into POJOs

When not to use it

  • Storing massive blobs of data exceeding the 64KB secret limit
  • Managing highly static, non-sensitive configuration values better suited for AppConfig or SSM Parameter Store
  • Small local command-line scripts where environment variables are sufficient

Example workflow

  1. Configure the SecretsManagerClient with appropriate AWS region credentials.
  2. Initialize the SecretCache to handle local storage of retrieved values.
  3. Define a request for a specific secret ID using GetSecretValueRequest.
  4. Execute the call to fetch the secret string from the manager.
  5. Parse the returned JSON payload into a configuration POJO.
  6. Inject the POJO values into your application's service or database beans.

Prerequisites

  • An active AWS account with IAM permissions for secretsmanager:GetSecretValue
  • AWS credentials configured via environment variables, profiles, or IAM roles
  • Maven or Gradle build system installed

Pitfalls & limitations

  • !Failing to use the caching client, leading to API rate limiting and increased costs
  • !Hardcoding secret names instead of using environment-specific paths
  • !Missing error handling for expired or rotated secrets
  • !Overloading the memory heap if too many secrets are cached simultaneously

FAQ

Why should I use the caching client instead of just the standard SecretsManagerClient?
The caching client reduces API costs and latency by storing secrets in memory and refreshing them periodically based on TTL settings, preventing redundant network requests.
What is the maximum size for a secret stored in the manager?
AWS Secrets Manager supports secret values up to 64KB per secret.
Does this SDK automatically handle secret rotation?
The SDK provides the interface to trigger rotations and manage versions, but the actual rotation logic is typically executed by an AWS Lambda function associated with the secret.

How it compares

Using this SDK provides structured, type-safe integration and automatic caching, whereas manual REST API calls require tedious manual handling of authentication signing, retry logic, and JSON parsing.

Source & trust

282 stars📄 MIT🕒 Updated 2026-06-15
📄 Full skill instructions — original source: giuseppe-trisciuoglio/developer-kit
# AWS SDK for Java 2.x - AWS Secrets Manager

## When to Use

Use this skill when:
- Storing and retrieving application secrets programmatically
- Managing database credentials securely without hardcoding
- Implementing automatic secret rotation with Lambda functions
- Integrating AWS Secrets Manager with Spring Boot applications
- Setting up secret caching for improved performance
- Creating secure configuration management systems
- Working with multi-region secret deployments
- Implementing audit logging for secret access

## Dependencies

### Maven
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>secretsmanager</artifactId>
</dependency>

<!-- For secret caching (recommended for production) -->
<dependency>
<groupId>com.amazonaws.secretsmanager</groupId>
<artifactId>aws-secretsmanager-caching-java</artifactId>
<version>2.0.0</version> // Use the sdk v2 compatible version
</dependency>


### Gradle
implementation 'software.amazon.awssdk:secretsmanager'
implementation 'com.amazonaws.secretsmanager:aws-secretsmanager-caching-java:2.0.0


## Quick Start

### Basic Client Setup
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;

SecretsManagerClient secretsClient = SecretsManagerClient.builder()
.region(Region.US_EAST_1)
.build();


### Store a Secret
import software.amazon.awssdk.services.secretsmanager.model.*;

public String createSecret(String secretName, String secretValue) {
CreateSecretRequest request = CreateSecretRequest.builder()
.name(secretName)
.secretString(secretValue)
.build();

CreateSecretResponse response = secretsClient.createSecret(request);
return response.arn();
}


### Retrieve a Secret
public String getSecretValue(String secretName) {
GetSecretValueRequest request = GetSecretValueRequest.builder()
.secretId(secretName)
.build();

GetSecretValueResponse response = secretsClient.getSecretValue(request);
return response.secretString();
}


## Core Operations

### Secret Management
- Create secrets with createSecret()
- Retrieve secrets with getSecretValue()
- Update secrets with updateSecret()
- Delete secrets with deleteSecret()
- List secrets with listSecrets()
- Restore deleted secrets with restoreSecret()

### Secret Versioning
- Access specific versions by versionId
- Access versions by stage (e.g., "AWSCURRENT", "AWSPENDING")
- Automatically manage version history

### Secret Rotation
- Configure automatic rotation schedules
- Lambda-based rotation functions
- Immediate rotation with rotateSecret()

## Caching for Performance

### Setup Cache
import com.amazonaws.secretsmanager.caching.SecretCache;

public class CachedSecrets {
private final SecretCache cache;

public CachedSecrets(SecretsManagerClient secretsClient) {
this.cache = new SecretCache(secretsClient);
}

public String getCachedSecret(String secretName) {
return cache.getSecretString(secretName);
}
}


### Cache Configuration
import com.amazonaws.secretsmanager.caching.SecretCacheConfiguration;

SecretCacheConfiguration config = SecretCacheConfiguration.builder()
.maxCacheSize(1000)
.cacheItemTTL(3600000) // 1 hour
.build();


## Spring Boot Integration

### Configuration
@Configuration
public class SecretsManagerConfiguration {

@Bean
public SecretsManagerClient secretsManagerClient() {
return SecretsManagerClient.builder()
.region(Region.of(region))
.build();
}

@Bean
public SecretCache secretCache(SecretsManagerClient secretsClient) {
return new SecretCache(secretsClient);
}
}


### Service Layer
@Service
public class SecretsService {

private final SecretCache cache;

public SecretsService(SecretCache cache) {
this.cache = cache;
}

public <T> T getSecretAsObject(String secretName, Class<T> type) {
String secretJson = cache.getSecretString(secretName);
return objectMapper.readValue(secretJson, type);
}
}


### Database Configuration
@Configuration
public class DatabaseConfiguration {

@Bean
public DataSource dataSource(SecretsService secretsService) {
Map<String, String> credentials = secretsService.getSecretAsMap(
"prod/database/credentials");

HikariConfig config = new HikariConfig();
config.setJdbcUrl(credentials.get("url"));
config.setUsername(credentials.get("username"));
config.setPassword(credentials.get("password"));

return new HikariDataSource(config);
}
}


## Examples

### Database Credentials Structure
{
"engine": "postgres",
"host": "mydb.us-east-1.rds.amazonaws.com",
"port": 5432,
"username": "admin",
"password": "MySecurePassword123!",
"dbname": "mydatabase",
"url": "jdbc:postgresql://mydb.us-east-1.rds.amazonaws.com:5432/mydatabase"
}


### API Keys Structure
{
"api_key": "abcd1234-5678-90ef-ghij-klmnopqrstuv",
"api_secret": "MySecretKey123!",
"api_token": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}


## Common Patterns

### Error Handling
try {
String secret = secretsClient.getSecretValue(request).secretString();
} catch (SecretsManagerException e) {
if (e.awsErrorDetails().errorCode().equals("ResourceNotFoundException")) {
// Handle missing secret
}
throw e;
}


### Batch Operations
List<String> secretNames = List.of("secret1", "secret2", "secret3");
Map<String, String> secrets = secretNames.stream()
.collect(Collectors.toMap(
Function.identity(),
name -> cache.getSecretString(name)
));


## Best Practices

1. **Secret Management**:
- Use descriptive secret names with hierarchical structure
- Implement versioning and rotation
- Add tags for organization and billing

2. **Caching**:
- Always use caching in production environments
- Configure appropriate TTL values based on secret sensitivity
- Monitor cache hit rates

3. **Security**:
- Never log secret values
- Use KMS encryption for sensitive secrets
- Implement least privilege IAM policies
- Enable CloudTrail logging

4. **Performance**:
- Reuse SecretsManagerClient instances
- Use async operations when appropriate
- Monitor API throttling limits

5. **Spring Boot Integration**:
- Use @Value annotations for secret names
- Implement proper exception handling
- Use configuration properties for secret names

## Testing Strategies

### Unit Testing
@ExtendWith(MockitoExtension.class)
class SecretsServiceTest {

@Mock
private SecretCache cache;

@InjectMocks
private SecretsService secretsService;

@Test
void shouldGetSecret() {
when(cache.getSecretString("test-secret")).thenReturn("secret-value");

String result = secretsService.getSecret("test-secret");

assertEquals("secret-value", result);
}
}


### Integration Testing
@SpringBootTest(classes = TestSecretsConfiguration.class)
class SecretsManagerIntegrationTest {

@Autowired
private SecretsService secretsService;

@Test
void shouldRetrieveSecret() {
String secret = secretsService.getSecret("test-secret");
assertNotNull(secret);
}
}


## Troubleshooting

### Common Issues
- **Access Denied**: Check IAM permissions
- **Resource Not Found**: Verify secret name and region
- **Decryption Failure**: Ensure KMS key permissions
- **Throttling**: Implement retry logic and backoff

### Debug Commands
# Check secret exists
aws secretsmanager describe-secret --secret-id my-secret

# List all secrets
aws secretsmanager list-secrets

# Get secret value (CLI)
aws secretsmanager get-secret-value --secret-id my-secret


## References

For detailed information and advanced patterns, see:

- [API Reference](./references/api-reference.md) - Complete API documentation
- [Caching Guide](./references/caching-guide.md) - Performance optimization strategies
- [Spring Boot Integration](./references/spring-boot-integration.md) - Complete Spring integration patterns

## Related Skills

- aws-sdk-java-v2-core - Core AWS SDK patterns and best practices
- aws-sdk-java-v2-kms - KMS encryption and key management
- spring-boot-dependency-injection - Spring dependency injection patterns

How to Use This Skill Unit

Option A: Project-Specific (Recommended)

  1. Click "Download" above
  2. In your project, create the directory: .agent/skills/aws-sdk-java-v2-secrets-manager/
  3. Save the file as SKILL.md
  4. The agent will automatically discover the skill based on its description.

Option B: Global Installation (All Agents)

Save the file to these locations to make it available across all projects:

  • Claude Code: ~/.claude/skills/giuseppe-trisciuoglio/developer-kit/aws-sdk-java-v2-secrets-manager/SKILL.md
  • Cursor: ~/.cursor/skills/giuseppe-trisciuoglio/developer-kit/aws-sdk-java-v2-secrets-manager/SKILL.md
  • Antigravity: ~/.gemini/antigravity/skills/giuseppe-trisciuoglio/developer-kit/aws-sdk-java-v2-secrets-manager/SKILL.md

🚀 Install with CLI:
npx skills add giuseppe-trisciuoglio/developer-kit

Read the Master Guide: Mastering Agent Skills

Recommended Rules

View more rules

Recommended Workflows

View more workflows

Recommended MCP Servers

View more MCP servers

Take It Further

Maximize your productivity with these powerful resources

📋

Define Your Standards

Set up coding standards to ensure this workflow produces consistent, high-quality results.

Browse Rules Library
📖

Master Workflows

Learn how to create custom workflows, use Turbo Mode, and build your automation library.

Complete Guide

How to use this Skill in Claude Code & Cursor

For Claude Code (CLI)

To use this skill in Claude Code, copy the rule content into your project's custom instructions or follow our Add-Skill CLI guide. This ensures Claude follows your standards during every code generation.

For Cursor & Windsurf

For Cursor or Windsurf, individual skills are best used in the "Rules for AI" section. This specific unit helps the agent avoid security & vulnerability analysis issues, leading to cleaner, more efficient code.

Why the skill format matters: the standardized Agent Skills format lets your AI agent load detailed instructions only when they are relevant, keeping your prompt clean while improving results.

Source & attribution

This skill is categorized under Security & Vulnerability Analysis and is published by Giuseppe Trisciuoglio, maintained in giuseppe-trisciuoglio/developer-kit.

← Browse All Agent Skills
Sponsored AI assistant. Recommendations may be paid.