ASP.NET 4.7.2 C# MVC용 SameSite 쿠키 샘플

.NET Framework 4.7은 SameSite 특성을 기본적으로 지원하지만 원래 표준을 준수합니다. 패치된 동작은 값을 None전혀 내보내지 않고 값을 사용하여 특성을 내보내도록 의 의미를 SameSite.None 변경했습니다. 값을 내보내지 않으려면 쿠키의 SameSite 속성을 -1로 설정할 수 있습니다.

SameSite 특성 작성

다음은 쿠키에 SameSite 특성을 작성하는 방법의 예입니다.

// Create the cookie
HttpCookie sameSiteCookie = new HttpCookie("SameSiteSample");

// Set a value for the cookieSite none.
// Note this will also require you to be running on HTTPS
sameSiteCookie.Value = "sample";

// Set the secure flag, which Chrome's changes will require for Same
sameSiteCookie.Secure = true;

// Set the cookie to HTTP only which is good practice unless you really do need
// to access it client side in scripts.
sameSiteCookie.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 -1.
sameSiteCookie.SameSite = SameSiteMode.None;

// Add the cookie to the response cookie collection
Response.Cookies.Add(sameSiteCookie);

영어 이외의 언어로 읽는 경우 모국어로 코드 주석을 보려면 이 GitHub 토론 문제 에서 알려주세요.

세션 상태에 대한 기본 sameSite 특성은 의 세션 설정에 대한 'cookieSameSite' 매개 변수에 설정됩니다. web.config

<system.web>
  <sessionState cookieSameSite="None">     
  </sessionState>
</system.web>

MVC 인증

OWIN MVC 쿠키 기반 인증은 쿠키 관리자를 사용하여 쿠키 특성을 변경할 수 있도록 합니다. SameSiteCookieManager.cs는 고유한 프로젝트에 복사할 수 있는 이러한 클래스의 구현입니다.

Microsoft.Owin 구성 요소가 모두 버전 4.1.0 이상으로 업그레이드되었는지 확인해야 합니다. packages.config 예를 들어 파일을 확인하여 모든 버전 번호가 일치하는지 확인합니다.

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <!-- other packages -->
  <package id="Microsoft.Owin.Host.SystemWeb" version="4.1.0" targetFramework="net472" />
  <package id="Microsoft.Owin.Security" version="4.1.0" targetFramework="net472" />
  <package id="Microsoft.Owin.Security.Cookies" version="4.1.0" targetFramework="net472" />
  <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net472" />
  <package id="Owin" version="1.0" targetFramework="net472" />
</packages>

그런 다음, 시작 클래스에서 CookieManager를 사용하도록 인증 구성 요소를 구성해야 합니다.

public void Configuration(IAppBuilder app)
{
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        CookieSameSite = SameSiteMode.None,
        CookieHttpOnly = true,
        CookieSecure = CookieSecureOption.Always,
        CookieManager = new SameSiteCookieManager(new SystemWebCookieManager())
    });
}

쿠키 관리자는 쿠키 관리자를 지원하는 구성 요소에 설정해야 합니다. 여기에는 CookieAuthentication 및 OpenIdConnectAuthentication이 포함됩니다.

SystemWebCookieManager는 응답 쿠키 통합과 관련된 알려진 문제를 방지하는 데 사용됩니다.

샘플 실행

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

브라우저 디버거 쿠키 목록

위의 이미지에서 "쿠키 만들기" 단추를 클릭할 때 샘플에서 만든 쿠키의 SameSite 특성 값이 샘플 코드에 설정된 값Lax과 일치하는 것을 볼 수 있습니다.

제어하지 않는 쿠키 가로채기

.NET 4.5.2는 헤더 쓰기를 가로채는 새 이벤트인 Response.AddOnSendingHeaders를 도입했습니다. 클라이언트 컴퓨터로 반환되기 전에 쿠키를 가로채는 데 사용할 수 있습니다. 샘플에서는 브라우저에서 새 sameSite 변경 내용을 지원하는지 여부를 확인하는 정적 메서드로 이벤트를 연결하고, 그렇지 않은 경우 새 None 값이 설정된 경우 특성을 내보내지 않도록 쿠키를 변경합니다.

이벤트를 처리하고 사용자 고유의 코드로 복사할 수 있는 쿠키 sameSite 특성을 조정하는 예제는 event 및 SameSiteCookieRewriter.cs를 연결하는 예제는 global.asax를 참조하세요.

public static void FilterSameSiteNoneForIncompatibleUserAgents(object sender)
{
    HttpApplication application = sender as HttpApplication;
    if (application != null)
    {
        var userAgent = application.Context.Request.UserAgent;
        if (SameSite.BrowserDetection.DisallowsSameSiteNone(userAgent))
        {
            HttpContext.Current.Response.AddOnSendingHeaders(context =>
            {
                var cookies = context.Response.Cookies;
                for (var i = 0; i < cookies.Count; i++)
                {
                    var cookie = cookies[i];
                    if (cookie.SameSite == SameSiteMode.None)
                    {
                        cookie.SameSite = (SameSiteMode)(-1); // Unspecified
                    }
                }
            });
        }
    }
}

명명된 특정 쿠키 동작을 거의 동일한 방식으로 변경할 수 있습니다. 아래 샘플에서는 값을 지원하는 브라우저에서 LaxNone 에서 로 기본 인증 쿠키를 조정하거나 를 지원하지 NoneNone않는 브라우저에서 sameSite 특성을 제거합니다.

public static void AdjustSpecificCookieSettings()
{
    HttpContext.Current.Response.AddOnSendingHeaders(context =>
    {
        var cookies = context.Response.Cookies;
        for (var i = 0; i < cookies.Count; i++)
        {
            var cookie = cookies[i]; 
            // Forms auth: ".ASPXAUTH"
            // Session: "ASP.NET_SessionId"
            if (string.Equals(".ASPXAUTH", cookie.Name, StringComparison.Ordinal))
            { 
                if (SameSite.BrowserDetection.DisallowsSameSiteNone(userAgent))
                {
                    cookie.SameSite = -1;
                }
                else
                {
                    cookie.SameSite = SameSiteMode.None;
                }
                cookie.Secure = true;
            }
        }
    });
}

추가 정보

Chrome 업데이트

OWIN SameSite 설명서

ASP.NET 설명서

.NET SameSite 패치