ASP.NET Core 中的歐盟一般資料保護規定 (GDPR) 支援EU General Data Protection Regulation (GDPR) support in ASP.NET Core

作者:Rick AndersonBy Rick Anderson

ASP.NET Core 提供 Api 和範本,以協助符合某些歐盟一般資料保護規定 (GDPR)需求:ASP.NET Core provides APIs and templates to help meet some of the EU General Data Protection Regulation (GDPR) requirements:

  • 專案範本包括擴充點以及附加虛設常式的標記,您可以使用您的隱私權與 cookie 的使用原則來取代。The project templates include extension points and stubbed markup that you can replace with your privacy and cookie use policy.
  • Cookie 同意功能可讓您要求 (和追蹤) 同意從您的使用者,用來儲存個人資訊。A cookie consent feature allows you to ask for (and track) consent from your users for storing personal information. 如果使用者尚未同意資料收集,而且應用程式有CheckConsentNeeded設定為true,非必要 cookie 不傳送至瀏覽器。If a user hasn't consented to data collection and the app has CheckConsentNeeded set to true, non-essential cookies aren't sent to the browser.
  • Cookie 可以標示為重要。Cookies can be marked as essential. 基本的 cookie 會傳送至瀏覽器中,即使當使用者尚未同意,並已停用追蹤。Essential cookies are sent to the browser even when the user hasn't consented and tracking is disabled.
  • TempData 和工作階段 cookie追蹤已停用時不會運作。TempData and Session cookies aren't functional when tracking is disabled.
  • 身分識別管理頁面提供連結讓您下載及刪除使用者資料。The Identity manage page provides a link to download and delete user data.

範例應用程式可讓您測試大部分的 GDPR 擴充點,而且 Api 新增至 ASP.NET Core 2.1 範本。The sample app allows you test most of the GDPR extension points and APIs added to the ASP.NET Core 2.1 templates. 請參閱讀我檔案檔案以供測試的指示。See the ReadMe file for testing instructions.

檢視或下載範例程式碼 (英文) (如何下載)View or download sample code (how to download)

在範本產生的程式碼中的 ASP.NET Core GDPR 支援ASP.NET Core GDPR support in template-generated code

Razor Pages 和 MVC 專案範本建立的專案具有 GDPR 或 cookie 同意不支援。Razor Pages and MVC projects created with the project templates have no support for GDPR or cookie consent. 若要新增 GDPR,複製 ASP.NET Core 2.2 範本中產生的程式碼。To add GDPR, copy the code generated in the ASP.NET Core 2.2 templates.

Razor Pages 和 MVC 專案範本建立的專案包含下列的 GDPR 支援:Razor Pages and MVC projects created with the project templates include the following GDPR support:

  • CookiePolicyOptionsUseCookiePolicy中所設定Startup類別。CookiePolicyOptions and UseCookiePolicy are set in the Startup class.
  • _CookieConsentPartial.cshtml 部分檢視The _CookieConsentPartial.cshtml partial view. 接受按鈕包含在這個檔案。An Accept button is included in this file. 當使用者按一下接受按鈕,同意將 cookie 提供。When the user clicks the Accept button, consent to store cookies is provided.
  • Pages/Privacy.cshtml頁面或Views/Home/Privacy.cshtml檢視會提供頁面的詳細說明您網站的隱私權原則。The Pages/Privacy.cshtml page or Views/Home/Privacy.cshtml view provides a page to detail your site's privacy policy. _CookieConsentPartial.cshtml檔案會產生 [隱私權] 頁面的連結。The _CookieConsentPartial.cshtml file generates a link to the Privacy page.
  • 使用個別使用者帳戶建立的應用程式,[管理] 頁面會提供連結來下載並刪除使用者個人資料For apps created with individual user accounts, the Manage page provides links to download and delete personal user data.

CookiePolicyOptions 和 UseCookiePolicyCookiePolicyOptions and UseCookiePolicy

CookiePolicyOptions會初始化Startup.ConfigureServices:CookiePolicyOptions are initialized in Startup.ConfigureServices:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services 
    // to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies 
            // is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddDefaultIdentity<IdentityUser>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

        // If the app uses session state, call AddSession.
        // services.AddSession();

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // This method gets called by the runtime. Use this method to configure the 
    // HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseAuthentication();

        // If the app uses session state, call Session Middleware after Cookie 
        // Policy Middleware and before MVC Middleware.
        // app.UseSession();

        app.UseMvc();
    }
}

UseCookiePolicy呼叫Startup.Configure:UseCookiePolicy is called in Startup.Configure:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services 
    // to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies 
            // is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddDefaultIdentity<IdentityUser>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

        // If the app uses session state, call AddSession.
        // services.AddSession();

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // This method gets called by the runtime. Use this method to configure the 
    // HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseAuthentication();

        // If the app uses session state, call Session Middleware after Cookie 
        // Policy Middleware and before MVC Middleware.
        // app.UseSession();

        app.UseMvc();
    }
}

_CookieConsentPartial.cshtml partial view_CookieConsentPartial.cshtml partial view

_CookieConsentPartial.cshtml部分檢視:The _CookieConsentPartial.cshtml partial view:

@using Microsoft.AspNetCore.Http.Features

@{
    var consentFeature = Context.Features.Get<ITrackingConsentFeature>();
    var showBanner = !consentFeature?.CanTrack ?? false;
    var cookieString = consentFeature?.CreateConsentCookie();
}

@if (showBanner)
{
    <nav id="cookieConsent" class="navbar navbar-default navbar-fixed-top" role="alert">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#cookieConsent .navbar-collapse">
                    <span class="sr-only">Toggle cookie consent banner</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <span class="navbar-brand"><span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span></span>
            </div>
            <div class="collapse navbar-collapse">
                <p class="navbar-text">
                    Use this space to summarize your privacy and cookie use policy.
                </p>
                <div class="navbar-right">
                    <a asp-page="/Privacy" class="btn btn-info navbar-btn">Learn More</a>
                    <button type="button" class="btn btn-default navbar-btn" data-cookie-string="@cookieString">Accept</button>
                </div>
            </div>
        </div>
    </nav>
    <script>
        (function () {
            document.querySelector("#cookieConsent button[data-cookie-string]").addEventListener("click", function (el) {
                document.cookie = el.target.dataset.cookieString;
                document.querySelector("#cookieConsent").classList.add("hidden");
            }, false);
        })();
    </script>
}

這個部分中:This partial:

  • 取得使用者追蹤的狀態。Obtains the state of tracking for the user. 如果應用程式設定為需要同意,使用者必須同意之前可以追蹤 cookie。If the app is configured to require consent, the user must consent before cookies can be tracked. 如果需要同意的話,cookie 同意不固定在所建立的導覽列頂端 _Layout.cshtml檔案。If consent is required, the cookie consent panel is fixed at top of the navigation bar created by the _Layout.cshtml file.
  • 提供 HTML<p>項目,以摘述您的隱私權與 cookie 使用的原則。Provides an HTML <p> element to summarize your privacy and cookie use policy.
  • 提供隱私權頁面或檢視,其中詳細說明您網站的隱私權原則的連結。Provides a link to Privacy page or view where you can detail your site's privacy policy.

基本的 cookieEssential cookies

如果同意將 cookie 未提供,標示為重要的 cookie 傳送至瀏覽器。If consent to store cookies hasn't been provided, only cookies marked essential are sent to the browser. 下列程式碼可讓您基本的 cookie:The following code makes a cookie essential:

public IActionResult OnPostCreateEssentialAsync()
{
    HttpContext.Response.Cookies.Append(Constants.EssentialSec, 
        DateTime.Now.Second.ToString(), 
        new CookieOptions() { IsEssential = true });

    ResponseCookies = Response.Headers[HeaderNames.SetCookie].ToString();

    return RedirectToPage("./Index");
}

TempData 提供者和工作階段狀態的 cookie 並不一定TempData provider and session state cookies aren't essential

TempData 提供者cookie 不必要的元素。The TempData provider cookie isn't essential. 如果已停用追蹤,TempData 提供者將無法運作。If tracking is disabled, the TempData provider isn't functional. 若要停用追蹤時,請啟用 TempData 提供者,將 TempData cookie 標示為以Startup.ConfigureServices:To enable the TempData provider when tracking is disabled, mark the TempData cookie as essential in Startup.ConfigureServices:

// The TempData provider cookie is not essential. Make it essential
// so TempData is functional when tracking is disabled.
services.Configure<CookieTempDataProviderOptions>(options => {
    options.Cookie.IsEssential = true;
});

工作階段狀態cookie 不重要。Session state cookies are not essential. 停用追蹤時,工作階段狀態未作用。Session state isn't functional when tracking is disabled. 下列程式碼可讓工作階段 cookie 不可或缺:The following code makes session cookies essential:

services.AddSession(options =>
{
    options.Cookie.IsEssential = true;
});

個人資料Personal data

使用個別使用者帳戶建立的 ASP.NET Core 應用程式包含下載和刪除個人資料的程式碼。ASP.NET Core apps created with individual user accounts include code to download and delete personal data.

選取的使用者名稱,然後選取個人資料:Select the user name and then select Personal data:

管理個人資料頁面

附註:Notes:

  • 若要產生Account/Manage程式碼,請參閱 < Scaffold 識別To generate the Account/Manage code, see Scaffold Identity.
  • 刪除下載連結只會依據預設身分識別資料。The Delete and Download links only act on the default identity data. 建立自訂使用者資料的應用程式必須延伸到 delete/下載自訂的使用者資料。Apps that create custom user data must be extended to delete/download the custom user data. 如需詳細資訊,請參閱 < 加入、 下載及刪除身分識別的自訂使用者資料For more information, see Add, download, and delete custom user data to Identity.
  • 儲存使用者的身分識別資料庫資料表中儲存的語彙基元AspNetUserTokens串聯的 delete 行為,因為透過刪除使用者時,會刪除外部索引鍵Saved tokens for the user that are stored in the Identity database table AspNetUserTokens are deleted when the user is deleted via the cascading delete behavior due to the foreign key.
  • 外部提供者驗證,例如 Facebook 和 Google,無法使用之前接受 cookie 的原則。External provider authentication, such as Facebook and Google, isn't available before the cookie policy is accepted.

待用加密Encryption at rest

某些資料庫和儲存機制允許進行待用加密。Some databases and storage mechanisms allow for encryption at rest. 待用加密:Encryption at rest:

  • 自動加密儲存的資料。Encrypts stored data automatically.
  • 加密而不需要設定、 程式設計中或其他軟體,以存取資料的工作。Encrypts without configuration, programming, or other work for the software that accesses the data.
  • 是最簡單且最安全的選項。Is the easiest and safest option.
  • 讓資料庫可管理金鑰和加密。Allows the database to manage keys and encryption.

例如:For example:

不會提供內建的加密靜止的資料庫,您可以使用磁碟加密來提供相同的保護。For databases that don't provide built-in encryption at rest, you may be able to use disk encryption to provide the same protection. 例如:For example:

其他資源Additional resources