--- lang: ja-jp breaks: true --- # C# プロジェクト内に機密情報を格納せずに、アプリケーションの設定を行う方法 `ConfigurationBuilder` `ユーザシークレット` 2023-05-02 > ASP.NET Core での開発におけるアプリ シークレットの安全な保存 > https://learn.microsoft.com/ja-jp/aspnet/core/security/app-secrets?view=aspnetcore-7.0&tabs=windows > ![](https://i.imgur.com/bOzX5dV.png) ## `csproj` ```xml= <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net7.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> <UserSecretsId>765A5AE0-0C15-4301-B022-0382B50559C6</UserSecretsId> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="7.0.2" /> <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="7.0.0" /> </ItemGroup> <ItemGroup> <None Update="appsettings.json"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup> </Project> ``` :::info 1. 以下を追加。 ```xml= <UserSecretsId>765A5AE0-0C15-4301-B022-0382B50559C6</UserSecretsId> ``` 2. `appsettings.json` の設定を「新しい場合はコピーする」に変更する。 ![](https://i.imgur.com/tpyDkd4.png) 3. `Microsoft.Extensions.Configuration`パッケージを追加する。 ::: ## `appsettings.json` 以下は例。 ```json= { "SP-API_EXAMPLES": { "AccessKey": "XXXXXXXX", "SecretKey": "XXXXXXXX", "RoleArn": "XXXXXXXX", "ClientId": "XXXXXXXX", "ClientSecret": "00000000", "RefreshToken": "00000000", "MarketPlaceID": "00000000", "ProxyAddress": "http://localhost:8080" } } ``` ## `secrets.json` プロジェクトを右クリックし、`ユーザーシークレットの管理`をクリックする。 ![](https://i.imgur.com/Ar8dfvI.png) 開発用の設定や、テスト用の設定を行う。 ![](https://i.imgur.com/xHEcF1f.png) `secrets.json`は、ユーザフォルダ内に自動的に作成される。 ![](https://i.imgur.com/TqSfuMI.png) ## `Program.cs` ```csharp= static async Task Main(string[] args) { var config = new ConfigurationBuilder() .SetBasePath(AppDomain.CurrentDomain.BaseDirectory) .AddJsonFile("appsettings.json") .AddUserSecrets<Program>() .Build(); AmazonCredential amazonCredential = new() { AccessKey = config.GetSection("SP-API:AccessKey").Value, SecretKey = config.GetSection("SP-API:SecretKey").Value, RoleArn = config.GetSection("SP-API:RoleArn").Value, ClientId = config.GetSection("SP-API:ClientId").Value, ClientSecret = config.GetSection("SP-API:ClientSecret").Value, RefreshToken = config.GetSection("SP-API:RefreshToken").Value, MarketPlaceID = config.GetSection("SP-API:MarketPlaceID").Value, SellerID = config.GetSection("SP-API:SellerId").Value, IsDebugMode = true }; AmazonConnection amazonConnection = new AmazonConnection(amazonCredential); ・・・ } ``` ###### tags: `C#` `ConfigurationBuilder` `json` `secrets.json` `ユーザシークレット`