Using onedrive-explorer-win sample SDK with store apps

A couple of folks have asked me recently how they can use the sample SDK in the onedrive-explorer-win project inside a Windows Store app. Since Store apps handle authentication differently and don't depend on OAuth. I've created a gist to show how you can use the Windows Store APIs to get an access token and provide that token to the ODConnection class in the sample SDK.

 

Fortunately, it's pretty straight forward. The sample SDK is looking for authentication to come in the form of an object that implements the IAuthenticationInfo interface defined in the sample SDK. The interface is pretty straightforward, and has properties such as AccessToken, RefreshToken, TokenType, and a few others. Implementing this is pretty easy.

 public class AuthToken : OneDrive.IAuthenticationInfo
{
 public string AccessToken { get; private set; }
 
 public string RefreshToken { get; private set; }
 
 public string TokenType { get { return "Bearer"; } }
 
 public DateTimeOffset TokenExpiration { get; private set; }
 
 public Task<bool> RefreshAccessTokenAsync()
 {
 throw new NotImplementedException();
 }
 
 public string AuthorizationHeaderValue { get { return "Bearer " + AccessToken; } }
 }

The slightly harder part is getting the access token and other details from the Windows API. However, after reading up on the subject on MSDN, I got it working. You need to become familiar with the Windows.Security.Authentication.OnlineId namespace and classes, which is where the magic happens.

To request a token from the Windows APIs, you need to create a new instance of the OnlineIdAuthenticator class:

 Authenticator = new OnlineIdAuthenticator();

Once you have that created, you can ask for an access token that contains a set of scopes and conditionally prompts the user or not:

 string accessToken = null;
string scopes = "onedrive.readwrite";
 
CredentialPromptType promptType = silent ? CredentialPromptType.DoNotPrompt : CredentialPromptType.PromptIfNeeded;
var ticketRequests = new List<OnlineIdServiceTicketRequest>();
ticketRequests.Add(new OnlineIdServiceTicketRequest(scopes, OnlineIdTicketPolicyForLiveServices));
 
UserIdentity identity = await Authenticator.AuthenticateUserAsync(ticketRequests, promptType);
if (identity.Tickets != null && identity.Tickets.Count > 0)
{
 accessToken = identity.Tickets[0].Value;
}

The OnlineIdTicketPolicyForLiveServices constant is set to "DELEGATION" which is required for using Microsoft Account credentials.

Once you have the accessToken value back, you can store that value into your implementation of IAuthenticationInfo and pass that to the ODConnection object and everything should work.

For the complete code sample for how to implement this, see my Windows Store App Sign-in for OneDrive SDK gist on GitHub.