# C++ 연동

> Learn how to implement authentication using C++ in Unreal Engine.

다음 섹션에서는 [Unreal Engine 보조 시스템](https://docs.unrealengine.com/5.3/en-US/programming-subsystems-in-unreal-engine/)을 사용하여 Authentication SDK와 연동하는 방법을 설명합니다. 블루프린트 API는 이 기능을 노출하는 Authentication 보조 시스템을 제공합니다.

## 종속성으로 Authentication SDK 추가##add-the-authentication-sdk-as-a-dependency

계속하기 전에 모듈의 공용 종속성으로 `Authentication`을 추가한 다음 플러그인 헤더 파일을 클래스에 포함합니다.

Unreal 프로젝트 빌드 파일에서 모듈의 종속 관계로 `Authentication`를 추가합니다.

```cpp
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "Authentication" });
```

자신의 클래스에 액세스하려는 플러그인 헤더 파일을 포함합니다.

```cpp
#include "AuthenticationSubsystem.h"
```

## Authentication 보조 시스템##authentication-subsystem

Authentication 보조 시스템에는 Unity Authentication 서버와 통신하고, 플레이어 프로필 정보를 보관하고, 로컬 스토리지에서 플레이어 환경 설정을 로드/언로드하는 인터페이스가 포함되어 있습니다. 인증 라이프사이클을 처리하고 프로젝트의 중요한 인증 정보를 저장하는 역할을 담당합니다.

[UGameInstance](https://docs.unrealengine.com/5.3/en-US/API/Runtime/Engine/Engine/UGameInstance/)에서 레퍼런스를 가져와서 Authentication 보조 시스템에 액세스할 수 있습니다.

```cpp
UWorld* GameWorld = GetWorld();
UGameInstance* GameInstance = GameWorld->GetGameInstance();
UAuthenticationSubsystem* AuthenticationSubsystem = GameInstance->GetSubsystem<UAuthenticationSubsystem>();
```

### SignInAnonymously##signinanonymously

[익명으로 인증](/authentication/use-anon-sign-in.md)하려면 [SignInAnonymously()](./sdk-api/authentication/authentication-subsystem.md#signinanonymously\(fauthenticationsigninoptions,-unity::services::core::thandlerfauthenticationresponse\)) 메서드를 사용합니다. 이는 사용자 정보 없이 빠르게 인증할 수 있는 방법이며, 외부 공급자와의 상호 작용이 필요하지 않습니다. 성공하면 현재 플레이어 프로필이 Unity Authentication 서버에서 반환된 검색된 자격 증명 정보로 채워집니다.

[SignInAnonymously()](./sdk-api/authentication/authentication-subsystem.md#signinanonymously\(fauthenticationsigninoptions,-unity::services::core::thandlerfauthenticationresponse\))는 로그인 수행 방식을 변경하는 파라미터로 [`FAuthenticationSignInOptions`](./sdk-api/authentication/models/authentication-sign-in-options.md) 구조체를 사용합니다. 이러한 파라미터에 대한 자세한 내용은 [Unity API 서비스 기술 자료 페이지](https://services.docs.unity.com/player-auth/v1/index.html)를 참고하십시오.

SDK의 응답은 [`FAuthenticationResponse`](./sdk-api/authentication/models/authentication-response.md)를 수신해야 하는 응답 핸들러에서 처리할 수 있습니다.

```cpp
// Create sign-in options body
FAuthenticationSignInOptions SignInOptions;
SignInOptions.bCreateAccount = true;
SignInOptions.Nonce = TEXT("abc123");

AuthenticationSubsystem->SignInAnonymously(SignInOptions, THandler<FAuthenticationResponse>::CreateLambda([this](FAuthenticationResponse Response)
{
	// Your response logic here
}));
```

### GetUserInfo##getuserinfo

[GetUserInfo()](./sdk-api/authentication/authentication-subsystem.md#getuserinfo\(unity::services::core::thandlerfauthenticationuserresponse\)) 메서드를 사용해 현재 인증된 사용자에 대한 정보를 검색합니다. 여기에는 사용자 ID, 인증 타임스탬프, 세션에 연결된 모든 외부 ID 제공업체 정보 등이 포함됩니다.

SDK의 응답은 [`FAuthenticationUserResponse`](./sdk-api/authentication/models/authentication-user-response.md)를 수신해야 하는 응답 핸들러에서 처리할 수 있습니다.

```cpp
AuthenticationSubsystem->GetUserInfo(
THandler<FAuthenticationUserResponse>::CreateLambda([this](FAuthenticationUserResponse Response)
{
	// Your response logic here
}));
```

### DeleteUser##deleteuser

[DeleteUser()](./sdk-api/authentication/authentication-subsystem.md#deleteuser\(unity::services::core::thandlerbool\)) 메서드를 사용해 현재 인증된 플레이어와 관련된 모든 정보를 삭제합니다. 이 메서드는 또한 플레이어를 로그아웃하고 플레이어에 연결된 모든 플레이어 환경 설정과 프로필을 삭제합니다.

> **Note:**
>
> **참고**: 기본 프로필을 사용하는 동안 [DeleteUser()](./sdk-api/authentication/authentication-subsystem.md#deleteuser\(unity::services::core::thandlerbool\))를 호출하면 프로필 정보가 지워지고 프로필은 그대로 유지됩니다.

SDK의 응답은 응답 핸들러에서 처리할 수 있으며, 이 핸들러는 삭제에 성공하면 값이 `true`이고 그렇지 않으면 `false`인 `bool`을 받아 들여야 합니다.

```cpp
AuthenticationSubsystem->DeleteUser(
THandler<bool>::CreateLambda([this](bool bResponse)
{
	// Your response logic here
}));
```

### RegisterStateChangedCallback##registerstatechangedcallback

[RegisterStateChangedCallback()](./sdk-api/authentication/authentication-subsystem.md#registerstatechangedcallback\(unity::services::core::thandlerfauthenticationstatechangedresponse\)) 메서드를 사용해 [보조 시스템의 상태](./authentication-lifecycle.md)가 변경될 때 호출되는 콜백 함수를 할당합니다. 예를 들어, 할당된 함수는 플레이어가 인증에 성공하고 보조 시스템 상태가 `Authorized`로 변경되면 실행됩니다.

SDK의 응답은 [`AuthenticationStateChangedResponse`](./sdk-api/authentication/models/authentication-state-changed-response.md)를 수신해야 하는 응답 핸들러에서 처리할 수 있습니다.

```cpp
AuthenticationSubsystem->RegisterStateChangedCallback(
THandler<AuthenticationStateChangedResponse>::CreateLambda([this](AuthenticationStateChangedResponse Response)
{
	// Your response logic here
}));
```

### SignOut##signout

[SignOut()](./sdk-api/authentication/authentication-subsystem.md#signout\(bool\)) 메서드를 사용해 현재 인증된 플레이어 프로필에서 로그아웃합니다. 이렇게 하면 현재 플레이어 프로필이 제거되고 기본 프로필로 전환됩니다. 이 메서드에는 이 플레이어와 관련된 모든 저장된 자격 증명 정보를 제거하는 선택적 파라미터도 있습니다.

> **Note:**
>
> **참고**: 기본 프로필을 사용하는 동안 [SignOut()](./sdk-api/authentication/authentication-subsystem.md#signout\(bool\))을 호출하면 프로필 정보가 지워지고 프로필은 그대로 유지됩니다.

```cpp
AuthenticationSubsystem->SignOut(true); // Clear player credentials
```

### SwitchProfile##switchprofile

[SwitchProfile()](./sdk-api/authentication/authentication-subsystem.md#switchprofile\(const-fstring&\))메서드를 사용해 플레이어 프로필로 전환하거나 생성합니다.

> **Note:**
>
> **참고**: [SwitchProfile()](./sdk-api/authentication/authentication-subsystem.md#switchprofile\(const-fstring&\))은 로그아웃한 상태에서만 호출할 수 있습니다. 인증된 상태에서 프로필 전환을 호출하면 경고가 기록되고 아무 일도 일어나지 않습니다.

```cpp
FString NewProfileName = FString(TEXT("new_profile_123"));
AuthenticationSubsystem->SwitchProfile(NewProfileName);
```

### ProfileExists##profileexists

[ProfileExists()](./sdk-api/authentication/authentication-subsystem.md#profileexists\(const-fstring&\)) 메서드를 사용해 현재 세션에 지정된 프로필이 있는지 확인합니다.

> **Note:**
>
> **참고**: [ProfileExists()](./sdk-api/authentication/authentication-subsystem.md#profileexists\(const-fstring&\))는 현재 세션에서 다시 만들지 않은 이전 세션의 프로필을 감지할 수 없습니다.

```cpp
FString ProfileToCheckFor = FString(TEXT("new_profile_123"));
bool bExists = AuthenticationSubsystem->ProfileExists(ProfileToCheckFor);
```

### GetCurrentProfileName##getcurrentprofilename

[GetCurrentProfileName()](./sdk-api/authentication/authentication-subsystem.md#getcurrentprofilename\(\)) 메서드를 사용해 현재 플레이어 프로필의 이름을 검색합니다.

```cpp
FString ProfileName = AuthenticationSubsystem->GetCurrentProfileName();
```

### GetProfileNames##getprofilenames

[GetCurrentProfileName()](./sdk-api/authentication/authentication-subsystem.md#getcurrentprofilename\(\)) 메서드를 사용해 현재 세션에서 사용 중인 모든 플레이어 프로필 이름 목록을 검색합니다.

```cpp
TArray<FString> ProfileNames = AuthenticationSubsystem->GetProfileNames();
```

### RegisterProfileChangedCallback##registerprofilechangedcallback

[RegisterProfileChangedCallback()](./sdk-api/authentication/authentication-subsystem.md#registerprofilechangedcallback\(unity::services::core::thandlerfauthenticationplayerprofilechangedresponse\)) 메서드를 사용해 플레이어 프로필 변경 시 호출되는 콜백 함수를 지정할 수 있습니다. 예를 들어, 할당된 함수는 [SwitchProfile](./cpp-integration.md#switchprofile)이 성공적으로 실행되면 실행됩니다.

SDK의 응답은 [AuthenticationPlayerProfileChangedResponse](./sdk-api/authentication/models/authentication-player-profile-changed-response.md)를 수신해야 하는 응답 핸들러에서 처리할 수 있습니다.

```cpp
AuthenticationSubsystem->RegisterPlayerProfileChangedCallback(
THandler<AuthenticationPlayerProfileChangedResponse>::CreateLambda([this](AuthenticationPlayerProfileChangedResponse Response)
{
	// Your response logic here
}));
```

### RegisterProfileDeletedCallback##registerprofiledeletedcallback

[RegisterProfileChangedCallback()](./sdk-api/authentication/authentication-subsystem.md#registerprofilechangedcallback\(unity::services::core::thandlerfauthenticationplayerprofilechangedresponse\)) 메서드를 사용해 현재 세션에서 플레이어 프로필이 제거될 때 호출되는 콜백 함수를 지정합니다. 예를 들어, 할당된 함수는 [SignOut](./cpp-integration.md#signout)이 성공적으로 실행되면 실행됩니다.

SDK의 응답은 [AuthenticationPlayerProfileChangedResponse](./sdk-api/authentication/models/authentication-player-profile-changed-response.md)를 수신해야 하는 응답 핸들러에서 처리할 수 있습니다.

```cpp
AuthenticationSubsystem->RegisterPlayerProfileChangedCallback(
THandler<AuthenticationPlayerProfileChangedResponse>::CreateLambda([this](AuthenticationPlayerProfileChangedResponse Response)
{
	// Your response logic here
}));
```

### IsSignedIn##issignedin

[IsSignedIn()](./sdk-api/authentication/authentication-subsystem.md#issignedin\(\)) 메서드를 사용해 현재 플레이어 프로필이 익명으로 로그인되어 있는지 확인합니다. '로그인' 상태는 권한이 부여된 상태 또는 만료된 상태로 정의됩니다.

```cpp
bool bSignedIn = AuthenticationSubsystem->IsSignedIn();
```

### IsAnonymous##isanonymous

[IsAuthorized()](./sdk-api/authentication/authentication-subsystem.md#isauthorized\(\))메서드를 사용해 현재 플레이어 프로필이 익명으로 로그인되어 있는지 확인합니다. [SignInAnonymously](./cpp-integration.md#signinanonymously)를 성공적으로 실행하고 나면 true가 반환됩니다.

```cpp
bool bAnonymous = AuthenticationSubsystem->IsAnonymous();
```

### IsAuthorized##isauthorized

[IsAuthorized()](./sdk-api/authentication/authentication-subsystem.md#isauthorized\(\)) 메서드를 사용해 현재 플레이어 프로필이 로그인되어 있고 현재 권한을 부여한 상태인지 확인합니다. 만료 시간이 아직 지나지 않은 상태에서 로그인 메서드를 실행하면 true를 반환해야 합니다.

```cpp
bool bAuthorized = AuthenticationSubsystem->IsAuthorized();
```

### IsExpired##isexpired

[IsExpired()](./sdk-api/authentication/authentication-subsystem.md#isexpired\(\)) 메서드를 사용해 현재 플레이어 프로필의 세션이 만료되었는지 확인합니다. 성공적인 로그인 응답에서 반환된 만료 시간이 지나면 true를 반환해야 합니다.

```cpp
bool bExpired = AuthenticationSubsystem->IsExpired();
```

### SessionTokenExists##sessiontokenexists

[SessionTokenExists()](./sdk-api/authentication/authentication-subsystem.md#sessiontokenexists\(\))메서드를 사용해 현재 플레이어 프로필에 대한 플레이어 환경 설정에 세션 토큰이 있는지 확인합니다.

```cpp
bool bTokenExists = AuthenticationSubsystem->SessionTokenExists();
```

### GetUnityProjectId##getunityprojectid

[GetUnityProjectId()](./sdk-api/authentication/authentication-subsystem.md#getunityprojectid\(\)) 메서드를 사용해 현재 인증 세션과 연결된 Unity 프로젝트 ID를 검색합니다.

```cpp
FGuid ProjectId = AuthenticationSubsystem->GetUnityProjectId();
```

### GetUnityEnvironmentName##getunityenvironmentname

[GetUnityEnvironmentName()](./sdk-api/authentication/authentication-subsystem.md#getunityenvironmentname\(\)) 메서드를 사용해 현재 인증 세션과 연결된 Unity 환경 이름의 이름을 검색합니다.

```cpp
FString EnvironmentId = AuthenticationSubsystem->GetUnityEnvironmentName();
```

### GetAccessToken##getaccesstoken

[GetAccessToken()](./sdk-api/authentication/authentication-subsystem.md#getaccesstoken\(\)) 메서드를 사용해 현재 세션의 액세스 토큰을 검색합니다. 토큰이 없으면 빈 문자열을 반환합니다.

```cpp
FString AccessToken = AuthenticationSubsystem->GetAccessToken();
```

### GetSessionToken##getsessiontoken

[GetSessionToken()](./sdk-api/authentication/authentication-subsystem.md#getsessiontoken\(\)) 메서드를 사용해 현재 세션의 세션 토큰을 검색합니다. 토큰이 없으면 빈 문자열을 반환합니다.

```cpp
FString SessionToken = AuthenticationSubsystem->GetSessionToken();
```

### GetUserId##getuserid

[GetUserId()](./sdk-api/authentication/authentication-subsystem.md#getuserid\(\)) 메서드를 사용해 현재 세션의 사용자 ID를 검색합니다. 토큰이 없으면 빈 문자열을 반환합니다.

> **Note:**
>
> **참고**: [플레이어 프로필 이름](./cpp-integration.md#getcurrentprofilename)과는 다릅니다. 사용자 ID는 Unity Authentication 시스템에서 반환된 고유한 사용자 식별자입니다.

```cpp
FString UserId = AuthenticationSubsystem->GetUserId();
```

### GetState##getstate

[GetState()](./sdk-api/authentication/authentication-subsystem.md#getstate\(\)) 메서드를 사용해 인증 세션의 현재 상태를 검색합니다.

```cpp
EAuthenticationState UserId = AuthenticationSubsystem->GetUserId();
```

### SetUnityProjectId##setunityprojectid

[SetUnityProjectId()](./sdk-api/authentication/authentication-subsystem.md#setunityprojectid\(fguid\)) 메서드를 사용해 현재 인증 세션의 Unity 프로젝트 ID를 설정합니다. 이렇게 하면 프로젝트 설정에서 구성된 Unity 프로젝트 ID가 오버라이드됩니다.

```cpp
FGuid NewProjectId = FGuid(TEXT("00000000-1234-1234-000000000000"));
AuthenticationSubsystem->SetUnityProjectId(NewProjectId);
```

### SetUnityEnvironmentName##setunityenvironmentname

[SetUnityEnvironmentName()](./sdk-api/authentication/authentication-subsystem.md#setunityenvironmentname\(fstring\)) 메서드를 사용해 현재 인증 세션의 Unity 환경 이름을 설정합니다. 이렇게 하면 프로젝트 설정에서 구성된 Unity 환경 이름이 오버라이드됩니다.

```cpp
FString NewEnvironmentName = FString(TEXT("testenv2"));
AuthenticationSubsystem->SetUnityEnvironmentName(NewEnvironmentName );
```
