ASP.NET Core の暗号化された構成 質問する

ASP.NET Core の暗号化された構成 質問する

廃止に伴いweb.config、ASP.NET Core を使用して構築された Web アプリの構成に機密情報 (パスワード、トークン) を保存する推奨される方法は何ですか?

暗号化された構成セクションを自動的に取得する方法はありますかappsettings.json?

ベストアンサー1

ユーザーシークレットは、パスワードや、一般的にはアプリケーションシークレットを保存するのに適したソリューションのように思えます。開発中

チェックしてくださいマイクロソフトの公式ドキュメント確認することもできますこれその他のSOの質問。

これは、開発プロセス中に秘密を「隠す」方法であり、ソースツリーに公開されるのを避けるためのものです。Secret Managerツール保存された秘密を暗号化しない信頼できるストアとして扱うべきではありません。

appsettings.json暗号化されたアプリケーションを本番環境に導入したい場合は、カスタム構成プロバイダー

例えば:

public class CustomConfigProvider : ConfigurationProvider, IConfigurationSource
{
    public CustomConfigProvider()
    {
    }

    public override void Load()
    {
        Data = UnencryptMyConfiguration();
    }

    private IDictionary<string, string> UnencryptMyConfiguration()
    {
        // do whatever you need to do here, for example load the file and unencrypt key by key
        //Like:
       var configValues = new Dictionary<string, string>
       {
            {"key1", "unencryptedValue1"},
            {"key2", "unencryptedValue2"}
       };
       return configValues;
    }

    private IDictionary<string, string> CreateAndSaveDefaultValues(IDictionary<string, string> defaultDictionary)
    {
        var configValues = new Dictionary<string, string>
        {
            {"key1", "encryptedValue1"},
            {"key2", "encryptedValue2"}
        };
        return configValues;                
    }

    public IConfigurationProvider Build(IConfigurationBuilder builder)
    {
       return new CustomConfigProvider();
    }
}

拡張メソッドの静的クラスを定義します。

public static class CustomConfigProviderExtensions
{              
        public static IConfigurationBuilder AddEncryptedProvider(this IConfigurationBuilder builder)
        {
            return builder.Add(new CustomConfigProvider());
        }
}

そして、それをアクティブ化できます:

// Set up configuration sources.
var builder = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .AddEncryptedProvider()
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

おすすめ記事