Are you an LLM? Read llms.txt for a summary of the docs, or llms-full.txt for the full context.
Skip to content

Email and Password Authentication

Allow users to sign up and sign in with their email address and a password in your Unity game. For passwordless authentication using one-time codes, see Email OTP & SMS OTP.

Methods

SignUpWithEmailPassword

Creates a new user account with email and password.

Method Signature:
public async UniTask<AuthResponse> SignUpWithEmailPassword(string email, string password, string name = null)
Parameters:
  • string email - User's email address
  • string password - User's password
  • string name - Optional display name for the user
Returns:
  • UniTask<AuthResponse> - Authentication response containing user info and tokens
AuthResponse Structure:
public class AuthResponse
{
    public User User { get; set; }       // User profile information
    public string Token { get; set; }    // Access token for authentication
    public Session Session { get; set; } // Session information
}
 
public class User
{
    public string Id { get; set; }              // Unique user identifier
    public string Email { get; set; }           // User's email address
    public string Name { get; set; }            // User's display name
    public string Image { get; set; }           // URL to user's profile image
    public bool? EmailVerified { get; set; }    // Whether email is verified
    public string CreatedAt { get; set; }       // ISO timestamp when created
    public string UpdatedAt { get; set; }       // ISO timestamp when updated
    public bool? IsAnonymous { get; set; }      // Whether user is anonymous
    public string PhoneNumber { get; set; }     // User's phone number
    public bool? PhoneNumberVerified { get; set; } // Whether phone is verified
}
 
public class Session
{
    public string Id { get; set; }        // Session identifier
    public string Token { get; set; }     // Session token
    public string UserId { get; set; }    // User ID
    public string ExpiresAt { get; set; } // When session expires
    public string CreatedAt { get; set; } // When session was created
}
Example:
using System;
using UnityEngine;
using Cysharp.Threading.Tasks;
using Openfort.OpenfortSDK;
using Openfort.OpenfortSDK.Model;
 
public class EmailSignUp : MonoBehaviour
{
    private OpenfortSDK openfort;
    
    private async void Start()
    {
        openfort = await OpenfortSDK.Init(
            "YOUR_OPENFORT_PUBLISHABLE_KEY",
            "YOUR_SHIELD_PUBLISHABLE_KEY" // Optional
        );
    }
    
    public async UniTask<AuthResponse> CreateNewAccount(string email, string password, string displayName = null)
    {
        try
        {
            var response = await openfort.SignUpWithEmailPassword(email, password, displayName);
 
            Debug.Log(quot;User created successfully: {response.User.Id}");
            Debug.Log(quot;Email: {response.User.Email}");
            Debug.Log(quot;Email verified: {response.User.EmailVerified}");
 
            return response;
        }
        catch (OpenfortException e)
        {
            Debug.LogError(quot;Signup failed: {e.Message}, Type: {e.Type}");
            throw;
        }
    }
}

LogInWithEmailPassword

Authenticate an existing user with email and password.

Method Signature:
public async UniTask<AuthResponse> LogInWithEmailPassword(string email, string password)
Parameters:
  • string email - User's email address
  • string password - User's password
Returns:
  • UniTask<AuthResponse> - Authentication response containing user info and tokens
Example:
using System;
using UnityEngine;
using Cysharp.Threading.Tasks;
using Openfort.OpenfortSDK;
using Openfort.OpenfortSDK.Model;
 
public class EmailLogin : MonoBehaviour
{
    private OpenfortSDK openfort;
    
    private async void Start()
    {
        openfort = await OpenfortSDK.Init(
            "YOUR_OPENFORT_PUBLISHABLE_KEY",
            "YOUR_SHIELD_PUBLISHABLE_KEY"
        );
    }
    
    public async UniTask<AuthResponse> LoginUser(string email, string password)
    {
        try
        {
            var response = await openfort.LogInWithEmailPassword(email, password);
 
            Debug.Log(quot;Login successful: {response.User.Id}");
            Debug.Log(quot;Email: {response.User.Email}");
            Debug.Log(quot;Session expires at: {response.Session?.ExpiresAt}");
 
            return response;
        }
        catch (OpenfortException e)
        {
            Debug.LogError(quot;Login failed: {e.Message}, Type: {e.Type}");
            throw;
        }
    }
}

RequestEmailVerification

Send an email verification to the user.

Method Signature:
public async UniTask RequestEmailVerification(RequestEmailVerificationRequest request)
Parameters:
  • RequestEmailVerificationRequest request - Email verification request
Returns:
  • UniTask - Completes when verification email is sent
RequestEmailVerificationRequest Structure:
public class RequestEmailVerificationRequest
{
    public string Email { get; set; }
}
Example:
using System;
using UnityEngine;
using Cysharp.Threading.Tasks;
using Openfort.OpenfortSDK;
using Openfort.OpenfortSDK.Model;
 
public class EmailVerification : MonoBehaviour
{
    private OpenfortSDK openfort;
    
    private async void Start()
    {
        openfort = await OpenfortSDK.Init(
            "YOUR_OPENFORT_PUBLISHABLE_KEY",
            "YOUR_SHIELD_PUBLISHABLE_KEY"
        );
    }
    
    public async UniTask SendVerificationEmail(string email)
    {
        try
        {
            var request = new RequestEmailVerificationRequest
            {
                Email = email
            };
            
            await openfort.RequestEmailVerification(request);
            Debug.Log(quot;Verification email sent to {email}");
        }
        catch (Exception e)
        {
            Debug.LogError(quot;Failed to send verification email: {e.Message}");
            throw;
        }
    }
}

VerifyEmail

Verify the user's email using the verification code from the email.

Method Signature:
public async UniTask VerifyEmail(VerifyEmailRequest request)
Parameters:
  • VerifyEmailRequest request - Email verification request with email and code
Returns:
  • UniTask - Completes when email is verified successfully
VerifyEmailRequest Structure:
public class VerifyEmailRequest
{
    public string Email { get; set; }  // User's email address
    public string Code { get; set; }   // Verification code from email
}
Example:
using System;
using UnityEngine;
using Cysharp.Threading.Tasks;
using Openfort.OpenfortSDK;
using Openfort.OpenfortSDK.Model;
 
public class EmailVerifier : MonoBehaviour
{
    private OpenfortSDK openfort;
 
    private async void Start()
    {
        openfort = await OpenfortSDK.Init(
            "YOUR_OPENFORT_PUBLISHABLE_KEY",
            "YOUR_SHIELD_PUBLISHABLE_KEY"
        );
    }
 
    public async UniTask VerifyUserEmail(string email, string verificationCode)
    {
        try
        {
            var request = new VerifyEmailRequest
            {
                Email = email,
                Code = verificationCode
            };
 
            await openfort.VerifyEmail(request);
            Debug.Log(quot;Email {email} verified successfully");
        }
        catch (Exception e)
        {
            Debug.LogError(quot;Email verification failed: {e.Message}");
            throw;
        }
    }
}

Authentication response

Upon successful authentication, you'll receive a response containing:

{
  "user": {
    "id": "usr_cc9ed2b7-c5f5-4c43-8dca-c4b104ba1762",
    "email": "[email protected]",
    "name": "John Doe",
    "emailVerified": true,
    "createdAt": "2024-03-20T12:00:00Z",
    "updatedAt": "2024-03-20T12:00:00Z",
    "isAnonymous": false
  },
  "token": "eyJhbGci...",
  "session": {
    "id": "ses_...",
    "token": "eyJhbGci...",
    "userId": "usr_cc9ed2b7-c5f5-4c43-8dca-c4b104ba1762",
    "expiresAt": "2024-03-21T12:00:00Z",
    "createdAt": "2024-03-20T12:00:00Z"
  }
}

RequestResetPassword

Request a password reset email for the user.

Method Signature:
public async UniTask RequestResetPassword(ResetPasswordRequest request)
Parameters:
  • ResetPasswordRequest request - Password reset request containing email
Returns:
  • UniTask - Completes when reset email is sent
Example:
using System;
using UnityEngine;
using Cysharp.Threading.Tasks;
using Openfort.OpenfortSDK;
using Openfort.OpenfortSDK.Model;
 
public class PasswordResetRequest : MonoBehaviour
{
    private OpenfortSDK openfort;
    
    private async void Start()
    {
        openfort = await OpenfortSDK.Init(
            "YOUR_OPENFORT_PUBLISHABLE_KEY",
            "YOUR_SHIELD_PUBLISHABLE_KEY"
        );
    }
    
    public async UniTask RequestPasswordReset(string email)
    {
        try
        {
            var request = new ResetPasswordRequest
            {
                Email = email
            };
            
            await openfort.RequestResetPassword(request);
            Debug.Log(quot;Password reset email sent to {email}");
        }
        catch (Exception e)
        {
            Debug.LogError(quot;Failed to request password reset: {e.Message}");
            throw;
        }
    }
}

ResetPassword

Reset the user's password using the verification state from email.

Method Signature:
public async UniTask ResetPassword(ResetPasswordRequest request)
Parameters:
  • ResetPasswordRequest request - Complete reset request with email, password, and state
Returns:
  • UniTask - Completes when password is reset successfully
ResetPasswordRequest Structure:
public class ResetPasswordRequest
{
    public string Email { get; set; }
    public string Password { get; set; }  // New password
    public string State { get; set; }     // From verification email
}
Example:
using System;
using UnityEngine;
using Cysharp.Threading.Tasks;
using Openfort.OpenfortSDK;
using Openfort.OpenfortSDK.Model;
 
public class PasswordReset : MonoBehaviour
{
    private OpenfortSDK openfort;
 
    private async void Start()
    {
        openfort = await OpenfortSDK.Init(
            "YOUR_OPENFORT_PUBLISHABLE_KEY",
            "YOUR_SHIELD_PUBLISHABLE_KEY"
        );
    }
 
    public async UniTask ResetUserPassword(string email, string newPassword, string verificationState)
    {
        try
        {
            var request = new ResetPasswordRequest
            {
                Email = email,
                Password = newPassword,
                State = verificationState  // From the reset email link
            };
 
            await openfort.ResetPassword(request);
            Debug.Log(quot;Password reset successfully for {email}");
        }
        catch (Exception e)
        {
            Debug.LogError(quot;Password reset failed: {e.Message}");
            throw;
        }
    }
}

Logout

Log out the current user and clear stored credentials.

Method Signature:
public async UniTask Logout()
Parameters:
  • None
Returns:
  • UniTask - Completes when logout is finished
Example:
using System;
using UnityEngine;
using Cysharp.Threading.Tasks;
using Openfort.OpenfortSDK;
 
public class UserLogout : MonoBehaviour
{
    private OpenfortSDK openfort;
    
    private async void Start()
    {
        openfort = await OpenfortSDK.Init(
            "YOUR_OPENFORT_PUBLISHABLE_KEY",
            "YOUR_SHIELD_PUBLISHABLE_KEY"
        );
    }
    
    public async UniTask LogoutUser()
    {
        try
        {
            await openfort.Logout();
            Debug.Log("User logged out successfully");
            
            // Navigate to login screen or perform cleanup
        }
        catch (Exception e)
        {
            Debug.LogError(quot;Logout failed: {e.Message}");
        }
    }
}

UI integration example

Here's a basic example of how to integrate this with Unity UI:

using TMPro;
using UnityEngine.UI;
using Cysharp.Threading.Tasks;
 
public class AuthUIManager : MonoBehaviour
{
    [SerializeField] private TMP_InputField emailInput;
    [SerializeField] private TMP_InputField passwordInput;
    [SerializeField] private TMP_InputField nameInput; // Optional for signup
    [SerializeField] private Button signUpButton;
    [SerializeField] private Button loginButton;
    [SerializeField] private GameObject loadingIndicator;
    
    private OpenfortAuthManager authManager;
 
    private void Start()
    {
        authManager = GetComponent<OpenfortAuthManager>();
        
        signUpButton.onClick.AddListener(() => HandleSignUp().Forget());
        loginButton.onClick.AddListener(() => HandleLogin().Forget());
    }
 
    private async UniTaskVoid HandleSignUp()
    {
        SetUIEnabled(false);
        try
        {
            string name = string.IsNullOrEmpty(nameInput?.text) ? null : nameInput.text;
            await authManager.SignUpNewUser(emailInput.text, passwordInput.text, name);
            // Navigate to next scene or show success
        }
        catch (Exception e)
        {
            // Show error to user
            Debug.LogError(quot;Sign up failed: {e.Message}");
        }
        finally
        {
            SetUIEnabled(true);
        }
    }
 
    private async UniTaskVoid HandleLogin()
    {
        SetUIEnabled(false);
        try
        {
            var response = await authManager.LogInUser(emailInput.text, passwordInput.text);
            // Navigate to game scene
            Debug.Log(quot;Login successful for user: {response.User.Id}");
        }
        catch (Exception e)
        {
            // Show error to user
            Debug.LogError(quot;Login failed: {e.Message}");
        }
        finally
        {
            SetUIEnabled(true);
        }
    }
 
    private void SetUIEnabled(bool enabled)
    {
        signUpButton.interactable = enabled;
        loginButton.interactable = enabled;
        emailInput.interactable = enabled;
        passwordInput.interactable = enabled;
        if (loadingIndicator != null)
            loadingIndicator.SetActive(!enabled);
    }
}
Copyright © 2023-present Alamas Labs, Inc