docs.unity3d.com
  • Manual
  • Scripting API
  • Changelog
  • License

    • Identity
      • Installation
    • Get started
    • Best practice | Dependency injection
    • Integrate authentication in your scene
    • Get user information
    • Test with WebGL in a localhost
    • Sample | Integrate Identity in a Unity project

    Integrate authentication in your scene

    This section explains how to set up your scene to integrate an authentication layer to communicate with Digital Twin services.

    An authentication process should retrieve an access token that identifies your app user when calling Digital Twin services. Identity supports the following login flows to retrieve an access token:

    • Automated flow: A flow often recommended for automated tools, where the user can generate a personal access token (PAT) from the Digital Twin Portal and inject it into the app to avoid a UI.
    • Preauthenticated flow : A flow that can be used by web-hosted plaforms (Furioos, WebGL) where the host already has a valid access token. In that case, identity can skip the user login flow and directly use the host's access token.
    • User login flow: A standard flow where the user must fill a login form through a UI.

    Prerequisites

    • Follow the Installation instructions.
    • Follow the Get started instructions.
    • Follow the Best practices: dependency injection guide.

    Overview

    To integrate authentication in your scene, perform the following procedures:

    1. Instantiate a CompositeAuthenticator in PlatformServices
    2. Tie Identity's authentication engine with UI
    3. Leverage the access token to communicate with other Digital Twin services

    Instantiate a CompositeAuthenticator in PlatformServices

    To instantiate a CompositeAuthenticator in the PlatformServices class, see the following steps:

    1. Add the following references in the PlatformServices class:

      • A public reference to IInteractiveAuthenticator and IAccessTokenProvider
      • A private reference to UnityHttpClient and CompositeAuthenticator

           static UnityHttpClient s_HttpClient;
           static CompositeAuthenticator s_CompositeAuthenticator;
        
           public static IInteractiveAuthenticator InteractiveAuthenticator => s_CompositeAuthenticator;
           public static IAccessTokenProvider AccessTokenProvider => s_CompositeAuthenticator;
        
    2. Initialize the services in the InitializeAsync method. In the future, when adding more services, the s_CompositeAuthenticator.InitializeAsync call must happen at the end of the method, after all the other services have been built.

          public static async Task InitializeAsync()
          {
              var playerSettings = DigitalTwinsPlayerSettings.Instance;
              s_HttpClient = new UnityHttpClient();
              s_CompositeAuthenticator = new CompositeAuthenticator(s_HttpClient, playerSettings, playerSettings);
      
              await s_CompositeAuthenticator.InitializeAsync();
          }
      
    3. Shutdown the services in the Shutdown method.

          public static void Shutdown()
          {
              s_CompositeAuthenticator.Dispose();
              s_CompositeAuthenticator = null;
      
              s_HttpClient = null;
          }
      

    Tie Identity's authentication engine with UI

    Identity's authentication engine doesn't handle any UI, so you must create a login UI and link it to the authentication engine. The authentication engine automatically decides which authentication flow to use based on certain conditions (see Authentication flows). This means some parts of the UI must stay hidden, depending on the situation.

    1. Create Login and Logout buttons in your scene. These buttons are used if the authentication engine uses the user login flow. Creating buttons in the scene

    2. Create a LoginManager GameObject and attach a new LoginManager MonoBehaviour to it. This script links your UI with Identity's authentication engine.

    3. Update the LoginManager script so it references your buttons and an IInteractiveAuthenticator.

          public class LoginManager : MonoBehaviour
          {
              [SerializeField]
              Button m_LoginButton;
      
              [SerializeField]
              Button m_LogoutButton;
      
              IInteractiveAuthenticator m_Authenticator;
          }
      
    4. Update the Awake method to do the following:

      • Retrieve the IInteractiveAuthenticator from PlatformServices.
      • Subscribe to the AuthenticationStateChanged event.
      • Subscribe to the buttons' onClick events.
      • Call ApplyAuthenticationState to update the UI when the scene loads.

           void Awake()
           {
               m_Authenticator = PlatformServices.InteractiveAuthenticator;
               m_Authenticator.AuthenticationStateChanged += ApplyAuthenticationState;
        
               m_LoginButton.onClick.AddListener(new UnityEngine.Events.UnityAction(OnLoginButtonClick));
               m_LogoutButton.onClick.AddListener(new UnityEngine.Events.UnityAction(OnLogoutButtonClick));
        
               ApplyAuthenticationState(m_Authenticator.AuthenticationState);
           }
        
    5. Make sure the subscriptions are cleaned up in OnDestroy.

          void OnDestroy()
          {
              m_Authenticator.AuthenticationStateChanged -= ApplyAuthenticationState;
      
              m_LoginButton.onClick.RemoveAllListeners();
              m_LogoutButton.onClick.RemoveAllListeners();
          }
      
    6. Implement the ApplyAuthenticationState method to update your buttons based on the current authentication state. Make your buttons interactive in specific circumstances, otherwise you risk errors and exceptions. To determine if you should display your buttons, rely on the AuthenticationState and the Interactive property that determines whether the UI is relevant in the selected authentication flow.

          void ApplyAuthenticationState(AuthenticationState state)
          {
              switch (state)
              {
                  case AuthenticationState.LoggedOut:
                      m_LoginButton.interactable = m_Authenticator.Interactive;
                      m_LogoutButton.interactable = false;
                      break;
                  case AuthenticationState.LoggedIn:
                      m_LoginButton.interactable = false;
                      m_LogoutButton.interactable = m_Authenticator.Interactive;
                      break;
                  case AuthenticationState.AwaitingLogin:
                  case AuthenticationState.AwaitingLogout:
                      m_LoginButton.interactable = false;
                      m_LogoutButton.interactable = false;
                      break;
              }
          }
      
    7. Define the behaviors for your buttons by calling the appropriate methods.

    Note: Only the user login flow (when Interactive is set to true) requires these methods. If the flow isn't interactive, calling LoginAsync or LogoutAsync throws exceptions.

    ```csharp
        async void OnLoginButtonClick()
        {
            await m_Authenticator.LoginAsync();
        }
    
        async void OnLogoutButtonClick()
        {
            await m_Authenticator.LogoutAsync();
        }
    ```
    
    1. Test your scene to see how the buttons update along with the authentication state of the user.

    Leverage the access token to communicate with other Digital Twin services

    After you set up your login flow, communication with other Digital Twin services is possible. All Digital Twin services expect an instance of IAccessTokenProvider, which the PlatformServices provides.

    For an example of a service that expects an IAccessTokenProvider, refer to the Get user information guide.

    Authentication flows

    The CompositeAuthenticator contains logic to choose an authentication flow based on certain pre-conditions. This section lists the supported flows, their corresponding pre-conditions, and how to use them.

    Automated flow

    This flow is for automated workflows (for example, unit testing) and isn't interactive. This flow works through a PAT that you generate.

    Generate your personal access token

    To generate your PAT, see the following steps:

    1. Log into the Digital Twin portal.
    2. Go to the Identity swagger page.
    3. Use POST /api/personal-access-tokens > [Try it out] > Execute. The following is an example of the response:

      {
      "PersonalAccessToken": "PAT",
      "Uid": "uid",
      "Comment": "string",
      "CreationTicks": 637962807880335700
      }
      
    4. Save your PAT. You can't see it after this step.

    Note: The URLs must be slightly adapted if you want to generate an API token on a different cloud environment than production.

    Inject the personal access token in your app

    The CompositeAuthenticator tries to find a PAT in the following ways:

    • From a command line argument passed to the app.

          ./MyApp.exe -DT_PERSONAL_ACCESS_TOKEN [MyAccessToken]
      
    • From a DT_PERSONAL_ACCESS_TOKEN environment variable set before running the app.

    If the CompositeAuthenticator retrieves a PAT from one of the above sources, it automatically launches the automated authentication flow.

    Preauthenticated flow

    This non-interactive flow is for workflows where authentication happens before launching the app. For example, when using the Furioos system inside the Digital Twin dashboard and the user is already logged into the dashboard, so the existing access token passes to the nested Furioos app.

    Note: The CompositeAuthenticator supports only the Furioos flow and some additional code is needed to tie the authentication engine and the Furioos API together (refer to the Furioos sample for more information).

    User login flow

    This flow (OAuth 2.0 with PKCE) is the regular login flow where the user uses a login UI to provide their credentials and retrieve an access token. This flow is interactive (which means you expose the login and logout buttons) and used by CompositeAuthenticator by default if none of the pre-conditions listed above is detected.

    Back to top Generated by DocFX
    Copyright © 2023 Unity Technologies — Terms of use
    • Legal
    • Privacy Policy
    • Cookies
    • Do Not Sell or Share My Personal Information
    • Your Privacy Choices (Cookie Settings)
    "Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
    Generated by DocFX on 18 October 2023