ASP.NET 4.7.2 VB WebForms에 대한 SameSite 쿠키 샘플

.NET Framework 4.7은 SameSite 특성에 대한 기본 제공 지원을 제공하지만 원래 표준을 준수합니다. 패치된 동작은 값을 전혀 내보내지 않는 대신 None 값을 사용해 SameSite.None 속성을 내보내는 것으로 의미가 변경되었습니다. 값을 내보내지 않으려면 쿠키의 SameSite 속성을 -1로 설정할 수 있습니다.

SameSite 특성 작성

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

' Create the cookie
Dim sameSiteCookie As New HttpCookie("sameSiteSample")

' Set a value for the cookie
sameSiteCookie.Value = "sample"

' Set the secure flag, which Chrome's changes will require for SameSite none.
' Note this will also require you to be running on HTTPS
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

' Expire the cookie in 1 minute
sameSiteCookie.Expires = Date.Now.AddMinutes(1)

' 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>
  <authentication mode="Forms">
    <forms name=".ASPXAUTH" loginUrl="~/" cookieSameSite="None" requireSSL="true">
    </forms>
  </authentication>
</system.web>

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

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

.NET에 대한 2019년 11월 업데이트에서 양식 인증 및 세션 lax 의 기본 설정이 가장 호환되는 설정으로 변경되었습니다. 그러나 iframes에 페이지를 포함하는 경우 이 설정을 None으로 되돌린 다음 아래에 표시된 가로채기 코드를 추가하여 브라우저 기능에 따라 동작을 조정 none 해야 할 수 있습니다.

샘플 실행

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

브라우저 디버거 쿠키 목록

위의 이미지에서 "쿠키 만들기" 버튼을 클릭하면, 샘플 코드 에 설정된 값과 일치하는 SameSite 특성 값을 가진 쿠키가 샘플에서 생성된 것을 확인할 수 있습니다.

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

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

이벤트를 연결하는 예제는 global.asax를 참조하고, 이벤트를 처리하고 쿠키 속성을 조정하는 예제는 SameSiteCookieRewriter.cs를 참조하세요.

Sub FilterSameSiteNoneForIncompatibleUserAgents(ByVal sender As Object)
    Dim application As HttpApplication = TryCast(sender, HttpApplication)

    If application IsNot Nothing Then
        Dim userAgent = application.Context.Request.UserAgent

        If SameSite.DisallowsSameSiteNone(userAgent) Then
            application.Response.AddOnSendingHeaders(
                Function(context)
                    Dim cookies = context.Response.Cookies

                    For i = 0 To cookies.Count - 1
                        Dim cookie = cookies(i)

                        If cookie.SameSite = SameSiteMode.None Then
                            cookie.SameSite = CType((-1), SameSiteMode)
                        End If
                    Next
                End Function)
        End If
    End If
End Sub

명명된 특정 쿠키의 행동을 거의 같은 방식으로 변경할 수 있습니다. 아래 예시에서는 Lax 브라우저에서 기본 인증 쿠키를 None로 조정하고, None 값을 지원하는 브라우저에서만 사용하거나, None을 지원하지 않는 브라우저에서는 sameSite 속성을 제거합니다.

Public Shared Sub AdjustSpecificCookieSettings()
    HttpContext.Current.Response.AddOnSendingHeaders(Function(context)
            Dim cookies = context.Response.Cookies

            For i = 0 To cookies.Count - 1
            Dim cookie = cookies(i)

            If String.Equals(".ASPXAUTH", cookie.Name, StringComparison.Ordinal) Then

                If SameSite.BrowserDetection.DisallowsSameSiteNone(userAgent) Then
                    cookie.SameSite = -1
                Else
                    cookie.SameSite = SameSiteMode.None
                End If

                cookie.Secure = True
            End If
            Next
        End Function)
End Sub

더 많은 정보

Chrome 업데이트

ASP.NET 설명서

.NET SameSite 패치