How To: Retrieve a secret

Use the secret store building block to securely retrieve a secret

This article provides guidance on using Dapr’s secrets API in your code to leverage the secrets store building block. The secrets API allows you to easily retrieve secrets in your application code from a configured secret store.

Example

The below code example loosely describes an application that processes orders. In the example, there is an order processing service, which has a Dapr sidecar. The order processing service uses Dapr to store a secret in a local secret store.

Diagram showing secrets management of example service

Set up a secret store

Before retrieving secrets in your application’s code, you must have a secret store component configured. For the purposes of this guide, as an example you will configure a local secret store which uses a local JSON file to store secrets.

Warning

In a production-grade application, local secret stores are not recommended. You can find other alternatives here to securely manage your secrets.

Create a file named secrets.json with the following contents:

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

Create a directory for your components file named components and inside it create a file named localSecretStore.yaml with the following contents:

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

Note: the path to the secret store JSON is relative to where you call dapr run from.

To configure a different kind of secret store see the guidance on how to configure a secret store and review supported secret stores to see specific details required for different secret store solutions.

Get a secret

Run the Dapr sidecar with the application.

  1. dapr run --app-id orderprocessingservice --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 --components-path ./components dotnet run
  1. dapr run --app-id orderprocessingservice --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 --components-path ./components mvn spring-boot:run
  1. dapr run --app-id orderprocessingservice --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 --components-path ./components python3 OrderProcessingService.py
  1. dapr run --app-id orderprocessingservice --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 --components-path ./components go run OrderProcessingService.go
  1. dapr run --app-id orderprocessingservice --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 --components-path ./components npm start

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

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

For a full API reference, go here.

Calling the secrets API from your code

Once you have a 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-client';
  3. //code
  4. const daprHost = "127.0.0.1";
  5. async function main() {
  6. const client = new DaprClient(daprHost, process.env.DAPR_HTTP_PORT, CommunicationProtocolEnum.HTTP);
  7. const SECRET_STORE_NAME = "localsecretstore";
  8. //Using Dapr SDK to get a secret
  9. var secret = await client.secret.get(SECRET_STORE_NAME, "secret");
  10. console.log("Result: " + secret);
  11. //Using Dapr SDK to get bulk secrets
  12. secret = await client.secret.getBulk(SECRET_STORE_NAME);
  13. console.log("Result for bulk: " + secret);
  14. }
  15. main();

Last modified February 18, 2022: Update setup-jetstream.md (#2200) (428d8c2)