ASP.NET Core 提供 Api 和模板,以帮助满足一些欧洲常规数据保护法规 (GDPR)要求:
若要启用默认的 cookie 许可功能, 如在 ASP.NET Core 3.0 模板生成的应用中的 ASP.NET Core 2.2 模板中找到的功能:
将using Microsoft.AspNetCore.Http
添加到 using 指令列表。
将CookiePolicyOptions添加Startup.ConfigureServices
到UseCookiePolicy , Startup.Configure
并将其添加到:
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } 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; // requires using Microsoft.AspNetCore.Http; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddRazorPages(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } }
将 cookie 同意部分添加到 _Layout文件:
@*Previous markup removed for brevity*@ </header> <div class="container"> <partial name="_CookieConsentPartial" /> <main role="main" class="pb-3"> @RenderBody() </main> </div> <footer class="border-top footer text-muted"> <div class="container"> © 2019 - RPCC - <a asp-area="" asp-page="/Privacy">Privacy</a> </div> </footer> <script src="~/lib/jquery/dist/jquery.js"></script> <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script> <script src="~/js/site.js" asp-append-version="true"></script> @RenderSection("Scripts", required: false) </body> </html>
将 CookieConsentPartial 文件添加到项目: _
@using Microsoft.AspNetCore.Http.Features @{ var consentFeature = Context.Features.Get<ITrackingConsentFeature>(); var showBanner = !consentFeature?.CanTrack ?? false; var cookieString = consentFeature?.CreateConsentCookie(); } @if (showBanner) { <div id="cookieConsent" class="alert alert-info alert-dismissible fade show" role="alert"> Use this space to summarize your privacy and cookie use policy. <a asp-page="/Privacy">Learn More</a>. <button type="button" class="accept-policy close" data-dismiss="alert" aria-label="Close" data-cookie-string="@cookieString"> <span aria-hidden="true">Accept</span> </button> </div> <script> (function () { var button = document.querySelector("#cookieConsent button[data-cookie-string]"); button.addEventListener("click", function (event) { document.cookie = button.dataset.cookieString; }, false); })(); </script> }
选择本文的 ASP.NET Core 2.2 版本, 了解 cookie 许可功能。
true
, 则不重要的 cookie 不会发送到浏览器。该示例应用允许你测试添加到 ASP.NET Core 2.1 模板的大多数 GDPR 扩展点和 api。 有关测试说明, 请参阅自述文件。
用项目模板创建 Razor Pages 和 MVC 项目包含以下 GDPR 支持:
Startup
类中设置的。CookiePolicyOptions在中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
调用:
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 分部视图: _
@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> }
此部分内容:
<p>
元素, 用于汇总隐私和 cookie 使用策略。如果尚未提供存储 cookie 的许可, 则仅将标记为 "重要" 的 cookie 发送到浏览器。 以下代码使 cookie 非常重要:
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 提供程序不起作用。 若要在禁用跟踪时启用 TempData 提供程序, 请在中Startup.ConfigureServices
将 TempData cookie 标记为重要:
// 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 并不重要。 禁用跟踪后, 会话状态不起作用。 以下代码使会话 cookie 非常重要:
services.AddSession(options => { options.Cookie.IsEssential = true; });
ASP.NET Core 通过单独用户帐户创建的应用包括下载和删除个人数据的代码。
选择用户名, 然后选择 "个人数据":
注意:
Account/Manage
代码, 请参阅基架标识。AspNetUserTokens
将删除存储在标识数据库表中的用户的已保存令牌。某些数据库和存储机制允许静态加密。 静态加密:
例如:
对于不提供静态内置加密的数据库, 您可以使用磁盘加密来提供相同的保护。 例如: