question

pmattei0 avatar image
pmattei0 asked

How tell the client to set a PhotonToken to the user

Hi, im following this tutorial :

https://api.playfab.com/docs/tutorials/landing-tournaments/photon-unity

I have a registeryPlayFabAccount method and I dont know how can I tell the client to set up the Photontoken when he just finished to register ...

Also, is this photon token must be set for the 1st registry only or always when a user is logging in ?

photon
1 comment
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

pmattei0 avatar image pmattei0 commented ·

I just have this :

private void RequestPhotonToken(LoginResult obj)
{
LogMessage("PlayFab authenticated. Requesting photon token...");

_playFabPlayerIdCache = obj.PlayFabId;

PlayFabClientAPI.GetPhotonAuthenticationToken(new GetPhotonAuthenticationTokenRequest()
{
PhotonApplicationId = PhotonNetwork.PhotonServerSettings.AppID
}, AuthenticateWithPhoton, OnPlayFabError);
}

private void AuthenticateWithPhoton(GetPhotonAuthenticationTokenResult obj)
{
LogMessage("Photon token acquired: " + obj.PhotonCustomAuthenticationToken + " Authentication complete.");

var customAuth = new AuthenticationValues { AuthType = CustomAuthenticationType.Custom };

customAuth.AddAuthParameter("username", _playFabPlayerIdCache);

customAuth.AddAuthParameter("token", obj.PhotonCustomAuthenticationToken);

PhotonNetwork.AuthValues = customAuth;
}

And when the user is logged in, I've wrote this but nothing happens :

GetPhotonAuthenticationTokenRequest request = new GetPhotonAuthenticationTokenRequest();

I dont know if that make sense but that seems me good, have you suggestion to resolve it ?

0 Likes 0 ·
brendan avatar image
brendan answered

Are you using the Photon Unity example project linked in that tutorial? The flow is as stated - use PlayFabClientAPI.GetPhotonAuthenticationToken to get the token, and use that to sign into Photon, using their custom authentication system. This is done whenever you log the user in, if you want to connect to Photon. If those steps pass, you're signed into both services, and you can proceed to create lobbies/rooms, as shown in the example.

I'm not clear on what you're referring to with the final GetPhotonAuthenticationTokenRequest reference. That's the object used in the GetPhotonAuthenticationToken call to get the token - it is not an API call itself. You do not need to create another instance of it once you've completed the Photon login, above.

10 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

pmattei0 avatar image pmattei0 commented ·

Thanks for your answer.

I successful send tokens for each user that connects by making a copy paste of the script in the tuto in a new project , but I managed to create a connection system with email and password combo and now I am a little lost to send tokens at each connection

Can you teach me a little? I probably look at all the topics about this but I do not understand how to use it with that email/password combo authentcation.

0 Likes 0 ·
brendan avatar image brendan pmattei0 commented ·

So, you've logged into PlayFab and used the token to sign the players into Photon. Have you done the next step in the example - created a room for the players and connect to it? If you're looking for a deeper dive on specifically using the Photon API calls, you should have a look at the tutorials on their site specific to their service: https://doc.photonengine.com/en-us/realtime/current/getting-started/realtime-intro.

0 Likes 0 ·
pmattei0 avatar image pmattei0 brendan commented ·

Nono... I expressed myself poorly. Sorry for the confusion.

I meant that I'm at the stage where I'm registered and I have managed to identy myself with that email/password.

And now I'm a stuck to integrate photon after identifying myself.

How to make a token for the user who connects ? What I missed with the code above ?

0 Likes 0 ·
Show more comments
pmattei0 avatar image pmattei0 commented ·

Yep I managed to get that photon token with the script on the example.

But I've already a script which use an password / email combo.

My English Is not very good, I may be more clear with this schema :

I feel like I'm missing something ?

0 Likes 0 ·
igpsmrv3.jpg (125.5 KiB)
pmattei0 avatar image pmattei0 pmattei0 commented ·

There is my code, I guess it should be more explicit :

private void OnLoginClicked()
{
_AuthService.Email = Mail.text;
_AuthService.Password = Password.text;
_AuthService.Authenticate(Authtypes.EmailAndPassword);
}

That is when the user click on the login button

And there is the following script :

private void AuthenticateEmailPassword()
{

    PlayFabClientAPI.LoginWithEmailAddress(new LoginWithEmailAddressRequest()
    {
        TitleId = PlayFabSettings.TitleId,
        Email = Email,
        Password = Password,
        InfoRequestParameters = InfoRequestParams
     }, (result) =>
     {

        _playFabId = result.PlayFabId;
        _sessionTicket = result.SessionTicket;


        if (OnLoginSuccess != null)
        {
                OnLoginSuccess.Invoke(result);
        }
    }, (error) =>
    {
        if (OnPlayFabError != null)
        {
            OnPlayFabError.Invoke(error);
        }
    });
}

Can you help me with this photon integration please ?

0 Likes 0 ·
brendan avatar image brendan pmattei0 commented ·

What you're describing in these last two posts is the PlayFab login. From the tutorial, after you have logged the player into PlayFab, you use GetPhotonAuthenticationToken to get a token to sign into Photon, using their customAuth system. Does that help clarify this?

0 Likes 0 ·
pmattei0 avatar image pmattei0 commented ·

Sorry I'm probably a bit confusing in with these tokens and my english deesnt help me much ...

My issue is that I have not the same authentication system than in the tutorial, so I'll not copy their 1st one step, that's make no sense. ( If I do this, I'll have 2 authentication method, I'm right ? )

In the tutorial at the 1st step, it's said : " We pass RequestPhotonToken as a callback to be our next step, if authentication was successful. "

I'm stuck because I don't know how to pass the function RequestPhotonToken as a callback with my authentication login above.

0 Likes 0 ·
pmattei0 avatar image pmattei0 pmattei0 commented ·

I think I understood

Thank you

0 Likes 0 ·
brendan avatar image brendan pmattei0 commented ·

To make sure this is clear for anyone else following the thread, the issue here is that there are two stages:

First, you sign the player into PlayFab. That can be done with any of the Login... API calls.

After that is complete, you can use GetPhotonAuthenticationToken to get an authentication token which is valid for signing the player into Photon, using their custom authentication system.

1 Like 1 ·
Andrew Maksimov avatar image
Andrew Maksimov answered
private void AuthenticateWithPlayFab() {
    PlayFabClientAPI.LoginWithEmailAddress(new LoginWithEmailAddressRequest()
    {
        TitleId = PlayFabSettings.TitleId,
        Email = Email,
        Password = Password,
        InfoRequestParameters = InfoRequestParams
    }, RequestPhotonToken, OnPlayFabError);
}

private void RequestPhotonToken(LoginResult obj) {        
    _playFabId = obj.PlayFabId;
    _sessionTicket = obj.SessionTicket;

    _result = obj;

    PlayFabClientAPI.GetPhotonAuthenticationToken(new GetPhotonAuthenticationTokenRequest()
    {
        PhotonApplicationId = PhotonNetwork.PhotonServerSettings.AppID
    }, AuthenticateWithPhoton, OnPlayFabError);
}

private void AuthenticateWithPhoton(GetPhotonAuthenticationTokenResult obj) {
    var customAuth = new AuthenticationValues { AuthType = CustomAuthenticationType.Custom };
        
    customAuth.AddAuthParameter("username", _playFabId );
    customAuth.AddAuthParameter("token", obj.PhotonCustomAuthenticationToken);
    PhotonNetwork.AuthValues = customAuth;
    PhotonNetwork.ConnectUsingSettings(_gameVersion);
}

public override void OnConnectedToMaster() {
    if (OnLoginSuccess != null)
    {
        OnLoginSuccess.Invoke(_result);
    }
}

Your code.

4 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

pmattei0 avatar image pmattei0 commented ·

I think I understood, can you tell me if I'm on the right way ?

private void OnLoginClicked()
}
_AuthService.Email = _Email.text;
_AuthService.Password = _Password.text;
_AuthService.Authenticate(Authtypes.EmailAndPassword);
} private void OnLoginSuccess(PlayFab.ClientModels.LoginResult result)
{
Debug.LogFormat("Logged In as: {0}", result.PlayFabId);
AuthenticateWithPlayFab();
} private void AuthenticateWithPlayFab()
{
PlayFabClientAPI.LoginWithEmailAddress(new LoginWithEmailAddressRequest()
{
TitleId = PlayFabSettings.TitleId,
Email = _Email.text,
Password = _Password.text,
InfoRequestParameters = InfoRequestParams
}, RequestPhotonToken, OnPlayFabError);
}

Thank you guys for all of the answers.

0 Likes 0 ·
Andrew Maksimov avatar image Andrew Maksimov pmattei0 commented ·

You are authorized with email/password to Photon and PlayFab.

While you need to first authorize with email/password to PlayFab, and get from him photonToken.
And then, with photonToken, to authorized in Photon


Earlier, I showed you the code that suits your situation. Try it.

0 Likes 0 ·
pmattei0 avatar image pmattei0 Andrew Maksimov commented ·

Yes of course that's what I did but I didnt put in the code.

Thank you and thank you @Brandan :]

0 Likes 0 ·
Show more comments
timothysrasmussen avatar image
timothysrasmussen answered

To anyone getting stuck with this. I used a lot of time to get this working. But this should really not be that hard to find or get a solution for so here you go. The login system is based on a course I followed from Zenva Academy, but I applied the needed system to receive photon tokens. The change of scene can be chosen for your own liking.

using System;
using System.Collections;
using System.Collections.Generic;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine;
using PlayFab;
using PlayFab.ClientModels;
using TMPro;
using UnityEngine.Events;
using UnityEngine.SceneManagement;

namespace Tim.Scripts.Login_System
{
    
    public class LogInRegister : MonoBehaviour
    {
        
        [HideInInspector]
        public string playFabId;
        private string _playFabPlayerIdCache;

        public TMP_InputField usernameInput;
        public TMP_InputField passwordInput;

        public TextMeshProUGUI displayText;

        public UnityEvent onLoggedIn;

        public static LogInRegister instance;

        public string LevelToLoad;
        
        private void Awake()
        {
            
            instance = this;
            
        }

        public void OnLoginButton()
        {
            Login();
        }
        
        public void OnRegisterButton()
        {
            Register();
        }

        private void Register()
        {
            //The Structure class for readying the API request. 

            RegisterPlayFabUserRequest registerRequest = new RegisterPlayFabUserRequest
            {
                Username = usernameInput.text,
                DisplayName = usernameInput.text,
                Password = passwordInput.text,
                RequireBothUsernameAndEmail = false
            };

            //The actual request. With tests testing if it was a success or not. 

            PlayFabClientAPI.RegisterPlayFabUser(registerRequest,
                result => { SetDisplayText("Registered a new account as: " + result.PlayFabId, Color.green); },
                error => SetDisplayText(error.ErrorMessage, Color.red)
            );
        } 
        
        /*
         * Step 1
         * We authenticate current PlayFab user normally.
         * In this case we use LoginWithCustomID API call for simplicity.
         * You can absolutely use any Login method you want.
         * We use PlayFabSettings.DeviceUniqueIdentifier as our custom ID.
         * We pass RequestPhotonToken as a callback to be our next step, if
         * authentication was successful.
         */
        private void Login()
        {
            LoginWithPlayFabRequest loginRequest = new LoginWithPlayFabRequest()
            {
                Username = usernameInput.text,
                Password = passwordInput.text
            };

            LogMessage("PlayFab authenticating using Custom ID...");
            
            PlayFabClientAPI.LoginWithPlayFab(loginRequest, 
                result =>
                {
                    SetDisplayText("Logged in as: " + result.PlayFabId, Color.green);
                    playFabId = result.PlayFabId;
                    SceneManager.LoadScene(LevelToLoad);
                    onLoggedIn?.Invoke();
                    RequestPhotonToken(result);
                },
                error =>
                {
                    SetDisplayText(error.ErrorMessage, Color.red);
                    OnPlayFabError(error);
                }
            );
            
        }

        /*
        * Step 2
        * We request Photon authentication token from PlayFab.
        * This is a crucial step, because Photon uses different authentication tokens
        * than PlayFab. Thus, you cannot directly use PlayFab SessionTicket and
        * you need to explicitly request a token. This API call requires you to
        * pass Photon App ID. App ID may be hard coded, but, in this example,
        * We are accessing it using convenient static field on PhotonNetwork class
        * We pass in AuthenticateWithPhoton as a callback to be our next step, if
        * we have acquired token successfully
        */
        private void RequestPhotonToken(LoginResult obj) {
            
            LogMessage("PlayFab authenticated. Requesting photon token...");
            //We can player PlayFabId. This will come in handy during next step
            _playFabPlayerIdCache = obj.PlayFabId;

            PlayFabClientAPI.GetPhotonAuthenticationToken(new GetPhotonAuthenticationTokenRequest()
            {
                PhotonApplicationId = PhotonNetwork.PhotonServerSettings.AppSettings.AppIdRealtime,
            }, AuthenticateWithPhoton, OnPlayFabError);
        }
        
        /*
         * Step 3
         * This is the final and the simplest step. We create new AuthenticationValues instance.
         * This class describes how to authenticate a players inside Photon environment.
         * https://doc.photonengine.com/en-us/realtime/current/reference/playfab
         */
        private void AuthenticateWithPhoton(GetPhotonAuthenticationTokenResult obj) {
            LogMessage("Photon token acquired: " + obj.PhotonCustomAuthenticationToken + "  Authentication complete.");

            //We set AuthType to custom, meaning we bring our own, PlayFab authentication procedure.
            var customAuth = new AuthenticationValues { AuthType = CustomAuthenticationType.Custom };
            //We add "username" parameter. Do not let it confuse you: PlayFab is expecting this parameter to contain player PlayFab ID (!) and not username.
            customAuth.AddAuthParameter("username", _playFabPlayerIdCache);    // expected by PlayFab custom auth service

            //We add "token" parameter. PlayFab expects it to contain Photon Authentication Token issues to your during previous step.
            customAuth.AddAuthParameter("token", obj.PhotonCustomAuthenticationToken);

            //We finally tell Photon to use this authentication parameters throughout the entire application.
            PhotonNetwork.AuthValues = customAuth;
        }

        void SetDisplayText(string text, Color color)
        {
            displayText.text = text;
            displayText.color = color;
        }

        private void OnPlayFabError(PlayFabError obj)
        {
            LogMessage(obj.GenerateErrorReport());
        }

        private void LogMessage(string message)
        {
            Debug.Log($"Playfab + Photon: {message}");
        }
        
    }

}
1 comment
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

timothysrasmussen avatar image timothysrasmussen commented ·
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using PlayFab;
using PlayFab.ClientModels;
using Tim.Scripts.Login_System;

public class PlayerInfo : MonoBehaviour
{
    [HideInInspector]
    public PlayerProfileModel profile;

    public static PlayerInfo instance;

    private void Awake()
    {
        instance = this;
    }

    public void OnLoggedIn()
    {
        GetPlayerProfileRequest getPlayerProfileRequest = new GetPlayerProfileRequest
        {
            PlayFabId = LogInRegister.instance.playFabId,
            ProfileConstraints =  new PlayerProfileViewConstraints
            {
                ShowDisplayName = true
            }
        };
        
        PlayFabClientAPI.GetPlayerProfile(getPlayerProfileRequest,
            result =>
            {
                profile = result.PlayerProfile;
                Debug.Log("Loaded in player: " + profile.DisplayName);
            },
            error =>
            {
                Debug.Log(error.ErrorMessage);
            }
        );
        
    }
}
0 Likes 0 ·
timothysrasmussen avatar image
timothysrasmussen answered

To anyone getting stuck with this. I used a lot of time to get this working. But this should really not be that hard to find or get a solution for so here you go. The login UI is based on a course I followed from Zenva Academy, so if you want a plug and play use that, but I applied the needed system to receive photon tokens from an existing account. The change of scene can be chosen for your own liking in Result => {}.

using System;
using System.Collections;
using System.Collections.Generic;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine;
using PlayFab;
using PlayFab.ClientModels;
using TMPro;
using UnityEngine.Events;
using UnityEngine.SceneManagement;

namespace Tim.Scripts.Login_System
{
    
    public class LogInRegister : MonoBehaviour
    {
        
        [HideInInspector]
        public string playFabId;
        private string _playFabPlayerIdCache;

        public TMP_InputField usernameInput;
        public TMP_InputField passwordInput;

        public TextMeshProUGUI displayText;

        public UnityEvent onLoggedIn;

        public static LogInRegister instance;

        public string LevelToLoad;
        
        private void Awake()
        {
            
            instance = this;
            
        }

        public void OnLoginButton()
        {
            Login();
        }
        
        public void OnRegisterButton()
        {
            Register();
        }

        private void Register()
        {
            //The Structure class for readying the API request. 

            RegisterPlayFabUserRequest registerRequest = new RegisterPlayFabUserRequest
            {
                Username = usernameInput.text,
                DisplayName = usernameInput.text,
                Password = passwordInput.text,
                RequireBothUsernameAndEmail = false
            };

            //The actual request. With tests testing if it was a success or not. 

            PlayFabClientAPI.RegisterPlayFabUser(registerRequest,
                result => { SetDisplayText("Registered a new account as: " + result.PlayFabId, Color.green); },
                error => SetDisplayText(error.ErrorMessage, Color.red)
            );
        } 
        
        /*
         * Step 1
         * We authenticate current PlayFab user normally.
         * In this case we use LoginWithCustomID API call for simplicity.
         * You can absolutely use any Login method you want.
         * We use PlayFabSettings.DeviceUniqueIdentifier as our custom ID.
         * We pass RequestPhotonToken as a callback to be our next step, if
         * authentication was successful.
         */
        private void Login()
        {
            LoginWithPlayFabRequest loginRequest = new LoginWithPlayFabRequest()
            {
                Username = usernameInput.text,
                Password = passwordInput.text
            };

            LogMessage("PlayFab authenticating using Custom ID...");
            
            PlayFabClientAPI.LoginWithPlayFab(loginRequest, 
                result =>
                {
                    SetDisplayText("Logged in as: " + result.PlayFabId, Color.green);
                    playFabId = result.PlayFabId;
                    SceneManager.LoadScene(LevelToLoad);
                    onLoggedIn?.Invoke();
                    RequestPhotonToken(result);
                },
                error =>
                {
                    SetDisplayText(error.ErrorMessage, Color.red);
                    OnPlayFabError(error);
                }
            );
            
        }

        /*
        * Step 2
        * We request Photon authentication token from PlayFab.
        * This is a crucial step, because Photon uses different authentication tokens
        * than PlayFab. Thus, you cannot directly use PlayFab SessionTicket and
        * you need to explicitly request a token. This API call requires you to
        * pass Photon App ID. App ID may be hard coded, but, in this example,
        * We are accessing it using convenient static field on PhotonNetwork class
        * We pass in AuthenticateWithPhoton as a callback to be our next step, if
        * we have acquired token successfully
        */
        private void RequestPhotonToken(LoginResult obj) {
            
            LogMessage("PlayFab authenticated. Requesting photon token...");
            //We can player PlayFabId. This will come in handy during next step
            _playFabPlayerIdCache = obj.PlayFabId;

            PlayFabClientAPI.GetPhotonAuthenticationToken(new GetPhotonAuthenticationTokenRequest()
            {
                PhotonApplicationId = PhotonNetwork.PhotonServerSettings.AppSettings.AppIdRealtime,
            }, AuthenticateWithPhoton, OnPlayFabError);
        }
        
        /*
         * Step 3
         * This is the final and the simplest step. We create new AuthenticationValues instance.
         * This class describes how to authenticate a players inside Photon environment.
         * https://doc.photonengine.com/en-us/realtime/current/reference/playfab
         */
        private void AuthenticateWithPhoton(GetPhotonAuthenticationTokenResult obj) {
            LogMessage("Photon token acquired: " + obj.PhotonCustomAuthenticationToken + "  Authentication complete.");

            //We set AuthType to custom, meaning we bring our own, PlayFab authentication procedure.
            var customAuth = new AuthenticationValues { AuthType = CustomAuthenticationType.Custom };
            //We add "username" parameter. Do not let it confuse you: PlayFab is expecting this parameter to contain player PlayFab ID (!) and not username.
            customAuth.AddAuthParameter("username", _playFabPlayerIdCache);    // expected by PlayFab custom auth service

            //We add "token" parameter. PlayFab expects it to contain Photon Authentication Token issues to your during previous step.
            customAuth.AddAuthParameter("token", obj.PhotonCustomAuthenticationToken);

            //We finally tell Photon to use this authentication parameters throughout the entire application.
            PhotonNetwork.AuthValues = customAuth;
        }

        void SetDisplayText(string text, Color color)
        {
            displayText.text = text;
            displayText.color = color;
        }

        private void OnPlayFabError(PlayFabError obj)
        {
            LogMessage(obj.GenerateErrorReport());
        }

        private void LogMessage(string message)
        {
            Debug.Log($"Playfab + Photon: {message}");
        }
        
    }

}
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.