0

In my .net core Api i use secrets.json:

{"UserServiceSecretKey": "secretKey123456"}

Evidently in my .csproj:

<PropertyGroup>
  <TargetFramework>netcoreapp3.1</TargetFramework>
  <UserSecretsId>6da803bf-439d-4e34-8735-195d652e8366</UserSecretsId>
  <DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>

And use in my Startup.cs ConfigureServicesMethod():

 var secretKey = Configuration["UserServiceSecretKey"];
        if (string.IsNullOrEmpty(secretKey))
            Console.WriteLine("Error: KEY UserServiceSecretKey cannot be null...");

If run the application on IISExpres it works (get the secret key).

But if i run the Api in docker like docker-compose, then in runtime the secret key is not obtained: enter image description here

In my docker-compose.override file i have:

tresfilos.users.service:
environment: 
  - ASPNETCORE_ENVIRONMENT= Development
  - ASPNETCORE_URLS= https://+:443;http://+:80
ports:
  - "7002:80"
  - "7003:443"
volumes:
    - ${APPDATA}/Microsoft/UserSecrets:/root/.microsoft/usersecrets:ro
    - ${APPDATA}/ASP.NET/Https:/root/.aspnet/https:ro

Additional, i have defined the APPDATA environment variable:

enter image description here

How can i access to secret key when i run the Api in docker ?

4

1 回答 1

1

Docker 机密作为目录内的文件加载到内存中/run/secrets,而不是作为挂载目录,因此您需要从内存中读取它

有3个步骤,

1. docker-compose 文件

version: "3.9"
services:
  redis:
    image: redis:latest
    deploy:
      replicas: 1
    secrets:
      - my_secret
      - my_other_secret
secrets:
  my_secret:
    file: ./my_secret.txt
  my_other_secret:
    external: true

注意:您可以通过使用文件或通过定义为外部资源来将秘密添加到 docker,这意味着它已经在 Docker 中定义,可以通过运行 docker secret create 命令或通过另一个堆栈部署。如果外部机密不存在,堆栈部署将失败并出现机密未找到错误。

2.安装nuget包

Microsoft.Extensions.Configuration.KeyPerFile

3. 向 Startup.cs 添加配置条目

config.AddKeyPerFile(directoryPath: "/run/secrets", optional: true);

于 2020-12-14T11:23:39.707 回答