ASP.NET Core 3.1 Razor 頁面 SameSite cookie 範例ASP.NET Core 3.1 Razor Pages SameSite cookie sample
ASP.NET Core 3.0 內建支援 SameSite 屬性,包括的 SameSiteMode
屬性值 Unspecified
來抑制寫入屬性。ASP.NET Core 3.0 has built-in support for the SameSite attribute, including a SameSiteMode
attribute value of Unspecified
to suppress writing the attribute.
ASP.NET Core Identity 大部分不會受到 SameSite cookie 的影響,但像是 IFrames
或整合的 advanced 案例除外 OpenIdConnect
。ASP.NET Core Identity is largely unaffected by SameSite cookies except for advanced scenarios like IFrames
or OpenIdConnect
integration.
使用時 Identity
,請勿新增任何 cookie 提供者或呼叫 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
,就 Identity
會處理這項作業。When using Identity
, do not add any cookie providers or call services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
, Identity
takes care of that.
寫入 SameSite 屬性Writing the SameSite attribute
以下是如何在上撰寫 SameSite 屬性的範例 cookie ;Following is an example of how to write a SameSite attribute on a cookie;
var cookieOptions = new CookieOptions
{
// Set the secure flag, which Chrome's changes will require for SameSite none.
// Note this will also require you to be running on HTTPS
Secure = true,
// Set the cookie to HTTP only which is good practice unless you really do need
// to access it client side in scripts.
HttpOnly = true,
// Add the SameSite attribute, this will emit the attribute with a value of none.
// To not emit the attribute at all set the SameSite property to SameSiteMode.Unspecified.
SameSite = SameSiteMode.None
};
// Add the cookie to the response cookie collection
Response.Cookies.Append(CookieName, "cookieValue", cookieOptions);
設定 Cookie 驗證和會話狀態 cookie sSetting Cookie Authentication and Session State cookies
Cookie 驗證、會話狀態和 各種其他元件 會透過選項設定其 sameSite 選項 Cookie ,例如Cookie authentication, session state and various other components set their sameSite options via Cookie options, for example
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.SameSite = SameSiteMode.None;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.IsEssential = true;
});
services.AddSession(options =>
{
options.Cookie.SameSite = SameSiteMode.None;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.IsEssential = true;
});
在上面顯示的程式碼中 cookie ,驗證和會話狀態都會將其 sameSite 屬性設定為 None,發出具有值的屬性, None
並將安全屬性設定為 true。In the code shown above both cookie authentication and session state set their sameSite attribute to None, emitting the attribute with a None
value, and also set the Secure attribute to true.
執行範例Run the sample
如果您執行 範例專案,請在初始頁面上載入您的瀏覽器偵錯工具,並使用它來查看 cookie 網站的集合。If you run the sample project, load your browser debugger on the initial page and use it to view the cookie collection for the site. 若要在 Edge 和 Chrome 中這麼做,請按一下 [] 索引標籤,然後在 F12
Application
區段中的選項下按一下網站 URL Cookies
Storage
。To do so in Edge and Chrome press F12
then select the Application
tab and click the site URL under the Cookies
option in the Storage
section.
您可以在上方的影像中看到 cookie ,當您按一下 [建立 SameSite] 按鈕時,範例所建立的 Cookie SameSite 屬性值,與 Lax
範例程式碼中所設定的值相符。You can see from the image above that the cookie created by the sample when you click the "Create SameSite Cookie" button has a SameSite attribute value of Lax
, matching the value set in the sample code.
攔截 cookie sIntercepting cookies
為了攔截 cookie s,若要根據使用者的瀏覽器代理程式中的支援來調整無值,您必須使用 CookiePolicy
中介軟體。In order to intercept cookies, to adjust the none value according to its support in the user's browser agent you must use the CookiePolicy
middleware. 這必須放入 HTTP 要求管線中, 才能 在 cookie 中寫入及設定的任何元件 ConfigureServices()
。This must be placed into the http request pipeline before any components that write cookies and configured within ConfigureServices()
.
若要將它插入管線中,請使用 app.UseCookiePolicy()
Startup.cs 中的 Configure(IApplicationBuilder, IHostingEnvironment)
方法。 Startup.csTo insert it into the pipeline use app.UseCookiePolicy()
in the Configure(IApplicationBuilder, IHostingEnvironment)
method in your Startup.cs. 例如:For example
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
然後在中 ConfigureServices(IServiceCollection services)
設定 cookie 原則,以在附加或刪除時呼叫 helper 類別 cookie ,如下所示:Then in the ConfigureServices(IServiceCollection services)
configure the cookie policy to call out to a helper class when cookies are appended or deleted, like so;
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
options.OnAppendCookie = cookieContext =>
CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
options.OnDeleteCookie = cookieContext =>
CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
});
}
private void CheckSameSite(HttpContext httpContext, CookieOptions options)
{
if (options.SameSite == SameSiteMode.None)
{
var userAgent = httpContext.Request.Headers["User-Agent"].ToString();
if (SameSite.BrowserDetection.DisallowsSameSiteNone(userAgent))
{
options.SameSite = SameSiteMode.Unspecified;
}
}
}
Helper 函數 CheckSameSite(HttpContext, CookieOptions)
:The helper function CheckSameSite(HttpContext, CookieOptions)
:
- 當將 cookie s 附加至要求或從要求中刪除時,會呼叫。Is called when cookies are appended to the request or deleted from the request.
- 檢查
SameSite
屬性是否設定為None
。Checks to see if theSameSite
property is set toNone
. - 如果
SameSite
設定為None
,且目前的使用者代理程式已知不支援 none 屬性值,則為。IfSameSite
is set toNone
and the current user agent is known to not support the none attribute value. 檢查是使用 SameSiteSupport 類別來完成:The check is done using the SameSiteSupport class:- 藉
SameSite
由將屬性設定為,將設定為不發出值(SameSiteMode)(-1)
SetsSameSite
to not emit the value by setting the property to(SameSiteMode)(-1)
- 藉
相關資訊More Information
Chrome 更新 ASP.NET Core SameSite 檔Chrome Updates ASP.NET Core SameSite Documentation