dotnet 解決使用本地不安全 http 的 NuGet 源 NU1803 警告或構建失敗問題

lindexi發表於2024-07-20

出於安全性考慮,微軟在 NuGet 的 6.3 版本開始引入 NU1803 警告,此警告將在遇到使用的 NuGet 源為 http 源時觸發。 微軟推薦 NuGet 的源應該都是安全的 https 源,甚至在 dotnet 9 預覽版本里面將其視為構建錯誤

在微軟的 NuGet is HTTPS everywhere 文件裡面說明了此決策的原因。但同時在許多開發環境中,將會使用到內部或本地的 http 源,比如說公司或團隊內部搭建的 nuget 源。儘管使用的是不安全的 http 協議,但對於本地或內部源來說,完全不會因此導致安全性問題

在 2024 的 10 月之前,咱依然可以使用 NoWarn 配置忽略 NU1803 警告,如以下程式碼

<NoWarn>$(NoWarn);NU1803</NoWarn>

以上程式碼可以寫到你的 csproj 專案檔案裡面,也可以放在 Directory.Build.props 做全域性忽略。將 NoWarn 放入到 PropertyGroup 裡即可

  <PropertyGroup>
    ... 忽略其他配置
    <!--
      新增 NoWarn 以移除構建警告
      NU1803: 使用了 http 不安全的 NuGet 源
    -->
    <NoWarn>$(NoWarn);NU1803</NoWarn>
  </PropertyGroup>

在此時間之後,微軟也許會直接讓使用 http 協議的 NuGet 源的專案構建不透過。咱如果確認本地或內部的 NuGet 源安全,在 NuGet 的 6.8 以上版本,可在 NuGet 源裡新增 allowInsecureConnections 配置,編輯之後的 NuGet.config 檔案裡面配置的包源的程式碼如下

<packageSources>
    <add key="http-source" value="http://httpsourcetrusted/" allowInsecureConnections="true" />
</packageSources>

以上的 allowInsecureConnections 的含義如下

When false, or not specified, NuGet will emit a warning when the source uses http, rather than https. If you are confident that communication with this source will never be at risk of interception attacks, you can set the value to true to suppress the warning. Supported in NuGet 6.8+.

詳細請看 https://learn.microsoft.com/en-us/nuget/reference/nuget-config-file#packagesources

以上的 NuGet.config 可以放在專案的 sln 所在的資料夾,隨著專案走。也可以存放在本機裡作為全域性配置,本機路徑分別如下

  • Windows:
    • 使用者級: %appdata%\NuGet\NuGet.Config
    • 機器級: ``
  • Mac/Linux:
    • 使用者級: ~/.config/NuGet/NuGet.Config~/.nuget/NuGet/NuGet.Config
    • 機器級: /etc/opt/NuGet/Config (Linux) 和 /Library/Application Support (Mac)

參考文件:

  • https://github.com/NuGet/Home/issues/12013
  • https://github.com/NuGet/Home/issues/12015
  • https://learn.microsoft.com/en-us/nuget/reference/nuget-config-file#packagesources

相關文章