简体   繁体   中英

How to get responded JWT in Unity Firebase Authentication?

as a newbie in Unity and C#, I am using Firebase email authentication in my project. I want to take an action with using responded JWT token. Here are my related codes:

    private IEnumerator Login(string _email, string _password)
    {
        //Call the Firebase auth signin function passing the email and password
        var LoginTask = auth.SignInWithEmailAndPasswordAsync(_email, _password);
        //Wait until the task completes
        yield return new WaitUntil(predicate: () => LoginTask.IsCompleted);

        
.
.
.

        else
        {
            //User is now logged in
            //Now get the result
            User = LoginTask.Result;
            Debug.LogFormat("User signed in successfully: {0} ({1})", User.DisplayName, User.Email);
            warningLoginText.text = "";
            confirmLoginText.text = "Logged In";
        }
    }

   

I think I need to access it from LoginTask. However, I don't know how to get JWT. I will use it API request operations. Thank you for your help.

I went through something similar and hope this helps:

In order to get the JWT token from the Firebase Authentication response in Unity, you can use the User object returned by the SignInWithEmailAndPasswordAsync() method and access the User.Token property.

JWT token:

private IEnumerator Login(string _email, string _password)
{
    //Call the Firebase auth signin function passing the email and password
    var LoginTask = auth.SignInWithEmailAndPasswordAsync(_email, _password);
    //Wait until the task completes
    yield return new WaitUntil(predicate: () => LoginTask.IsCompleted);

    if (LoginTask.IsFaulted)
    {
        //Handle error
        Debug.LogError("Error logging in user: " + LoginTask.Exception);
    }
    else
    {
        //User is now logged in
        //Now get the result
        User = LoginTask.Result;
        Debug.LogFormat("User signed in successfully: {0} ({1})", User.DisplayName, User.Email);
        warningLoginText.text = "";
        confirmLoginText.text = "Logged In";

        // Get the JWT token
        string jwt = User.Token;
        Debug.LogFormat("JWT token: {0}", jwt);
        // Do something with the JWT token, such as sending it to a server for verification
    }
}

It's worth noting that the token's lifetime is 1 hour, after which you will have to refresh it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM