{"id":22725664,"url":"https://github.com/maremare/usingsecretssandbox","last_synced_at":"2026-04-28T13:33:48.954Z","repository":{"id":36990133,"uuid":"504902098","full_name":"MareMare/UsingSecretsSandbox","owner":"MareMare","description":"⚠️for personal use. User Secrets を CI で利用してみる","archived":false,"fork":false,"pushed_at":"2025-06-03T15:55:37.000Z","size":163,"stargazers_count":1,"open_issues_count":1,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-06-04T01:59:23.494Z","etag":null,"topics":["csharp","github-actions","net6","net60","xunit"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/MareMare.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2022-06-18T17:00:43.000Z","updated_at":"2025-06-03T15:55:38.000Z","dependencies_parsed_at":"2023-10-17T05:09:58.950Z","dependency_job_id":"2b3e56fa-6052-46fd-b424-386a3620392e","html_url":"https://github.com/MareMare/UsingSecretsSandbox","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/MareMare/UsingSecretsSandbox","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MareMare%2FUsingSecretsSandbox","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MareMare%2FUsingSecretsSandbox/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MareMare%2FUsingSecretsSandbox/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MareMare%2FUsingSecretsSandbox/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MareMare","download_url":"https://codeload.github.com/MareMare/UsingSecretsSandbox/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MareMare%2FUsingSecretsSandbox/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":262720642,"owners_count":23353448,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["csharp","github-actions","net6","net60","xunit"],"created_at":"2024-12-10T16:13:31.834Z","updated_at":"2026-04-28T13:33:43.933Z","avatar_url":"https://github.com/MareMare.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Secrets をローカルとGitHubで使用する方法\n\n⚠️ **_This repository is intended for me._**\n\nローカルと GitHub 上の CI の両方でシークレットを扱う方法を考えてみます。\n\n## ソリューションの準備\n\n```ps1\ndotnet new sln\n```\n\n## アプリでのシークレット\n\nアプリでシークレットを利用してみます。\n\n### 1. プロジェクトの準備\n\n```ps1\ndotnet new console -o ConsoleApp\ndotnet sln add ConsoleApp\n```\n\n### 2. NuGet パッケージの参照追加\n\n```ps1\ndotnet add ConsoleApp package Microsoft.Extensions.Configuration.Binder\ndotnet add ConsoleApp package Microsoft.Extensions.Configuration.UserSecrets\n```\n\n### 3. シークレットの準備\n\n```ps1\ndotnet user-secrets -p ConsoleApp init\n```\n\n### 4. シークレットの設定と確認\n\n```ps1\ndotnet user-secrets -p ConsoleApp set \"AppSettings:User\" \"ゆーざ\"\ndotnet user-secrets -p ConsoleApp set \"AppSettings:ApiKey\" \"きー\"\n\ndotnet user-secrets -p ConsoleApp list\n```\n\n### 5. コードからシークレット取得\n\n```cs\nusing System.Reflection;\nusing Microsoft.Extensions.Configuration;\n\nvar config = new ConfigurationBuilder()\n    .AddUserSecrets(Assembly.GetExecutingAssembly())\n    .Build();\n\n// インデクサによる取得\nConsole.WriteLine($\"indexer: {config[\"AppSettings:User\"]} {config[\"AppSettings:ApiKey\"]}\");\n\n// POCO へのマッピングによる取得\nvar appSetting = config\n    .GetSection(nameof(AppSettings))\n    .Get\u003cAppSettings\u003e();\n\nConsole.WriteLine($\"POCO: {appSetting.User} {appSetting.ApiKey}\");\n\npublic class AppSettings\n{\n    public string User { get; set; }\n    public string ApiKey { get; set; }\n}\n```\n\n## Unit Test でのシークレット(環境変数版)\n\nUnit Test でシークレットを利用してみます。\nGitHub Actions からも利用したいので環境変数へアクセスできるようにします。\n\n### 1. プロジェクトの準備\n\n```ps1\ndotnet new xunit -o ConsoleApp.Test\ndotnet sln add ConsoleApp.Test\n```\n\n### 2. NuGet パッケージの参照追加\n\n```ps1\ndotnet add ConsoleApp.Test package Microsoft.Extensions.Configuration.Binder\ndotnet add ConsoleApp.Test package Microsoft.Extensions.Configuration.EnvironmentVariables\ndotnet add ConsoleApp.Test package Microsoft.Extensions.Configuration.UserSecrets\n```\n\n### 3. シークレットの準備\n\n```ps1\ndotnet user-secrets -p ConsoleApp.Test init\n```\n\n### 4. シークレットの設定と確認\n\n```ps1\ndotnet user-secrets -p ConsoleApp.Test set \"User\" \"Testゆーざ\"\ndotnet user-secrets -p ConsoleApp.Test set \"ApiKey\" \"Testきー\"\n\ndotnet user-secrets -p ConsoleApp.Test list\n```\n\n### 5. コードからシークレット取得\n\n```cs\nusing Microsoft.Extensions.Configuration;\n\nnamespace ConsoleApp.Test;\n\npublic class UnitTest1\n{\n    private readonly IConfiguration _config;\n    public UnitTest1()\n    {\n        _config = new ConfigurationBuilder()\n            .AddUserSecrets\u003cUnitTest1\u003e() // (A) for local\n            .AddEnvironmentVariables()   // (B) for dotnet test env in github actions\n            .Build();\n    }\n\n    [Fact]\n    public void Test_User()\n    {\n        var actual = _config[\"user\"];\n        Assert.Equal(\"Testゆーざ\", actual);\n    }\n\n    [Fact]\n    public void Test_ApiKey()\n    {\n        var actual = _config[\"apikey\"];\n        Assert.Equal(\"Testきー\", actual);\n    }\n}\n```\n\n## GitHub Actions\n\n### 1. GitHub Actions secrets の準備\n\n![](doc/GitHub-Actions-secrets.png)\n\n### 2. Workflow の設定\n\n```yml\n# ...\n      - name: 🧪 Test\n        working-directory: src\n        run: dotnet test --configuration $env:Configuration --no-build --verbosity normal\n        env:\n          user: ゆーざTest\n          apikey: ${{ secrets.SAMPLEAPIKEY }}\n          Configuration: ${{ matrix.configuration }}\n# ...\n```\n\n## Dependabot secrets\n\nDependabot には GitHub Secrets にアクセスする権限がないので前述の Workflow に `${{ secrets.SAMPLEAPIKEY }}` で指定したシークレットが取得できずに `dotnet test` が失敗します。\n* [GitHub Actions: Workflows triggered by Dependabot PRs will run with read\\-only permissions \\| GitHub Changelog](https://github.blog/changelog/2021-02-19-github-actions-workflows-triggered-by-dependabot-prs-will-run-with-read-only-permissions/)\n* [Accessing secrets \\- GitHub Docs](https://docs.github.com/en/code-security/dependabot/working-with-dependabot/automating-dependabot-with-github-actions#accessing-secrets)\n\n### 1. Dependabot secrets の準備\n\n![](doc/Dependabot-secrets.png)\n\nDependabot からシークレットへアクセスするには Dependabot secrets ストアに格納することで `${{secrets.NAME}}` のようにアクセスできるようになります。\n* [Configuring access to private registries for Dependabot \\- GitHub Docs](https://docs.github.com/en/code-security/dependabot/working-with-dependabot/configuring-access-to-private-registries-for-dependabot)\n* [About encrypted secrets for Dependabot \\- GitHub Docs](https://docs.github.com/en/code-security/dependabot/working-with-dependabot/configuring-access-to-private-registries-for-dependabot#about-encrypted-secrets-for-dependabot)\n\n## シークレット\n\nUser Secrets を格納した `secrets.json` は、あくまでも**開発環境**に限り構成プロバイダが有効になります。\n\n実稼働では**運用環境**となるので環境変数にてシークレットを提供するほうが良いみたいです。\n\n階層キー（`:` 区切り記号）は環境変数では対応していないので `__`（ダブルアンダースコア）を指定する必要があります。\nちなみに `__` は自動で `:` に置換されるのでコード上の変更は不要です。\n\n* json\n  ```json\n  \"Position\": {\n    \"Title\": \"Editor\",\n    \"Name\": \"Joe Smith\"\n  }\n  ```\n* C#\n  ```cs\n  var title = Configuration[\"Position:Title\"];\n  var name = Configuration[\"Position:Name\"];\n  ```\n\n* .NET CLI\n  ```ps1\n  dotnet user-secrets set \"Position:Title\" \"Editor\"\n  dotnet user-secrets set \"Position:Name\" \"Joe Smith\"\n  ```\n\n* cmd.exe\n  ```bat\n  setx ASPNETCORE_ENVIRONMENT Staging /M\n  setx Position__Title Environment_Editor /M\n  setx Position__Name Environment_Rick /M\n  ```\n\n* pwsh\n  ```ps1\n  [Environment]::SetEnvironmentVariable(\"ASPNETCORE_ENVIRONMENT\", \"Staging\", \"Machine\")\n  [Environment]::SetEnvironmentVariable(\"Position__Title\", \"Environment_Editor\", \"Machine\")\n  [Environment]::SetEnvironmentVariable(\"Position__Name\", \"Environment_Rick\", \"Machine\")\n  ```\n\n## 参考\n* [Azure 向けの GitHub Actions の variable substitution を使用する \\| Microsoft Docs](https://docs.microsoft.com/ja-jp/azure/developer/github/github-variable-substitution)\n* [Using secrets safely in development with \\.NET Core – Sam Learns Azure](https://samlearnsazure.blog/2020/06/17/using-secrets-safely-in-development-with-net-core/)\n* [Avoid Secrets in DotNet Core Tests\\.](https://patrickhuber.github.io/2017/07/26/avoid-secrets-in-dot-net-core-tests.html)\n* [Using User Secrets Configuration In \\.NET \\- \\.NET Core Tutorials](https://dotnetcoretutorials.com/2022/04/28/using-user-secrets-configuration-in-net/)\n\n## 参考（その２）\n* [暗号化されたシークレット \\- GitHub Docs](https://docs.github.com/ja/actions/security-guides/encrypted-secrets)\n* [Managing Secrets in \\.NET Console Apps](https://swharden.com/blog/2021-10-09-console-secrets/)\n* [integration testing \\- How to configure \\.net core 3\\.1 appsettings to run tests on Github actions \\- Stack Overflow](https://stackoverflow.com/questions/62220945/how-to-configure-net-core-3-1-appsettings-to-run-tests-on-github-actions)\n* [Microsoft\\.Extensions\\.Configuration\\.UserSecrets 6\\.0\\.0\\-preview\\.1\\.21102\\.12 throwing secrets\\.json error in CI/CD pipelines · Issue \\#48485 · dotnet/runtime](https://github.com/dotnet/runtime/issues/48485)\n* [Dotnet6 upgrade with recommended solution by samsmithnz · Pull Request \\#3 · samsmithnz/UserSecretsRegression](https://github.com/samsmithnz/UserSecretsRegression/pull/3/files)\n\n## 参考（その３）\n* [How to manage secrets in \\.NET locally and on GitHub? \\- Maytham Fahmi](https://itbackyard.com/how-to-manage-secrets-in-net-locally-and-on-github/)\n* [GitHub Actions: Workflows triggered by Dependabot PRs will run with read\\-only permissions \\| GitHub Changelog](https://github.blog/changelog/2021-02-19-github-actions-workflows-triggered-by-dependabot-prs-will-run-with-read-only-permissions/)\n* [Accessing secrets \\- GitHub Docs](https://docs.github.com/en/code-security/dependabot/working-with-dependabot/automating-dependabot-with-github-actions#accessing-secrets)\n* [Configuring access to private registries for Dependabot \\- GitHub Docs](https://docs.github.com/en/code-security/dependabot/working-with-dependabot/configuring-access-to-private-registries-for-dependabot)\n* [About encrypted secrets for Dependabot \\- GitHub Docs](https://docs.github.com/en/code-security/dependabot/working-with-dependabot/configuring-access-to-private-registries-for-dependabot#about-encrypted-secrets-for-dependabot)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmaremare%2Fusingsecretssandbox","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmaremare%2Fusingsecretssandbox","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmaremare%2Fusingsecretssandbox/lists"}