当前位置: 移动技术网 > IT编程>开发语言>.net > ubuntu中使用机密数据Secrets

ubuntu中使用机密数据Secrets

2018年10月19日  | 移动技术网IT编程  | 我要评论

邯郸吧,普法栏目剧单行道5,中国德迷联盟

目录

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)

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网