> ## Documentation Index
> Fetch the complete documentation index at: https://devdocs.xbox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 토큰 만료 처리

> GDK 일시 중단 및 재개 흐름을 포함하여 C SDK에서 PlayFab 엔터티 토큰 만료, 백그라운드 토큰 새로 고침 및 수동 재로그인을 처리합니다.

PlayFab Services SDK에는 플레이어의 세션을 활성 상태로 유지하는 데 도움이 되는 백그라운드 토큰 새로 고침 메커니즘이 포함되어 있습니다. 이 메커니즘의 작동 방식과 게임이 조치를 취해야 하는 시점을 이해하는 것은 중요하며, 특히 일시 중단 및 재개를 지원하는 Game Development Kit(GDK) 타이틀에서는 더욱 그렇습니다.

## 자동 토큰 새로 고침의 작동 방식

SDK는 플레이어의 엔터티 토큰을 주기적으로 확인하는 백그라운드 작업자를 실행합니다. 토큰이 **여전히 유효하지만 만료가 임박한 경우**(만료까지 1시간 이내), SDK는 원래 로그인 호출의 자격 증명을 사용해 자동으로 다시 인증합니다. 이 새로 고침이 성공하면 토큰이 투명하게 업데이트되고 **PFEntityHandle**은 계속 유효한 상태를 유지합니다. 게임에서 조치를 취할 필요가 없습니다.

이러한 자동 토큰 새로 고침은 [**PFEntityRegisterTokenRefreshedEventHandler**](/services/playfab/api-references/c/pfentity/functions/pfentityregistertokenrefreshedeventhandler) 콜백을 등록하여 관찰할 수 있습니다([투명한 새로 고침](#transparent-refresh) 참조).

## 게임이 토큰 만료를 처리해야 하는 경우

SDK가 토큰을 자동으로 새로 고칠 **수 없는** 시나리오가 있습니다:

* **토큰이 이미 만료된 경우.** 자동 새로 고침은 토큰이 여전히 유효할 때만 작동합니다. 예를 들어 긴 일시 중단/재개 주기 후처럼 토큰이 완전히 만료된 경우 SDK는 자동 재로그인을 시도하지 않습니다. 대신 **TokenExpiredHandler**를 통해 게임에 알립니다.
* **원래 로그인 자격 증명이 더 이상 유효하지 않은 경우.** 로그인 요청에 원래 제공된 핸들이나 토큰이 더 이상 유효하지 않으면 자동 새로 고침이 실패하고 **TokenExpiredHandler**가 호출됩니다.

<Info>
  [**PFEntityTokenExpiredEventHandler**](/services/playfab/api-references/c/pfentity/functions/pfentitytokenexpiredeventhandler)를 등록하는 것은 모든 타이틀에 권장되며, 일시 중단 및 재개를 지원하는 GDK 타이틀에는 **필수**입니다. 이 핸들러가 없으면 만료된 토큰에서 복구할 방법이 없습니다.
</Info>

### TokenExpiredHandler 등록

콜백을 등록하려면 [**PFEntityRegisterTokenExpiredEventHandler**](/services/playfab/api-references/c/pfentity/functions/pfentityregistertokenexpiredeventhandler)를 사용하고, 토큰이 만료될 때 다시 인증하려면 **PFAuthenticationReLoginWith\*Async**를 사용합니다.

```cpp theme={null}
    PFRegistrationToken registrationTokenExpired{};
    hr = PFEntityRegisterTokenExpiredEventHandler(nullptr, nullptr, [](void* ctx, PFEntityKey const* entityKey)
    {
        PFAuthenticationLoginWithXUserRequest request{};
        request.createAccount = true;
        request.user = user; // An XUserHandle obtained from XUserAddAsync

        XAsyncBlock async{};
        HRESULT hr = PFAuthenticationReLoginWithXUserAsync(GlobalState()->entityHandle, &request, &async); // This assumes the entity handle was stored in the game's global state
        hr = XAsyncGetStatus(&async, true); // This is doing a blocking wait for completion, but you can use the XAsyncBlock to set a callback instead for async style usage

        // After login we could potentially get back a new player entity with a new entity key
        PFEntityKey const* pEntityKey{};
        std::vector<char> entityKeyBuffer;
        size_t size{};
        hr = PFEntityGetEntityKeySize(GlobalState()->entityHandle, &size); // Add your own error handling when FAILED(hr) == true

        entityKeyBuffer.resize(size);
        hr = PFEntityGetEntityKey(GlobalState()->entityHandle, entityKeyBuffer.size(), entityKeyBuffer.data(), &pEntityKey, nullptr);
    }, &registrationTokenExpired);
```

## GDK: 일시 중단, 재개, Quick Resume

GDK 플랫폼(XBOX 콘솔 및 GDK를 사용하는 Windows)에서는 예를 들어 플레이어가 다른 게임으로 전환한 후 Quick Resume을 통해 다시 돌아오는 경우처럼 게임이 오랜 기간 동안 일시 중단될 수 있습니다. 일시 중단 중에 엔터티 토큰이 만료될 수 있습니다. 일시 중단 중에는 코드가 실행되지 않으므로 SDK의 주기적인 백그라운드 새로 고침이 토큰을 살아 있게 유지할 수 없습니다.

### 재개 시 발생하는 일

게임이 재개되면 SDK는 **즉시** 재개된 상태를 감지하고 엔터티 토큰을 확인합니다. 다음 주기적인 새로 고침 주기를 기다리지 않습니다. 일시 중단 중에 토큰이 만료된 경우:

1. SDK가 만료된 토큰을 감지합니다.
2. **TokenExpiredHandler** 콜백이 호출됩니다.
3. 게임은 새 토큰을 획득하기 위해 핸들러에서 **PFAuthenticationReLoginWith\*Async**를 호출해야 합니다.

<Note>
  재개 시 토큰 확인은 네트워크 연결이 복원되는 즉시 트리거됩니다. 재개 후 네트워크를 다시 초기화하는 데 시간이 걸리면 SDK는 토큰을 확인하기 전에 연결을 기다립니다. 토큰 확인이 손실되지 않습니다.
</Note>

## 투명한 새로 고침

SDK가 플레이어의 엔터티 토큰을 자동으로 새로 고칠 때 게임에서 이를 알고 싶다면 콜백을 등록할 수 있습니다. 이 핸들러는 SDK가 만료가 임박한 토큰을 성공적으로 새로 고칠 때 호출됩니다. 게임에서 조치를 취할 필요가 없습니다.

```cpp theme={null}
    PFRegistrationToken registrationTokenRefreshed{};
    hr = PFEntityRegisterTokenRefreshedEventHandler(nullptr, nullptr, [](void* ctx, PFEntityKey const* entityKey, const PFEntityToken* newToken)
    {
        // Perform any logging or other desired actions on token refresh
    }, &registrationTokenRefreshed);
```

## 핸들러 등록 해제

PlayFab을 종료할 때 또는 토큰 만료 및 새로 고침 콜백 수신을 중지하려는 경우, 적절한 등록 해제 함수를 호출합니다.

```cpp theme={null}
    PFEntityUnregisterTokenExpiredEventHandler(registrationTokenExpired);
    PFEntityUnregisterTokenRefreshedEventHandler(registrationTokenRefreshed);
```

## 참조

[API 참조 문서](/services/playfab/api-references/c/pfauthentication/pfauthentication_members)


## Related topics

- [PlayFab 오류 처리](/ko/services/playfab/sdks/c/errors.md)
- [엔터티 핸들](/ko/services/playfab/sdks/c/entity-handles.md)
- [빠른 시작 GDK](/ko/services/playfab/sdks/c/quickstart-gdk.md)
- [PlayFab 지원 언어](/ko/services/playfab/sdks/languages/index.md)
- [XBOX 서비스 인증](/ko/services/xbox-services/fundamentals/s2s-auth-calls/service-authentication/live-xbox-live-authentication.md)
