ASP.NET 쿠키 생성 방식 분석

ASP.NET에서 쿠키가 어떻게 생성되는지 그 과정을 단계별로 살펴보겠습니다. 쿠키 생성은 machineKey 설정과 밀접한 관련이 있으며, 이는 쿠키 생성 알고리즘 및 암호화 키를 결정합니다. 여러 서버로 구성된 부하 분산 환경에서는 일관된 machineKey를 사용하여 쿠키를 복호화해야 합니다. .NET Core 환경에서 ASP.NET 쿠키를 사용하기 위해 알아야 할 필수적인 내용을 다룹니다.

단계별 분석

사용자가 AccountController의 Login 액션을 통해 로그인을 시도하는 과정부터 시작합니다.

//
// POST: /Account/Login
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    // 사용자 로그인 시도
    var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);

    switch (result)
    {
        case SignInStatus.Success:
            // 로그인 성공 시 리디렉션
            return RedirectToLocal(returnUrl);
        // ... 기타 성공/실패 처리 생략
    }
    // ...
}

이 과정에서 SignInManager의 PasswordSignInAsync 메서드가 호출됩니다. 이 메서드의 주요 로직은 다음과 같습니다 (일부 코드 생략):

public virtual async Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout)
{
    // ... 기타 코드 생략
    // 사용자 이름과 비밀번호 확인
    if (await UserManager.CheckPasswordAsync(user, password).WithCurrentCulture())
    {
        // 2단계 인증 비활성화 시
        if (!await IsTwoFactorEnabled(user))
        {
            await UserManager.ResetAccessFailedCountAsync(user.Id).WithCurrentCulture();
        }
        // 로그인 또는 2단계 인증 절차 진행
        return await SignInOrTwoFactor(user, isPersistent).WithCurrentCulture();
    }
    // ... 기타 코드 생략
    return SignInStatus.Failure; // 로그인 실패
}

비밀번호 검증이 성공하면 SignInOrTwoFactor 메서드가 호출됩니다.

private async Task<SignInStatus> SignInOrTwoFactor(TUser user, bool isPersistent)
{
    var id = Convert.ToString(user.Id);
    // 2단계 인증이 활성화되어 있고, 브라우저 기억하기 기능이 사용되지 않은 경우
    if (await IsTwoFactorEnabled(user) && !await AuthenticationManager.TwoFactorBrowserRememberedAsync(id).WithCurrentCulture())
    {
        // 2단계 인증 쿠키 생성
        var identity = new ClaimsIdentity(DefaultAuthenticationTypes.TwoFactorCookie);
        identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, id));
        AuthenticationManager.SignIn(identity);
        return SignInStatus.RequiresVerification; // 2단계 인증 필요
    }
    // 2단계 인증이 필요 없거나 이미 처리된 경우
    await SignInAsync(user, isPersistent, false).WithCurrentCulture();
    return SignInStatus.Success; // 로그인 성공
}

이후 SignInAsync 메서드가 호출되어 실제 쿠키 생성을 위한 준비를 합니다.

public virtual async Task SignInAsync(TUser user, bool isPersistent, bool rememberBrowser)
{
    // 사용자 ID를 기반으로 클레임 기반 ID 생성
    var userIdentity = await CreateUserIdentityAsync(user).WithCurrentCulture();
    // 외부 로그인 또는 2단계 인증 관련 임시 쿠키 제거
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie);
    
    if (rememberBrowser)
    {
        // 브라우저 기억하기 기능 사용 시
        var rememberBrowserIdentity = AuthenticationManager.CreateTwoFactorRememberBrowserIdentity(ConvertIdToString(user.Id));
        // 영구 쿠키 설정 및 브라우저 기억하기 ID와 함께 로그인 처리
        AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, userIdentity, rememberBrowserIdentity);
    }
    else
    {
        // 일반 로그인 처리
        AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, userIdentity);
    }
}

모든 경로는 궁극적으로 AuthenticationManager.SignIn 메서드 호출로 이어지며, 이 메서드가 쿠키 생성의 핵심입니다. AuthenticationManager는 Microsoft.Owin에 정의되어 있습니다.

public void SignIn(AuthenticationProperties properties, params ClaimsIdentity[] identities)
{
    // ... (불필요한 코드 생략)

    // AuthenticationResponseGrant 객체 생성 또는 업데이트
    AuthenticationResponseGrant priorGrant = AuthenticationResponseGrant;
    if (priorGrant == null)
    {
        AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(identities), properties);
    }
    else
    {
        // ... (기존 Grant 병합 로직 생략)
        AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(mergedIdentities), priorGrant.Properties);
    }
}

AuthenticationResponseGrant은 SignInEntry라는 속성을 통해 저장되며, 이 SignInEntry는 IOwinContext에 "security.SignIn" 키로 저장됩니다.

쿠키 생성을 위한 미들웨어

ASP.NET은 미들웨어(Middleware) 모델을 기반으로 동작합니다. MVC 미들웨어에서 AuthenticationResponseGrant/SignInEntry 설정이 완료된 후, CookieAuthentication 미들웨어가 이 정보를 받아 쿠키를 생성합니다. 이 핵심 로직은 CookieAuthenticationHandler 클래스에 구현되어 있습니다.

protected override async Task ApplyResponseGrantAsync()
{
    // 로그인 정보를 조회합니다.
    AuthenticationResponseGrant signin = Helper.LookupSignIn(Options.AuthenticationType);
    // ... (일부 코드 생략)

    if (shouldSignin)
    {
        // 쿠키 생성을 위한 컨텍스트 객체 생성
        var signInContext = new CookieResponseSignInContext(
            Context,
            Options,
            Options.AuthenticationType,
            signin.Identity,
            signin.Properties,
            cookieOptions);

        // ... (일부 코드 생략)

        // 인증 티켓 생성
        model = new AuthenticationTicket(signInContext.Identity, signInContext.Properties);
        // ... (일부 코드 생략)

        // 티켓을 암호화하여 쿠키 값으로 변환
        string cookieValue = Options.TicketDataFormat.Protect(model);

        // Http 응답에 쿠키 추가
        Options.CookieManager.AppendResponseCookie(
            Context,
            Options.CookieName,
            cookieValue,
            signInContext.CookieOptions);
    }
    // ... (일부 코드 생략)
}

Cookie 생성 과정

AuthenticationTicket이 실제 쿠키 문자열로 변환되는 핵심 단계는 다음과 같습니다.

string cookieValue = Options.TicketDataFormat.Protect(model);

이후 CookieManager를 통해 이 쿠키 값이 HTTP 응답 헤더에 추가됩니다.

Protect 메서드는 다음과 같이 동작합니다:

public string Protect(TData data)
{
    // 데이터를 직렬화합니다.
    byte[] userData = _serializer.Serialize(data);
    // 직렬화된 데이터를 암호화합니다.
    byte[] protectedData = _protector.Protect(userData);
    // 암호화된 데이터를 Base64 URL 형식으로 인코딩합니다.
    string protectedText = _encoder.Encode(protectedData);
    return protectedText;
}

여기서 사용되는 주요 구성 요소는 다음과 같습니다:

  • _serializer: AuthenticationTicket을 바이트 배열로 직렬화하고 GZip으로 압축합니다.
  • _protector: IDataProtector 인터페이스를 구현하며, 실제 암호화/복호화를 담당합니다. 기본 구현은 MachineKey를 사용합니다.
  • _encoder: 암호화된 바이트 배열을 Base64 URL 형식의 문자열로 인코딩합니다.

IDataProtector 와 MachineKey

IDataProtector는 CookieAuthenticationMiddleware에서 초기화될 때 생성됩니다. 기본적으로 MachineKeyDataProtectionProvider가 사용되며, 이는 web.config 또는 app.config의 machineKey 설정을 활용합니다.

// MachineKeyDataProtector의 Protect 메서드 (내부 구현)
public virtual byte[] Protect(byte[] userData)
{
    // machineKey 설정을 사용하여 데이터를 보호합니다.
    return MachineKey.Protect(userData, _purposes);
}

이처럼 ASP.NET 쿠키는 SignInManager, AuthenticationManager, CookieAuthenticationMiddleware, MachineKey 등 여러 계층의 구성 요소를 거쳐 생성됩니다.

쿠키 복호화 및 분석 (예시)

생성된 쿠키를 복호화하고 분석하는 과정은 다음과 같습니다. (이 코드는 .NET Framework 환경에서 Microsoft.Owin.Security NuGet 패키지가 설치되어 있어야 실행 가능합니다.)

// 실제 쿠키 값 (예시)
string cookie = "..."; 

// Base64 URL 디코딩
var bytes = TextEncodings.Base64Url.Decode(cookie);

// MachineKey를 사용하여 복호화
// purpose 문자열은 CookieAuthenticationMiddleware 생성 시 사용된 값과 일치해야 합니다.
var decrypted = MachineKey.Unprotect(bytes,
    "Microsoft.Owin.Security.Cookies.CookieAuthenticationMiddleware",
    "ApplicationCookie", // ASP.NET Identity 기본값
    "v1"); // 버전 정보

// TicketSerializer를 사용하여 복호화된 데이터를 AuthenticationTicket으로 역직렬화
var serializer = new TicketSerializer();
var ticket = serializer.Deserialize(decrypted);

// ticket 객체를 통해 사용자 정보(Claims) 및 기타 속성에 접근 가능
// LINQPad의 Dump() 메서드와 유사하게 ticket 내용을 출력할 수 있습니다.
// 예를 들어:
foreach (var claim in ticket.Identity.Claims)
{
    Console.WriteLine($"{claim.Type}: {claim.Value}");
}
Console.WriteLine($"IsPersistent: {ticket.Properties.IsPersistent}");

주의: 위 예제 코드는 .NET Framework 환경을 기준으로 작성되었습니다. .NET Core에서는 MachineKey 대신 다른 데이터 보호 메커니즘을 사용하므로 직접적인 적용이 어렵습니다.

.NET Core 환경에서의 쿠키 생성 및 보호 방식에 대한 심층적인 내용은 별도로 다룰 예정입니다.

태그: ASP.NET OWIN cookie authentication MachineKey

11월 6일 00:46에 게시됨