Jerry Nixon on Windows: Login to your UWP with your MSA

Jerry Nixon on Windows

Tuesday, July 25, 2017

Login to your UWP with your MSA

Here’s the idea, you want your UWP user to login with their MSA so you can get their information, access OneDrive, Outlook, Office, Rome devices or just their profile photo and name. Whatever the reason, it’s more simple than you think.

Please note: the Live SDK we used to use for this has been deprecated and now we use Microsoft Graph for just about everything around authentication & access.

Here are your four easy steps to follow:

  1. Register your app @ http://apps.dev.microsoft.com
  2. Add your ClientID & ReturnURL to app.xaml Resources
  3. Copy AuthenticationHelper.cs
  4. Nuget packages
    1. PM> Install-Package Microsoft.Graph
    2. PM> Install-Package Microsoft.Identity.Client –pre

Step 1: Register your app

Your app can’t do special things until you tell Microsoft’s developer portal your plans. This helps the app police turn off capabilities when malicious apps written by evil developers start to take advantage of naïve users.

image

This is all the information the portal asks. Pretty simple. Fill in your basic information here, and the portal will, in turn, give you credentials.

image

Make sure your app has a ReturnUrl by adding a Web platform and giving it a valid URI as the Redirect URL. You will need this for authentication.

image

Step 2: Adding your ClientID and ReturnUrl to app.xaml

The name of these resources is hard-coded in the SAL helper we will copy into our project later on. So, copy this exactly. Change it will require you change the SDK helper. That’s fine if you need to do it. But not necessary.

image

Step 3: Copy AuthenticationHelper.cs

I copy this into a /Microsoft folder. You can put it anywhere. In fact, you can just open it and steal all the helper code if that’s what you want. But remember, it works out of the box and change is not necessary.

image

Get the code here: https://gist.github.com/

Step 3: Nuget things

There are several things you need to add to make this work, including the Graph SDK. As of today (7/2017) the Microsoft.Identity.Client is in preview. So, make note of that since NuGet doesn’t pull preview items by default.

PM> Install-Package Microsoft.Graph

And, the other one.

PM> Install-Package Microsoft.Identity.Client –pre

Step 4: Use it!

Here’s a simple little method I wrote to help with login, maybe this will help you, too. I made it a Try method because login doesn’t always work.

 image

If it’s the user’s name you want, you can do it by requesting it from the client through the async method, like this: 

image

Security

If you app is ever compromised, you can always nuke it from the developer portal and remove all access and it’s associated secrets, just like I did with the sample app I created for this blog article. Be careful.

image

Best of luck. Happy coding!