This document is about: SERVER 5
SWITCH TO

Facebook 인증

Facebook 인증의 경우, 클라이언트는 먼저 Meta의 API를 사용하여 사용자를 인증한 후, 결과로 생성된 시크릿 토큰을 Photon에 전송하여 신원을 확인하고 사용합니다.

이 페이지는 설정 및 워크플로우를 설명합니다.

서버 측

Facebook 앱 설정

Facebook 애플리케이션이 없다면 먼저 생성해야 합니다.

  • Facebook Developers 웹사이트에 접속하여 로그인합니다.
  • Apps -> Create a New App 을 클릭하고 앱 이름을 입력한 뒤 Create App 버튼을 누릅니다.
  • Apps -> [your_app] 을 선택한 후 App IDApp Secret을 복사합니다.

Photon 설정

  • "deploy\NameServer\bin\NameServer.xml.config" 파일을 엽니다.
  • CustomAuth가 활성화되어 있는지 확인합니다. Enabled는 true여야 합니다.
  • 필요에 따라 AllowAnonymous를 true 또는 false로 설정할 수 있습니다.
    보안상 false로 설정하는 것을 권장합니다.
  • AuthenticationType을 "2"로 설정하세요. 이는 Facebook 인증 제공자 유형 코드입니다.
  • 원하는 이름을 선택하세요. 이 예제에서는 "Facebook"을 사용했지만 변경할 수 있습니다.
  • "AuthUrl"은 필수 항목이지만 내부 인증 엔드포인트를 사용하므로 비워둡니다.
  • Facebook 개발자 포털에서 복사한 AppId와 Secret 값을 입력합니다.

XML

  <CustomAuth Enabled="true" AllowAnonymous="false">
    <AuthProviders>
      <AuthProvider Name="Facebook"
                    AuthenticationType="2"
                    AuthUrl=""
                    Secret="Val1"
                    AppId="Val2" />
    </AuthProviders>
  </CustomAuth>

클라이언트 측

클라이언트 측에서는 앱이 먼저 Facebook을 통해 인증을 받아 토큰을 획득해야 하며, 이 토큰은 AuthenticationValues를 통해 Photon 서버로 전송됩니다.

Unity에서 필요한 작업은 다음과 같습니다:

  • Facebook SDK for Unity를 가져옵니다.
  • Unity 메인 메뉴에서 Facebook -> Edit Settings 로 이동한 후, Facebook 애플리케이션의 App NameApp Id를 입력합니다.

구현

새로운 MonoBehaviour를 생성하고, 씬의 오브젝트에 추가한 후 Facebook 초기화 및 로그인을 위한 다음 코드를 작성합니다:

C#

// Include Facebook namespace
using Facebook.Unity;

// [..]

private void Awake()
{
    if (!FB.IsInitialized)
    {
        // Initialize the Facebook SDK
        FB.Init(InitCallback);
    }
    else
    {
        FacebookLogin();
    }
}

private void InitCallback()
{
    if (FB.IsInitialized)
    {
        FacebookLogin();
    }
    else
    {
        Debug.Log("Failed to initialize the Facebook SDK");
    }
}

private void FacebookLogin()
{
    if (FB.IsLoggedIn)
    {
        OnFacebookLoggedIn();
    }
    else
    {
        var perms = new List<string>(){"public_profile", "email", "user_friends"};
        FB.LogInWithReadPermissions(perms, AuthCallback);
    }
}

private void AuthCallback(ILoginResult result)
{
    if (FB.IsLoggedIn)
    {
        OnFacebookLoggedIn();
    }
    else
    {
        Debug.LogErrorFormat("Error in Facebook login {0}", result.Error);
    }
}

OnFacebookLoggedIn() 은 Facebook 인증이 완료되어 사용자의 Facebook 토큰이 사용 가능할 때 호출됩니다.

아래 예제는 AuthenticationValues를 설정하는 방법을 보여줍니다:

C#

private void OnFacebookLoggedIn()
{
    // Facebook's AccessToken class will have session details
    string aToken = AccessToken.CurrentAccessToken.TokenString;
    string facebookId = AccessToken.CurrentAccessToken.UserId;

    var authValues = new AuthenticationValues();
    authValues.AuthType = CustomAuthenticationType.FacebookGaming;  // specifically for gaming apps
    authValues.UserId = facebookId;
    authValues.AddAuthParameter("token", aToken);

    // set the new authValues on the client / runner and connect
    // example for Realtime API

    client.AuthValues = authValues;
    client.ConnectUsingSettings();
}

앱이 Facebook Gaming API(https://developers.facebook.com/docs/games 에 설명됨)를 사용하지 않는 경우, AuthTypeCustomAuthenticationType.Facebook으로 설정해야 합니다.

그 이후로는 일반적인 연결 워크플로우가 진행됩니다. 이는 사용 중인 Photon SDK에 따라 약간씩 다릅니다.

C#의 Realtime API에서는 IConnectionCallbacks를 구현하여 OnConnectedToMaster()OnCustomAuthenticationFailed(string debugMessage)를 확인해야 합니다.

C#

    public void OnConnectedToMaster()
    {
        Debug.Log("Successfully connected to Photon!");
    }

    // something went wrong, check the setup of the Facebook app, login, token, etc.
    public void OnCustomAuthenticationFailed(string debugMessage)
    {
        Debug.LogErrorFormat("Error authenticating to Photon using facebook: {0}", debugMessage);
    }
Back to top