Now that Dapr is about to hit version 1.0.0 let me show you how easy is to read secrets with a .NET 5 console application.
Create a console application
1dotnet new console -n DaprSecretSample
2cd DaprSecretSample
Add a reference to the Dapr.Client library
1dotnet add package Dapr.Client --prerelease
Create a Secret Store component
Create a components
folder and inside place a file named secretstore.yaml
with the following contents:
1apiVersion: dapr.io/v1alpha1
2kind: Component
3metadata:
4 name: starwarssecrets
5spec:
6 type: secretstores.local.file
7 metadata:
8 - name: secretsFile
9 value: ./secrets.json
This component will enable Dapr, and therefore your application, to read secrets from a
secrets.json
file.
Create a Secrets file
Create a secrets.json
file with the following contents:
1{
2 "mandalorianSecret": "this is the way!"
3}
Replace the contents of Program.cs
Replace the contents of Program.cs
with the following code:
1using System;
2using Dapr.Client;
3
4var client = new DaprClientBuilder().Build();
5var secret = await client.GetSecretAsync("starwarssecrets", "mandalorianSecret");
6Console.WriteLine($"Secret from local file: {secret["mandalorianSecret"]});
Test the program
Run the following command to test the application.
1dapr run --app-id secretapp --components-path .\components\ -- dotnet run
Experiment
One of the amazing things about Dapr is that your code will be the same even if you change the underlying secret store.
In your local environment you can also try reading “secrets” from environment variables. In order to do so, replace the contents of the ./componentes/secrets.yaml
file with:
1apiVersion: dapr.io/v1alpha1
2kind: Component
3metadata:
4 name: starwarssecrets
5spec:
6 type: secretstores.local.env
Be sure to set, in your system, an environment variable named mandalorianSecret
, for instance:
1export mandalorianSecret="May The Force be with you"
and run the application again:
1dapr run --app-id secretapp --components-path .\components\ -- dotnet run
Note: I recommend using the secret stores shown in this post only for development or test scenarios. For a complete list of supported secret stores check the following repo: https://github.com/dapr/components-contrib/tree/master/secretstores.
Hope it helps!
Comments