Skip to main contentArrow Right
Banner labeled "Developer Guide" showing the Descope logo, a plus sign, and the Unreal Engine logo in a row. The headline below reads "Auth & MFA for Unreal."

Table of Contents

Summarize with AI

Don't have the time to read the entire post? Our human writers will be sad, but we understand. Summarize the post with your preferred LLM here instead.

This tutorial was written by Thinus Swart, a jack-of-all-trades software developer and cybersecurity specialist. Connect with him on X to see more of his work!


Unreal Engine (UE) is widely known for its ability to create high-fidelity, immersive gaming experiences. Some of the most popular games today have been created with this more-than-capable engine, including games like Fortnite and Rocket League. Its visual scripting, robust C++ foundation, and cross-platform support make it a top choice for game development, from indie developers to AAA studios.

But building a great game isn't just about graphics or gameplay. When you start adding features like multiplayer, player profiles, cross-device syncing, and monetization, secure, seamless authentication becomes nonnegotiable. Making sure that only verified users can access key features or data is essential for both user safety and developer control. Descope is a flexible identity platform that allows developers to embed authentication and multifactor authentication (MFA) flows into their apps with minimal friction. With support for magic links, OTPs, and social logins, Descope makes it easier to build secure login flows that will feel like a natural part of your game.

In this tutorial, you'll learn how to add authentication and MFA to a UE game using Descope. Along the way, we'll cover the different approaches game developers typically consider when implementing authentication, walk through a real-world integration using Descope's OpenID Connect (OIDC) support, and demonstrate how to display user details and handle logouts in game.

Approaches to game authentication

Game developers generally have three options when it comes to implementing authentication. The first is to rely on a storefront's built-in identity system, such as Epic Games or Steam. These systems offer smooth onboarding within their ecosystems and can integrate well with features like matchmaking, achievements, and leaderboards. However, they also come with some trade-offs: limited customization, dependency on a single platform, and constraints around marketing access or monetization outside the store.

The second option is to purchase an authentication plugin from Fab, Epic Games' new unified marketplace for digital assets. While this can help to kickstart development, the quality and reliability of these plugins can vary. Many still require manual setup and ongoing maintenance or lack support for features like MFA. For teams working on production-grade titles, these limitations often become apparent late in development, right when integration changes are most costly.

Finally, you could opt to build your own authentication system from the ground up. This offers the most control but comes at a high cost in terms of engineering time, ongoing security maintenance, and compliance.

However, a custom authentication system does bring some advantages that the other options might not be able to offer:

  • Maintain consistent player identity across storefronts and devices

  • Implement subscriptions or microtransactions outside of the game platform

  • Get better user analytics and tracking

  • Reduce reliance on third-party platforms

  • Strengthen overall security with flexible MFA options

Descope helps you to bridge this gap by offering a secure, developer-first approach to authentication and MFA. This approach works across platforms, can be integrated into your game's UX, and doesn't require you to become an authentication expert.

In the following sections, you'll learn how to implement a secure, user-friendly authentication flow in Unreal Engine using Descope: from setting up your Descope project to integrating it with your UE game, configuring authentication flows, and adding multifactor authentication. By the end, you'll have a working login system with MFA, profile fetching, and logout functionality ready to plug into your own game.

Prerequisites

Before you get started, you're going to need a few tools and services downloaded, installed, and ready to go:

Visual Studio: specific modifications for Unreal Engine

Visual Studio's installer allows you to set up the IDE for different workloads or project types. If you've previously only used VS for Python projects, you'll have it set up in a particular way that won't work with UE, which requires a few specific components for it to fully work.

Launch the VS installer and click Modify to modify your installation of Visual Studio:

Visual Studio Installer window with two tabs, "Installed" (selected) and "Available." A banner reads "All installations are up to date." One product is listed: "Visual Studio Community 2022," version "17.14.9 (July 2025)," described as "Powerful IDE, free for students, open-source contributors, and individuals," with a "Release notes" link. To its right are three buttons: "Modify" (highlighted), "Launch," and a "More" drop-down.
Fig: Modify VS installation

Under the Workloads tab, in the Desktop & Mobile section, you need to make sure that these three components are selected:

  • .NET desktop development

  • Desktop development with C++

  • WinUI application development

Visual Studio Installer window titled "Modifying, Visual Studio Community 2022, 17.14.9 (July 2025)," with four tabs: "Workloads" (selected), "Individual components," "Language packs," and "Installation locations." The "Desktop & Mobile (5)" section lists five workloads with checkboxes. Three are selected: ".NET desktop development" ("Build WPF, Windows Forms, and console applications using C#, Visual Basic, and F# with .NET and .NET Frame..."), "Desktop development with C++" ("Build modern C++ apps for Windows using tools of your choice, including MSVC, Clang, CMake, or MSBuild."), and "WinUI application development" ("Build applications for the Windows platform using WinUI with C# or optionally C++."). Two are not selected: ".NET Multi-platform App UI development" ("Build Android, iOS, Windows, and Mac apps from a single codebase using C# with .NET MAUI.") and "Mobile development with C++" ("Build cross-platform applications for iOS, Android or Windows using C++.").
Fig: Selected Desktop & Mobile components

Still under Workloads, in the Gaming section, make sure that Game development with C++ is selected:

Visual Studio Installer window titled "Modifying, Visual Studio Community 2022, 17.14.9 (July 2025)," with four tabs: "Workloads" (selected), "Individual components," "Language packs," and "Installation locations." The "Gaming (2)" section lists two workloads with checkboxes. "Game development with C++" is selected, with the description "Use the full power of C++ to build professional games powered by DirectX, Unreal, or Cocos2d." "Game development with Unity" is not selected, with the description "Create 2D and 3D games with Unity, a powerful cross-platform development environment."
Fig: Selected gaming components

Once you've downloaded and installed all of the components, your Visual Studio environment is ready to go.

Note: If, for whatever reason, things don't seem to be working, or the installed version of UE is starting up with errors, consult the help pages on Epic Games' website to troubleshoot these errors.

Setting up Descope

Once you've set up your Descope account, you can start designing your authentication workflow.

First, log in to your Descope console via this link.

Navigate to Flows and then select Start from template.

Descope Console for the project "unreal-auth-demo" showing the Flows page. The left navigation lists Home, Getting Started, a Build section with Authentication Methods, Flows, Widgets, Styles, Localization, Authorization, and Connectors, and a Connect section with Federated Apps and Inbound Apps. The Flows item is outlined in red. The main area is titled "Flows" with the text "Flows are a no-code tool to create user journeys" and a "Learn More" link. Below are two buttons, "Start from template" (outlined in red) and "Start from scratch." Under "Your Flows" is a Search field and a table with ID and Name columns listing step-up (Step Up), sign-up-or-in (Sign Up or In), and sign-up (Sign Up).
Fig: Start from template

The flow template library allows you to filter by use cases and methods. Select Enchanted Link and Social (OAuth/OIDC) for your methods, and MFA for your use case. Select the Sign up or in version of the templates that matched your selected filters.

Descope flow template library filtered to Enchanted Link, Social (OAuth / OIDC), and MFA, showing three template cards. The first card is partly cropped. The second card reads "Sign up - enchanted link or social with OTP MFA. Sign up using enchanted link or social login. Registration information includes full name and phone (OTP verification)." with the tags MFA and Sign Up. The third card, outlined in red, reads "Sign up or in - enchanted link or social with OTP MFA" with the tags MFA, Sign Up, and Sign In. It is hovered, so it is dimmed and shows two buttons, "Use Template" (outlined in red) and "Preview."
Fig: Select template

You can rename your flow and give it a unique ID if you want. Once you're happy, click Create.

Once your new flow has been created, you can customize the flow to behave the way you want it. In this tutorial, we'll remove the social login buttons for Google and Apple, and add a Discord button instead.

Hover over the Welcome Screen element on the flow and select Edit.

Descope Flows editor canvas showing a START node connected by an arrow to a selected step named "Welcome Screen." The step contains a "Continue" output and a "Socials" group with "Continue with Google" and "Continue with Apple," each with a connector leading off to the right. A toolbar of four icons appears above the step, and the first one, a pencil edit icon, is outlined in red.
Fig: Edit Welcome Screen

Delete the Google and Apple social buttons, and drag in a Discord button from the sidebar.

Descope screen editor with a sidebar of social login buttons on the left: Sign in with Github, Sign in with Apple, Sign in with Discord (outlined in red), Sign in with Gitlab, Sign in with WhatsApp, Sign in with Biometrics, Sign in with Passkey, and Sign in with SSO. On the right is the screen preview titled "Welcome!" with an "Email address *" field, the text "By signing in, I agree to the Company's Privacy Statement and Terms of Service," a "Sign In" button, and an "OR" divider. Below the divider, outlined in red, a "Sign in with Discord" button is being dragged into an empty drop area above the text "Sample Error Message."
Fig: Drag Discord button

Remember to save your flow once you're happy with the changes you've made.

Your custom authentication flow has now been set up and is ready to be used in your Unreal Engine project.

Creating your Unreal Engine game

With the prerequisites in place, the first step is to set up the new Unreal Engine project that you will add authentication to. Start off by opening Unreal Engine either from the Epic Games Launcher or from the installed location.

Then, create a blank game project and give it a name. This tutorial will use UNREAL_AUTH_DEMO as the project name. Make sure to select C++ as your project type.

Unreal Project Browser window. The left column lists the categories Recent Projects, Games (selected), Film / Video & Live Events, Architecture, and Automotive. The middle shows the templates Blank (selected), First Person, Third Person, Top Down, Handheld AR, and Virtual Reality. The right panel previews the Blank template with the description "A clean empty project with no code." Under Project Defaults, the C++ option is selected instead of Blueprint and is outlined in red, Target Platform is set to Desktop, and Quality Preset is set to Maximum. At the bottom, Project Location ends in "\Unreal Projects," the Project Name field contains "unreal_auth_demo" and is outlined in red, and there are Create and Cancel buttons.
Fig: Blank game project

If everything went well, you'll see an empty game world showing up in the editor:

Unreal Engine editor with a level tab named "Untitled" open. The menu bar shows File, Edit, Window, Tools, Build, Select, Actor, and Help, and the toolbar shows a Selection Mode dropdown, play controls, and a Platforms dropdown. The viewport shows an empty game world: a flat checkered floor stretching to low hills on the horizon under a blue sky with clouds, with a player start marker and one other actor icon on the ground.
Fig: Empty game world

If it didn't go well and your editor refused to start, now would be the time to consult the Setting Up Visual Studio page to see if you're missing any components that need to be installed first.

Otherwise, you're ready to create your menu component that will allow your users to sign up or in.

Create your main menu

In the UE editor, at the bottom, expand your Content Drawer. Create a UI folder under Content to keep things organized.

Add a User Interface widget blueprint:

Unreal Engine Content Drawer for the unreal_auth_demo project. The Content Drawer tab at the bottom is outlined in red. In the folder tree, All contains Content, which contains a selected UI folder outlined in red. The Add button, also outlined in red, has opened a menu listing Audio, Blueprint, Cinematics, Editor Utilities, Foliage, FX, Gameplay, Input, Interchange, Material, Media, Miscellaneous, Paper2D, Physics, Texture, Tool Presets, User Interface, and World. User Interface is highlighted and outlined in red, and its submenu lists Font, Slate Brush, Slate Vector Art Data, Slate Widget Style, Widget Blueprint (highlighted and outlined in red), and Widget Preview. The folder shows 0 items.
Fig: Add User Interface widget blueprint

Click User Widget as the parent class when prompted:

Unreal Engine dialog titled "Pick Parent Class for New Widget Blueprint." Under the Common section, the "User Widget" option is outlined in red, with the description "A widget that enables UI extensibility through WidgetBlueprint." Under All Classes is a Search field and a class tree: Visual, Widget, UserWidget, then AudioButtonMatrix, AudioButtonMatrixColumn, AudioButtonToggle, AudioFader, AudioKnobLarge, AudioKnobSmall, AudioTextBox, and EditorUtilityWidget. The footer shows "17 items" and a Cancel button.
Fig: User Widget Parent class

Name your widget something practical like LoginMenu:

Unreal Engine Content Drawer for the unreal_auth_demo project with the UI folder selected under All, Content. The folder contains one asset, a Widget Blueprint named "LoginMenu," marked with an asterisk to show unsaved changes. The item count reads "1 item." The bottom bar shows the Content Drawer, Output Log, and Cmd tabs and an "Enter Console Command" field.
Fig: Name your widget

Once you're in the designer, you're going to need the following on your menu blueprint:

  • Two buttons, one named SigninButton and another named SignoutButton.

  • Both buttons need to have the Is Variable option enabled.

  • A textbox named TextResult, also with Is Variable enabled.

Once your menu has been created, you should have a hierarchy that looks similar to this:

Unreal Engine widget designer Hierarchy panel, next to a Bind Widgets tab, with a "Search Widgets" field. The tree shows [LoginMenu] containing [Canvas Panel], which contains [Vertical Box]. The Vertical Box holds three items in order: SigninButton with a child [Text] "Sign In," SignoutButton with a child [Text] "Sign Out," and [TextResult] with an empty string. Each row has lock and visibility icons.
Fig: Final hierarchy

And while your menu might look slightly different, it should look similar to this:

Unreal Engine widget designer canvas showing the login menu layout. Inside a dashed rectangular outline are three stacked elements, each outlined in green: a gray button labeled "Sign In," a gray button labeled "Sign Out," and an empty text block below them.
Fig: Final designer area

This menu is now ready to be displayed in your UE level.

Display your menu

Now that you have a login menu, you'll want it to appear when your game starts.

In the UE editor:

  • Create a new empty level (for example, you can name it MainMenuLevel).

  • Open the level blueprint.

On Begin Play, add a Create Widget node, select your LoginMenu widget, then connect it to an Add to Viewport node.

Unreal Engine level blueprint graph with a node titled "Create Login Menu Widget." The node has a Class input set to "Login Menu," an "Owning Player" input, and a "Return Value" output pin that is outlined in red. A wire dragged from Return Value opens a context menu titled "Actions taking a(n) Login Menu Object Reference" with "add to" typed in the search box. The results list User Interface, then Viewport, with the functions "Add to Player Screen" and "Add to Viewport." "Add to Viewport" is outlined in red. Below it, the Utilities and Operators categories list "Add."
Fig: Add to Viewport

Save your level blueprint, exit the blueprint editor, and click Play from the level editor to see your new menu inside the level:

Unreal Engine level editor in play mode. The green Play button in the toolbar is outlined in red. In the black game viewport, a red outline surrounds the login menu, which has two gray buttons stacked vertically: "Sign In" on top and "Sign Out" below.
Fig: Menu appears in level

Create your custom login widget class

Next, you'll add some simple C++ logic to connect to the menu.

Create a new C++ class (UserWidget parent) and name it LoginUIWidget.

Unreal Engine "Add C++ Class" dialog on the step "Name your new user widget." The instructions read: "Enter a name for your new class. Class names may only contain alphanumeric characters, and may not contain a space. When you click the 'Create' button below, a header (.h) file and a source (.cpp) file will be made using this name." Class Type is set to Public (outlined in red), with Private as the other option. The Name field contains "LoginUIWidget" (outlined in red), and the module dropdown shows "unreal_auth_demo (Runtime)." Path: C:/Users/thinu/OneDrive/Documents/Unreal Projects/unreal_auth_demo/Source/unreal_auth_demo/. Header File: C:/Users/thinu/OneDrive/Documents/Unreal Projects/unreal_auth_demo/Source/unreal_auth_demo/Public/LoginUIWidget.h. Source File: C:/Users/thinu/OneDrive/Documents/Unreal Projects/unreal_auth_demo/Source/unreal_auth_demo/Private/LoginUIWidget.cpp. Buttons at the bottom are Back, Create Class (outlined in red), and Cancel.
Fig: LoginUIWidget

Wire up basic button click events to confirm your UI is responding.

Update LoginUIWidget.h to declare the buttons, text block, and click handlers:

#pragma once

#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "LoginUIWidget.generated.h"

UCLASS()
class UNREAL_AUTH_DEMO_API ULoginUIWidget : public UUserWidget
{
    GENERATED_BODY()

    public:
        virtual void NativeConstruct() override;

        UFUNCTION()
        void OnSigninClicked();

        UFUNCTION()
        void OnSignoutClicked();

    protected:
        UPROPERTY(meta = (BindWidget))
        class UButton* SigninButton;

        UPROPERTY(meta = (BindWidget))
        class UButton* SignoutButton;

        UPROPERTY(meta = (BindWidget))
        class UTextBlock* TextResult;
};

Note the following:

  • Replace UNREAL_AUTH_DEMO_API with your actual project name and API.

  • Ensure the UButton and UTextBlock names match your blueprint widget variables.

Then update LoginUIWidget.cpp to register the button click handlers:

#include "LoginUIWidget.h"
#include "Components/Button.h"
#include "Components/TextBlock.h"

void ULoginUIWidget::NativeConstruct()
{
    Super::NativeConstruct();

    if (SigninButton)
        SigninButton->OnClicked.AddDynamic(this, &ULoginUIWidget::OnSigninClicked);

    if (SignoutButton)
        SignoutButton->OnClicked.AddDynamic(this, &ULoginUIWidget::OnSignoutClicked);
}

void ULoginUIWidget::OnSigninClicked()
{
    UE_LOG(LogTemp, Log, TEXT("Sign in button pressed!"));
    // login logic here
}

void ULoginUIWidget::OnSignoutClicked()
{
    UE_LOG(LogTemp, Log, TEXT("Sign out button pressed!"));
    // logout logic here
}

This test code does two things:

  • Hooks up the Sign In and Sign Out buttons

  • Logs a message to the UE output log when either button is pressed

Save these two files. Now, you'll need to reparent your existing login menu blueprint to use this new class's logic.

Reparent your login menu blueprint

Open up the LoginMenu blueprint from the content drawer. Then, select File > Reparent Blueprint. You'll be able to search for LoginUIWidget (the new class you just created) and then select it. This will reparent your blueprint's logic to the custom from earlier.

Note: At this point, you might run into an annoying bug that some people have with UE5 and VS 2022. If you do not see the class listed when you search for it, you'll need to do the following steps:

  • Close the Unreal Engine editor.

  • In Visual Studio, select Build > Build unreal_auth_demo or the project name you chose.

  • Wait for the build process to finish, and open the Unreal editor again.

Sometimes, you can use the build process without having to close the editor, and there are ways to fix it, but that's beyond the scope of this tutorial. In any case, if you've followed the steps, you should be able to reparent the blueprint to your custom class.

Save your blueprint once you've finished the reparent process.

Change your default level and test the button

Back in the editor, go to Edit > Project Settings, and then click Maps & Modes on the left sidebar menu. Change your Editor Startup Map and your Game Default Map to point to the MainMenuLevel you created.

Unreal Engine Project Settings window. In the left sidebar, under Project, the items are Description, Encryption, GameplayTags, Maps & Modes (selected and outlined in red), Movies, Packaging, Supported Platforms, and Target Hardware. Under Game, the items are Asset Manager, Asset Tools, Slate RHIRenderer Settings, Widget State Settings, and Zen Streaming. The main panel is titled "Project - Maps & Modes" with the description "Default maps, game modes and other map related settings" and the note "These settings are saved in DefaultEngine.ini, which is currently writable." Under Default Modes, Default GameMode is set to GameModeBase. Under Default Maps, Editor Startup Map and Game Default Map are both set to MainMenuLevel, and both dropdowns are outlined in red. Editor Template Map Overrides shows "0 Array element."
Fig: Change default map

Now, you can test your custom button code logic. Play the game using the same green play button from before, and click the Sign in button.

In your editor, you'll see a drawer called Output Log. Expand this drawer, scroll to the bottom, and see if your custom output message is there.

Unreal Engine game viewport above the Output Log drawer. In the viewport, the "Sign In" and "Sign Out" buttons are each outlined in red. The Output Log shows engine startup messages, including "LogLoad: Game class is 'GameModeBase'," "PIE: Server logged in," and "PIE: Play in editor total start time 0,165 seconds." The last two lines are outlined in red and read "LogTemp: Sign in button pressed!" and "LogTemp: Sign out button pressed!" Below the log are a Cmd dropdown and an "Enter Console Command" field.
Fig: Output Log

If you see the messages, that means your code is working.

Get some information from Descope

Before you can connect Unreal Engine to Descope, you need to gather some details about how the game will communicate with Descope during the login process. These details come from OAuth 2.0 and OpenID Connect (OIDC), which are the standards we'll use to handle authentication with Descope.

OAuth and OIDC

OAuth 2.0 is a protocol that lets an app (in this case, your game) request authorization for a user through a trusted provider like Descope. Instead of handling passwords directly, your game gets a temporary authorization code that can be exchanged for tokens.

OpenID Connect (OIDC) builds on OAuth 2.0 and adds identity information. That's how your game can get details like the player's username, email, or profile data.

In practice, this means your Unreal Engine project will:

  • Redirect the player to Descope's login page.

  • Descope will authenticate the user (e.g., via Discord login + MFA).

  • Descope will send your game back an authorization code.

  • Your game exchanges that code for tokens that prove the user is authenticated.

To make this work, your game needs some values from Descope's OIDC configuration.

Getting the OIDC Settings

In your Descope console:

  • Navigate to Federated Apps.

  • Click OIDC Default Application. (On the free tier, this is the only one available for editing.)

  • Scroll down to the SP Configuration section and note the following values:

    • Client ID: identifies your Unreal Engine app to Descope.

    • Authorization URL: the endpoint your game uses to start the login flow.

    • Token URL: the endpoint your game calls to exchange the authorization code for tokens.

    • Logout URL: the endpoint that clears the user's session when they sign out.

These values form the backbone of the login flow. In the next step, you'll wire them into the Unreal Engine code so the game can start and complete the OAuth process.

While you're on this screen, update the Flow Hosting URL to point to the custom flow you created earlier:

Descope Console IdP Configuration panel, Descope Configuration section. The Flow Hosting URL field is in focus and shows a URL ending in "/login/P3" followed by a blurred project ID, then a query string that is outlined in red and reads "sign-up-or-in-enchanted-link-or-social-with-otp-mf" before it is cut off by the field edge. Below it, the Issuer field reads "https://api.descope.com/P3" followed by a blurred project ID, and the Discovery URL field reads "https://api.descope.com/P3" followed by a blurred project ID and "/.well-known/openid-configu," also cut off. Each of these two fields has a copy icon. Supported Claims lists iss, aud, iat, exp, sub, name, email, email_verified, phone_number, phone_number_verified, picture, family_name, and given_name. A Force Authentication checkbox is unchecked.
Fig: Custom Flow Hosting URL

Modify your custom class

Next, let's update LoginUIWidget.h to declare the functions, variables, and UI bindings that power the authentication flow:

#pragma once

#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "LoginUIWidget.generated.h"

/**
 * 
 */
UCLASS()
class UNREAL_AUTH_DEMO_API ULoginUIWidget : public UUserWidget
{

    GENERATED_BODY()

    public:
        virtual void NativeConstruct() override;

        UFUNCTION()
            void OnSigninClicked();

        UFUNCTION()
            void OnSignoutClicked();

        UFUNCTION()
            void SetLoginState(bool bNewLoginState);
        
        UFUNCTION()
            void UpdateUI();

    protected:
        UPROPERTY(meta = (BindWidget))
        class UButton* SigninButton;

        UPROPERTY(meta = (BindWidget))
        class UButton* SignoutButton;

        UPROPERTY(meta = (BindWidget))
        class UTextBlock* TextResult;

        // Login state
        UPROPERTY(BlueprintReadOnly, Category = "Login")
        bool bIsLoggedIn = false;

        // Descope OIDC Parameters
        FString ClientId;
        FString RedirectUri;
        FString RedirectLogoutUri;

        // Descope endpoint URLs
        FString AuthUrl;
        FString TokenUrl;
        FString LogoutUrl;
        FString UserInfoUrl;

        FString CapturedAuthCode;

        // PKCE values
        FString CodeVerifier;
        FString CodeChallenge;
        FString State;

        // Tokens
        FString IdToken;
        FString AccessToken;
        FString RefreshToken;

        void GeneratePKCEParameters();
        void StartOAuthLogin();
        void ListenForAuthCodeInBackground();
        void PerformSignout();
        void RevokeTokens();
        void ClearSessionData();

        // Fetching user data variables and functions
        FString UserEmail;
        FString UserName;

        UFUNCTION()
            void FetchUserProfile(const FString& Token);

        UFUNCTION()
            void ExchangeAuthCodeForTokens(const FString& Code);

};

At a high level, this header sets up:

  • UI hooks: SigninButton, SignoutButton, TextResult

  • Authentication state: bIsLoggedIn, tokens, and PKCE parameters

  • Core functions: StartOAuthLogin, ExchangeAuthCodeForTokens, FetchUserProfile, and PerformSignout

  • Networking: a socket listener (ListenForAuthCodeInBackground) to receive the redirect from Descope

With the header file in place, you can now implement the functionality in LoginUIWidget.cpp. This is where the actual behavior for our authentication flow lives—handling button clicks, generating PKCE parameters, launching the OAuth login, listening for the redirect from Descope, exchanging the authorization code for tokens, and finally fetching the user's profile information to display in the game.

The next code snippet is large, so it's recommended to copy the code directly from the Github repo, here. Just remember to update the following variables with the values you retrieved from Descope earlier:

  • ClientId

  • RedirectUri

  • RedirectLogoutUri

  • AuthUrl

  • TokenUrl

  • LogoutUrl

  • UserInfoUrl

Here are the most important parts of the .cpp:

  • PKCE support (GeneratePKCEParameters) for secure OAuth logins

  • Browser-based login (StartOAuthLogin) using the system browser

  • Local redirect listener (ListenForAuthCodeInBackground) to capture the authorization code and exchange it for tokens

  • Profile fetching (FetchUserProfile) to display the user's email and username

  • Thread safety and timeouts—runs the socket in a background thread, logs any errors to the UE output log

Finally, because this project uses new features like network sockets and HTTP calls, you'll need to enable the corresponding Unreal Engine modules in your project's build configuration. Open your project's build file (ProjectName.Build.cs) and add the required dependencies, as shown below:

using UnrealBuildTool;

public class unreal_auth_demo : ModuleRules
{
    public unreal_auth_demo(ReadOnlyTargetRules Target) : base(Target)
    {
        PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;

        // PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "EnhancedInput" });
        PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "Networking", "HTTP", "Json", "JsonUtilities", "Sockets" });

        PrivateDependencyModuleNames.AddRange(new string[] {  });

        // Uncomment if you are using Slate UI
        // PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });
        
        // Uncomment if you are using online features
        // PrivateDependencyModuleNames.Add("OnlineSubsystem");

        // To include OnlineSubsystemSteam, add it to the plugins section in your uproject file with the Enabled attribute set to true
    }
}

Build your code again using Build -> Build unreal_auth_demo. Once it's finished building, you can open up the Unreal editor again.

Testing it all

Once your editor is open, run the game using the green play button again.

Game login menu on a black background showing a single gray "Sign In" button with the status text "Not logged in" below it. No Sign Out button is displayed.
Fig: Sign-in screen

Notice that your Sign Out button is not visible. This is because of the changes in the UpdateUI() method to show and hide the different buttons based on your logged-in state.

Click Sign In. A browser window will open with the following login UI:

Descope login screen in a browser, titled "Welcome!" It has a required "Email address" field, the text "By continuing, I agree to the Company's Privacy Statement and Terms of Service" with both document names as links, a blue "Continue" button, an "OR" divider, and an outlined "Sign in with Discord" button with the Discord logo.
Fig: Show Discord login

This is the right authentication flow that you set up earlier on Descope's flow designer. Click Sign in with Discord.

The first time you sign in, Descope will ask for some extra information about you and verify your identity using MFA.

Descope sign-up screen with the prompt "To complete your sign up, please provide the following information." A name field contains "Thinus Swart." Below it, a phone number field has the country code +27 selected and a blurred number, next to a blue "Verify" button.
Fig: Username and phone number

If you entered your number correctly, you should receive a verification code via SMS:

Descope verification screen reading "We've sent a message containing a 6-digit code to +27" followed by a blurred phone number, then "Enter it below." Six single-digit input boxes show 3, 4, 4, 8, and 9, with the sixth box still empty. Below are two links: "Send again" and "Use a different number."
Fig: Enter verification code

Once you've entered the code, your screen should look like this:

Descope sign-up screen after phone verification, with the prompt "To complete your sign up, please provide the following information." The name field contains "Thinus Swart," shown as selected text. The "Phone number:" row now shows a green check mark in place of the number input, and a blue "Submit" button appears below.
Fig: Verified

This process should only happen the first time you sign in with a new user. Click Submit to continue.

Discord will open up with the following dialog:

Discord authorization dialog showing the Descope logo beside a pixelated user avatar, with the heading "Descope wants to access your Discord account." Under "This will allow the developer of Descope to:" two items are checked, "Access your username, avatar, and banner" and "Access your email address," and one is crossed out, "Microbrew some local kombucha." Below, the dialog states "Once you authorize, you will be redirected outside of Discord to: https://api.descope.com," "The developer of Descope's privacy policy and terms of service apply to this application," "Active since Nov 17, 2022," and "This application cannot read your messages or send messages as you." At the bottom are Cancel and Authorize buttons, with Authorize outlined in red.
Fig: Discord login

Click Authorize and you should see the following:

Discord confirmation dialog with the Descope logo, the heading "Connect to Descope," the message "Return to your browser to finish setting up your connection," a Close button, and an X icon in the top-right corner.
Fig: Descope authorized

Descope will now call the configured callback URL (in your case, http://localhost:3000) to tell your server that the login was successful and to give you an authorization code:

Browser window at the address localhost:3000/callback?code= followed by a blurred authorization code. The page displays the bold message "Login Successful!"
Fig: Login successful

In the background, your code will use the ExchangeAuthCodeForTokens and FetchUserProfile methods to fetch proper authentication tokens and to retrieve user information. Once that's complete, it will update the UI in your game:

Unreal Engine game UI on a black background after login. A gray Sign Out button sits above the status line "Logged in Username:" followed by a blurred name, then "Email:" followed by a blurred email address.
Fig: Game UI updated

Notice now that the Sign In button has been replaced with a Sign Out button.

Try giving that button a click:

Unreal Engine game UI and output log after signing out. The game view shows a gray Sign In button above the message "Signed out successfully," which is outlined in red. Below, the log panel has a Search Log field and a Filters menu, and lists these LogTemp entries: "HTTP Response Code: 200," a "Response Body" line containing a long access_token value that runs off the right edge, "Tokens received successfully!," "Access Token: RECEIVED," "ID Token: RECEIVED," "Refresh Token: RECEIVED," "User Info:" followed by the user's name and email address, "Signout button clicked," "Starting signout process," "Revoking tokens server-side," "Clearing local session data," "Local session data cleared," "Signout completed," "Token revocation response: HTTP 200," and "Tokens successfully revoked server-side," which is outlined in red.
Fig: Sign Out clicked

You've now successfully integrated Descope as your auth provider for your Unreal Engine 5 game.

As mentioned before, all of the code used in this tutorial is available here.

Conclusion

Adding authentication and MFA to an Unreal Engine game doesn't necessarily mean writing your own identity system or locking yourself into a single storefront. With Descope, you can implement secure, flexible login flows, including social login and multifactor authentication, using modern standards like OIDC and PKCE.

In this tutorial, you built a working login system in Unreal Engine from the ground up. You integrated Descope with Discord for social login, captured the authorization code using a local socket, exchanged it for tokens, and fetched the authenticated user's profile to update your game's UI. You now have a foundation for cross-platform identity, security, and personalization inside your UE game.

Descope offers even more beyond what was covered here: drag-and-drop flow builders, passwordless authentication, risk-based access policies, and more. If you're building a connected game and want your auth system to scale with you, book a demo with Descope, or check out their documentation and explore how it can fit the identity strategy for your game or website.