Using OAuth in Hololens Apps

Using OAuth in Hololens Apps

Hello there. It’s been a couple months since I posted my last article. Now this is one of the interesting problems I came across and once I solved it, thought it is worth sharing. Using OAuth in your Hololens App using a third-party providers is what we are going to cover here. We’ll be using twitter as the OAuth provider in this case. As part of this we create a simple app which takes our twitter credential and asks to grant permissions to our app and log us in. Here we go:

Prerequisites (used for this article)

  • Visual Studio 2017
  • Unity 2017.3.0f3
  • Twitter Account

Create a Twitter App

The first step we need to do is to create a Twitter app since we are using Twitter as the OAuth provider.

  • Go to Twitter apps and create a new app. You can use the twitter account to sign in and create an app. Make sure that when you create the app you provide a valid url in the Callback URL section (any valid http url is fine. It doesn’t matter for the app). 
  • Once the app is created go to the Keys and Access Tokens tab for that app and copy the Consumer Key, Consumer Secret and the Callback Url for the app. We will need it later.

Create the Hololens App

  • Open Unity and create a new 3D application.
  • Go to Build settings of the application and change the Build Type as XAML (not D3D)
Build settings
Set Build Type as XAML
  • Now you can do here anything you want in this scene. Once you complete the login process you’ll be navigated to this scene.
  • Save the scene and add it to the “Scenes in Build”.
  • Build the application and create the Visual Studio Solution (Make sure to enable the Internet Client Capability for the app).

Create the Login page

  • Open the newly built Visual Studio solution for the app.
  • In the Solution Expplorer you’ll notice that there are two xaml files called App.xaml and MainPage.xaml. Right click on the project and select Add->New Item.
  • From the list select “Blank Page” and name it as Login.xaml. I should look like this
OAuth Login
Newly added OAuth Login page
  • Open the Login.xaml and create your login design. For brevity I am going to simply add one login button. That’s all.
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Button x:Name="LoginBtn" Height="65" Width="300" FontSize="32" Click="Login_Click" Margin="270,368,0,47">Login to Twitter</Button>
</Grid>
  • Open the Nuget package manager for the project and add the package “Microsoft.Toolkit.Uwp.Services”. This toolkit provides sign in facility to many OAuth providers like Microsoft, Twitter, Facebook, Google etc.
  • Open the Login.cs file of your login page and add the following code to the Login button tap function
    private async void Login_Click(object sender, RoutedEventArgs e)
        {
            TwitterOAuthTokens token = new TwitterOAuthTokens()
            {
                ConsumerKey = "<You twitter app consumer key>",
                ConsumerSecret = "<You twitter app consumer secret>",
                CallbackUri = "<your callback url e.g. http://unicodeexception.com>"
            };

            if (TwitterService.Instance.Initialize(token))
            {
                if (await TwitterService.Instance.LoginAsync())
                {

                }
            }
        }
  • Make sure to add “Microsoft.Toolkit.Uwp.Services.Twitter” namespace to your code. 
  • Now our Login code is ready but if you run the application now, you won’t see anything.
  • To set the Login.xaml as the startup page go ahead and open App.cs file under App.xaml. In the InitializeUnity function change the root navigation to Login type from MainPage.
OAuth Login Startup
Set Login as Startup page for your app.
  • Now we are ready. If you run you application you’ll see the Login page. Click on the Login button and it would load the Twitter sign-in page. Once you enter your credentials it’ll authenticate you and asks you to permissions to your twitter app. Once that is done it sets your tokens and you are good to go.

 

Are we Done with OAuth?

You must be thinking, “now wait, this is just a 2D application. How would I get to my Unity application after logging in? How do I use the access tokens?” and many other questions. Well 🙂 we are not done, not yet.

Final Stage

  • Go to the Login.cs and modify the Login button tap function to make it look like this
    private async void Login_Click(object sender, RoutedEventArgs e)
        {
            TwitterOAuthTokens token = new TwitterOAuthTokens()
            {
                ConsumerKey = "<Your Consumer Key>",
                ConsumerSecret = "<Your Consumer secret>",
                CallbackUri = "<Your callback url>"
            };

            if (TwitterService.Instance.Initialize(token))
            {
                if (await TwitterService.Instance.LoginAsync())
                {
                    //2d to 3d portal switching
                    var currentViewId = ApplicationView.GetForCurrentView().Id;
                    CoreApplicationView newView = CoreApplication.CreateNewView();
                    newView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        ApplicationView newAppView = ApplicationView.GetForCurrentView();
                        var frame = new Frame();
                        Window.Current.Content = frame;

                        frame.Navigate(typeof(MainPage));
                        Window.Current.Activate();

                        IAsyncAction action = ApplicationViewSwitcher.SwitchAsync(newAppView.Id, currentViewId, ApplicationViewSwitchingOptions.Default);

                    }).AsTask().Wait();
                }
            }
        }
  • Now you run your application again and you’ll see that after you log in, your app gets redirected automatically to your Unity scene. Here is the flow.

 

Login Home
Landing page

 

OAuth Sign in
OAuth Sign in

 

2D to 3D portal
2D to 3D portal

 

Twitter followers
Twitter followers list
  • So once you have logged in, your token would be set. This you can share with to your Unity code using a UWP class library  and use it to call other APIs if needed. Here I have displayed my Twitter followers list once I login (I know it’s a paltry 17 or something :/ ).
  • If you want to exit from your 3D application back to your launch view (login page in this case), use a UWP class library and expose a function that calls CoreApplication.Exit()
  • Call that from your Unity application when you want to exit.

Well, NOW we are done! I’ll have a follow up article to show the entire app in its full glory. Till then..

P.S: The 2D to 3D technique opens up a lot of possibilities to provide unique experiences to the user. Like the user logs in and enters your magical world or a portal opens etc. 

Leave a Reply

Your email address will not be published. Required fields are marked *