ubuntu中使用机密数据Secrets

AptNetCore使用Secrets管理私密数据

前言

在项目中, 数据库连接, 账户及密码等如果存储在appsetting.json中就太不安全了, 所以生产时都是放在环境变量中读取的.
在开发中可能存在每一台开发机用到的一些变量都不一样的情况, 这个时候如果写在appsettings.Development.json中每次提交版本控制就不方便了.
所以dotnet-cli贴心的提供了 user-secrets 命令, 来管理开始时用户的私密数据.

使用

设置UserSecretsId

在项目根目录输入 dotnet user-secrets list, 可以看到错误提示

Could not find the global property 'UserSecretsId' in MSBuild project '/home/xueyou/website-demo/website-demo.csproj'. Ensure this property is set in the project or use the '--id' command line option.

这提示我们, 要想使用Secrets管理机密, 需先定义UserSecretsId

并且根据上面的提示可以知道, 它在.csproj文件中寻找UserSecretsId, 那我们就在此文件中定义UserSecretsId

编辑.csproj文件在PropertyGroup内增加<UserSecretsId>79a3edd0-2092-40a2-a04d-dcb46d5ca9ed</UserSecretsId>

UserSecretsId值是GUID生成的, 每一个值都会实际对应到文件夹的名称上

  • windows中, %APPDATA%\Microsoft\UserSecrets\<user_secrets_id>\secrets.json
  • linux中, ~/.microsoft/usersecrets/<user_secrets_id>/secrets.json

设置机密

dotnet user-secrets set "WeChatAppKey" "X3423FEED2435DD"

其中keyWeChatAppKey是dotnet core配置系统中的key, 所以可以是:号分隔, 映射到配置树

dotnet user-secrets list 可以查看当前机密

代码中访问机密

public class Startup
{
    private string _wechatKey= null;

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        _wechatKey = Configuration["WeChatAppKey"];
    }

    public void Configure(IApplicationBuilder app)
    {
        var result = string.IsNullOrEmpty(_wechatKey) ? "Null" : "Not Null";
        app.Run(async (context) =>
        {
            await context.Response.WriteAsync($"Secret is {result}");
        });
    }
}

脚注

[ASP.NET Core 优雅的在开发环境保存机密](https://www.cnblogs.com/savorboard/p/dotnetcore-user-secrets.html)

在开发期间安全存储应用机密

posted @ 2018-10-18 17:55  学友2000  阅读(493)  评论(0编辑  收藏  举报