다음을 통해 공유


ASP.NET Core 3.1 Razor Pages SameSite cookie 샘플

ASP.NET Core 3.0에는 특성 작성을 표시하지 않기 위한 UnspecifiedSameSiteMode 특성 값을 비롯한 SameSite 특성이 기본으로 지원됩니다.

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.Unspecified.
    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.Unspecified;
        }
    }
}

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

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

추가 정보

Chrome 업데이트ASP.NET Core SameSite 설명서