How To: Retrieve a secret

Use the secret store building block to securely retrieve a secret

Now that you’ve learned what the Dapr secrets building block provides, learn how it can work in your service. This guide demonstrates how to call the secrets API and retrieve secrets in your application code from a configured secret store.

Diagram showing secrets management of example service.

Note

If you haven’t already, try out the secrets management quickstart for a quick walk-through on how to use the secrets API.

Set up a secret store

Before retrieving secrets in your application’s code, you must configure a secret store component. This example configures a secret store that uses a local JSON file to store secrets.

Warning

In a production-grade application, local secret stores are not recommended. Find alternatives to securely manage your secrets.

In your project directory, create a file named secrets.json with the following contents:

  1. {
  2. "secret": "Order Processing pass key"
  3. }

Create a new directory named components. Navigate into that directory and create a component file named local-secret-store.yaml with the following contents:

  1. apiVersion: dapr.io/v1alpha1
  2. kind: Component
  3. metadata:
  4. name: localsecretstore
  5. spec:
  6. type: secretstores.local.file
  7. version: v1
  8. metadata:
  9. - name: secretsFile
  10. value: secrets.json #path to secrets file
  11. - name: nestedSeparator
  12. value: ":"

Warning

The path to the secret store JSON is relative to where you call dapr run.

For more information:

Get a secret

Get the secret by calling the Dapr sidecar using the secrets API:

  1. curl http://localhost:3601/v1.0/secrets/localsecretstore/secret

See a full API reference.

Calling the secrets API from your code

Now that you’ve set up the local secret store, call Dapr to get the secrets from your application code. Below are code examples that leverage Dapr SDKs for retrieving a secret.

  1. //dependencies
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Net.Http;
  5. using System.Net.Http.Headers;
  6. using System.Threading.Tasks;
  7. using Dapr.Client;
  8. using Microsoft.AspNetCore.Mvc;
  9. using System.Threading;
  10. using System.Text.Json;
  11. //code
  12. namespace EventService
  13. {
  14. class Program
  15. {
  16. static async Task Main(string[] args)
  17. {
  18. string SECRET_STORE_NAME = "localsecretstore";
  19. using var client = new DaprClientBuilder().Build();
  20. //Using Dapr SDK to get a secret
  21. var secret = await client.GetSecretAsync(SECRET_STORE_NAME, "secret");
  22. Console.WriteLine($"Result: {string.Join(", ", secret)}");
  23. }
  24. }
  25. }
  1. //dependencies
  2. import com.fasterxml.jackson.core.JsonProcessingException;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import io.dapr.client.DaprClient;
  5. import io.dapr.client.DaprClientBuilder;
  6. import org.springframework.boot.autoconfigure.SpringBootApplication;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import java.util.Map;
  10. //code
  11. @SpringBootApplication
  12. public class OrderProcessingServiceApplication {
  13. private static final Logger log = LoggerFactory.getLogger(OrderProcessingServiceApplication.class);
  14. private static final ObjectMapper JSON_SERIALIZER = new ObjectMapper();
  15. private static final String SECRET_STORE_NAME = "localsecretstore";
  16. public static void main(String[] args) throws InterruptedException, JsonProcessingException {
  17. DaprClient client = new DaprClientBuilder().build();
  18. //Using Dapr SDK to get a secret
  19. Map<String, String> secret = client.getSecret(SECRET_STORE_NAME, "secret").block();
  20. log.info("Result: " + JSON_SERIALIZER.writeValueAsString(secret));
  21. }
  22. }
  1. #dependencies
  2. import random
  3. from time import sleep
  4. import requests
  5. import logging
  6. from dapr.clients import DaprClient
  7. from dapr.clients.grpc._state import StateItem
  8. from dapr.clients.grpc._request import TransactionalStateOperation, TransactionOperationType
  9. #code
  10. logging.basicConfig(level = logging.INFO)
  11. DAPR_STORE_NAME = "localsecretstore"
  12. key = 'secret'
  13. with DaprClient() as client:
  14. #Using Dapr SDK to get a secret
  15. secret = client.get_secret(store_name=DAPR_STORE_NAME, key=key)
  16. logging.info('Result: ')
  17. logging.info(secret.secret)
  18. #Using Dapr SDK to get bulk secrets
  19. secret = client.get_bulk_secret(store_name=DAPR_STORE_NAME)
  20. logging.info('Result for bulk secret: ')
  21. logging.info(sorted(secret.secrets.items()))
  1. //dependencies
  2. import (
  3. "context"
  4. "log"
  5. dapr "github.com/dapr/go-sdk/client"
  6. )
  7. //code
  8. func main() {
  9. client, err := dapr.NewClient()
  10. SECRET_STORE_NAME := "localsecretstore"
  11. if err != nil {
  12. panic(err)
  13. }
  14. defer client.Close()
  15. ctx := context.Background()
  16. //Using Dapr SDK to get a secret
  17. secret, err := client.GetSecret(ctx, SECRET_STORE_NAME, "secret", nil)
  18. if secret != nil {
  19. log.Println("Result : ")
  20. log.Println(secret)
  21. }
  22. //Using Dapr SDK to get bulk secrets
  23. secretBulk, err := client.GetBulkSecret(ctx, SECRET_STORE_NAME, nil)
  24. if secret != nil {
  25. log.Println("Result for bulk: ")
  26. log.Println(secretBulk)
  27. }
  28. }
  1. //dependencies
  2. import { DaprClient, HttpMethod, CommunicationProtocolEnum } from '@dapr/dapr';
  3. //code
  4. const daprHost = "127.0.0.1";
  5. async function main() {
  6. const client = new DaprClient({
  7. daprHost,
  8. daprPort: process.env.DAPR_HTTP_PORT,
  9. communicationProtocol: CommunicationProtocolEnum.HTTP,
  10. });
  11. const SECRET_STORE_NAME = "localsecretstore";
  12. //Using Dapr SDK to get a secret
  13. var secret = await client.secret.get(SECRET_STORE_NAME, "secret");
  14. console.log("Result: " + secret);
  15. //Using Dapr SDK to get bulk secrets
  16. secret = await client.secret.getBulk(SECRET_STORE_NAME);
  17. console.log("Result for bulk: " + secret);
  18. }
  19. main();

Last modified October 11, 2024: Fixed typo (#4389) (fe17926)