다음을 통해 공유


ASP.NET Core 2.1 Razor Pages SameSite cookie 샘플

이 샘플은 .NET Framework를 대상으로 합니다.

ASP.NET Core 2.1은 SameSite 특성을 기본으로 지원하지만 원래 표준에 기록되었습니다. 패치된 동작은 값을 전혀 내보내지 않고 값이 None인 sameSite 특성을 내보내는 SameSite.None의 의미를 변경했습니다. 값을 내보내지 않으려면 cookie의 SameSite 속성을 -1로 설정할 수 있습니다.

ASP.NET Core IdentityIFrames 또는 OpenIdConnect 통합과 같은 고급 시나리오를 제외하고 SameSite cookie의 영향을 크게 받지 않습니다.

Identity를 사용할 때 cookie 공급자 또는 호출 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)을 추가하지 마세요. Identity가 알아서 처리합니다.

SameSite 특성 작성

다음 코드는 cookie에 SameSite 특성을 작성하는 방법의 예제입니다.

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)(-1).
    SameSite = SameSiteMode.None
};

// Add the cookie to the response cookie collection
Response.Cookies.Append(CookieName, "cookieValue", cookieOptions);

Cookie 인증, 세션 상태 및 기타 다양한 구성 요소는 Cookie 옵션을 통해 sameSite 옵션을 설정합니다.

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 값을 가진 특성을 내보내고 Secure 특성을 true로 설정합니다.

샘플 실행

샘플 프로젝트를 실행하는 경우 초기 페이지에서 브라우저 디버거를 로드하고 이 디버거를 사용하여 사이트의 cookie 컬렉션을 봅니다. Edge 및 Chrome에서 이렇게 하려면 F12를 누른 다음, Application 탭을 선택하고 Storage 섹션의 Cookies 옵션 아래에서 사이트 URL을 클릭합니다.

Browser Debugger Cookie List

위의 이미지에서 “SameSite Cookie 만들기” 단추를 클릭하면 샘플에서 만든 cookie에 샘플 코드에 설정된 값과 일치하는 Lax의 SameSite 특성 값이 있음을 확인할 수 있습니다.

인터셉팅 s cookie

cookie를 가로채기 위해 사용자의 브라우저 에이전트에서 지원에 따라 none 값을 조정하려면 CookiePolicy 미들웨어를 사용해야 합니다. 이는 cookie를 작성하고 ConfigureServices() 내에서 구성된 구성 요소 http 요청 파이프라인에 배치해야 합니다.

파이프라인에 삽입하려면 Startup.csConfigure(IApplicationBuilder, IHostingEnvironment) 메서드에서 app.UseCookiePolicy()를 사용합니다. 예를 들면 다음과 같습니다.

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가 추가되거나 삭제될 때 도우미 클래스를 호출하도록 cookie 정책을 구성합니다.

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)(-1);
        }
    }
}

도우미 함수 CheckSameSite(HttpContext, CookieOptions)는:

  • cookie가 요청에 추가되거나 요청에서 삭제될 때 호출됩니다.
  • SameSite 속성이 None으로 설정되어 있는지 확인합니다.
  • SameSiteNone으로 설정되고 현재 사용자 에이전트가 none 특성 값을 지원하지 않는 것으로 알려져 있는 경우 검사 SameSiteSupport 클래스를 사용하여 수행됩니다.
    • 속성을 (SameSiteMode)(-1)로 설정하여 값을 내보내도록 SameSite를 설정합니다.

대상 .NET Framework 지정

ASP.NET Core 및 System.Web(ASP.NET 4.x)에는 SameSite의 독립적인 구현이 있습니다. ASP.NET Core를 사용하는 경우 .NET Framework에 대한 SameSite KB 패치가 필요하지 않으며 System.Web SameSite 최소 프레임워크 버전 요구 사항(.NET Framework 4.7.2)이 ASP.NET Core에 적용되지 않습니다.

.NET의 ASP.NET Core에서 적절한 수정 사항을 얻으려면 NuGet 패키지 종속성을 업데이트해야 합니다.

.NET Framework에 대한 ASP.NET Core 변경 내용을 얻으려면 패치된 패키지 및 버전(2.1.14 이상 2.1 버전)에 대한 직접 참조가 있는지 확인합니다.

<PackageReference Include="Microsoft.Net.Http.Headers" Version="2.1.14" />
<PackageReference Include="Microsoft.AspNetCore.CookiePolicy" Version="2.1.14" />

추가 정보

Chrome 업데이트ASP.NET Core SameSite 설명서ASP.NET Core 2.1 SameSite 변경 알림