Authentication Using Facebook, Google and Microsoft Account in Universal Apps Using MVVM

Introduction

This sample shows how to connect universal apps to Facebook, Google and Microsoft accounts using the MVVM pattern.

Building the Sample

You only need Visual Studio 2012 or Visual Studio 2013 and Windows 8 or Windows 8.1, both the RTM version.

Description

Recently published was Authentication using Facebook, Google and Microsoft account in WP8.0 App (MVVM) and this sample has the same goal, but now the target is Universal Apps. Both have the goal to use the MVVM pattern.

Before starting this sample, analize to see if the SDKs used in the first sample could be used in this new sample and in a first attempt didn´t find a package for all the targets (Windows 8.1 and Windows Phone 8.1 Runtime). Let's see that analysis.

The packages used was:

  1. Facebook SDK for Windows Phone (http://facebooksdk.net/docs/phone/ )
  2. Google APIs Auth Client and Google APIs OAuth2 Client (https://www.nuget.org/packages/Google.Apis.Auth/ and https://www.nuget.org/packages/Google.Apis.Authentication/1.6.0-beta )
  3. Live SDK (http://msdn.microsoft.com/en-US/onedrive/dn630256 )

The packages that were analized are:

  1. Facebook SDK for Windows Phone: there is a package for Windows 8.1 Store Apps but there isn't for Windows Phone 8.1 Runtime (we cannot use the version from Windows Phone 8.0 because it uses a namespace for controls that does not exist in the Windows Phone 8.1 Runtime)
  2. Google APIs Auth Client and Google APIs OAuth2 Client: there is a package compatible with Windows 8.1 Store Apps but it is a bit different from the sample created before, the API changed. And there isn't a package for the Windows Phone 8.1 Runtime.
  3. Live SDK: is compatible with the Windows Phone 8.1 Runtime and Windows 8.1.

The next step, was to try to port the package for Google from Windows 8.1 Store Apps to Windows Phone 8.1 Runtime, create the logic because there is a lot of code shared between them and then the hard work began.

After some attempts, the code started to throw the exception NotImplementedException because the WebAuthenticationBroker class does not work the same way for these targets. There is a sample that shows this difference, here is the source code  and we will see this in this sample.

In conclusion of this analysis, I decided to use WebAuthenticationBroker for authentication using Facebook and Google accounts and Live SDK for Microsoft accounts.

Let's start the sample!

Note: This sample uses MVVM Light and Cimbalino Toolkit.

For each provider it is necessary to get the app id/client id/client secrect in their websites.

For Google go to https://console.developers.google.com/project and create a new project (APIs and auth > credentials).

Universal Apps using MVVM

For Facebook go to https://developers.facebook.com/ and create a new app.

For Live SDK go to https://account.live.com/developers/applications/index and create one or use an existing app.

Before you start you should change the Constant file to add client ids / client secret / app id, without it the app fails!!

  1. /// <summary>   
  2.     /// Defines the constants strings used in the app.   
  3.     /// </summary>   
  4.     public class Constants   
  5.     {   
  6.         /// <summary>   
  7.         /// The google callback url.   
  8.         /// </summary>  
  9.  #if !WINDOWS_PHONE_APP 
  10.         public const string GoogleCallbackUrl = "urn:ietf:wg:oauth:2.0:oob";   
  11.  #else
  12.         public const string GoogleCallbackUrl = "http://localhost";
  13.  #end  
  14.         /// <summary>   
  15.         /// The facebook app id.   
  16.         /// </summary>   
  17.         public const string FacebookAppId = "<app id>";   
  18.    
  19.         /// <summary>   
  20.         /// The google client identifier.   
  21.         /// </summary>   
  22.         public const string GoogleClientId = "<client id>";   
  23.            
  24.         /// <summary>   
  25.         /// The google client secret.   
  26.         /// </summary>   
  27.         public const string GoogleClientSecret = "<client secret";   
  28.    
  29.         /// <summary>   
  30.         /// The login token.   
  31.         /// </summary>   
  32.         public const string LoginToken = "LoginToken";   
  33.            
  34.         /// <summary>   
  35.         /// The facebook provider.   
  36.         /// </summary>   
  37.         public const string FacebookProvider = "facebook";   
  38.    
  39.         /// <summary>   
  40.         /// The google provider.   
  41.         /// </summary>   
  42.         public const string GoogleProvider = "google";   
  43.    
  44.         /// <summary>   
  45.         /// The microsoft provider.   
  46.         /// </summary>   
  47.         public const string MicrosoftProvider = "microsoft";   
  48.     }  
This sample will use the same idea used in Authentication using Facebook, Google and Microsoft account in WP8.0 App (MVVM). There are classes that have the same goal and the same name. Like in that sample, this sample created a SessionService that manages the Login and Logout using a provider value. That is nice because in LoginView we set the buttons to the same command and for each command we set the provider in commandparameter. With it, the LoginView and LoginViewModel are more clear and simple.

The following are the classes created: 
  • FacebookService has all code related with authentication with Facebook account;
  • MicrosoftService has all code related with authentication with Microsoft account;
  • GoogleService has all code related with authentication with Google account;
  • SessionService call the methods login or logout for the provide requested;

The Flow

To help to understood the difference in the flow in each platform some diagrams were created.

The flow for the Windows 8.1 Store apps will be:



The flow for Windows Phone 8.1 Runtime will be:

  • using Microsoft account



  • using Facebook Account or Google account


Note: Start in LoginView using the blue arrow and when the blue flow finnishes, go to FacebookService/GoogleService and follow the red flow.

Like we can see, the authentication for Windows Phone 8.1 is very complicated, it could be easier like in Windows 8.1 Store apps. And It breaks the MVVM Pattern!

This sample is a Universal App, for this reason the code can be found in the Shared Project and to add specific features for each target directives (#if #else #endif) are used, it can cause some difficulties for understanding the code but is a good way to have only one code in one place. Partial methods and classes can be used here, because in most cases directives are added to add a method for Windows Phone.

The FacebookService

  1. /// <summary>   
  2.     /// Defines the Facebook Service.   
  3.     /// </summary>   
  4.     public class FacebookService : IFacebookService   
  5.     {   
  6.         private readonly ILogManager _logManager;   
  7.    
  8.         /// <summary>   
  9.         /// Initializes a new instance of the <see cref="FacebookService"/> class.   
  10.         /// </summary>   
  11.         /// <param name="logManager">   
  12.         /// The log manager.   
  13.         /// </param>   
  14.         public FacebookService(ILogManager logManager)   
  15.         {   
  16.             _logManager = logManager;   
  17.         }   
  18.    
  19.         /// <summary>   
  20.         /// The login sync.   
  21.         /// </summary>   
  22.         /// <returns>   
  23.         /// The <see cref="Task"/> object.   
  24.         /// </returns>   
  25.         public async Task<Session> LoginAsync()   
  26.         {   
  27.             const string FacebookCallbackUrl = "https://m.facebook.com/connect/login_success.html";   
  28.             var facebookUrl = "https://www.facebook.com/dialog/oauth?client_id=" + Uri.EscapeDataString(Constants.FacebookAppId) + "&redirect_uri=" + Uri.EscapeDataString(FacebookCallbackUrl) + "&scope=public_profile,email&display=popup&response_type=token";   
  29.    
  30.             var startUri = new Uri(facebookUrl);   
  31.             var endUri = new Uri(FacebookCallbackUrl);   
  32.   
  33. #if WINDOWS_PHONE_APP   
  34.             WebAuthenticationBroker.AuthenticateAndContinue(startUri, endUri, null, WebAuthenticationOptions.None);   
  35.             return null;   
  36. #else   
  37.             var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri, endUri);   
  38.             return GetSession(webAuthenticationResult);   
  39. #endif   
  40.         }   
  41.            
  42.         private void GetKeyValues(string webAuthResultResponseData, out string accessToken, out string expiresIn)   
  43.         {   
  44.             string responseData = webAuthResultResponseData.Substring(webAuthResultResponseData.IndexOf("access_token", StringComparison.Ordinal));   
  45.             string[] keyValPairs = responseData.Split('&');   
  46.             accessToken = null;   
  47.             expiresIn = null;   
  48.             for (int i = 0; i < keyValPairs.Length; i++)   
  49.             {   
  50.                 string[] splits = keyValPairs[i].Split('=');   
  51.                 switch (splits[0])   
  52.                 {   
  53.                     case "access_token":   
  54.                         accessToken = splits[1];   
  55.                         break;   
  56.                     case "expires_in":   
  57.                         expiresIn = splits[1];   
  58.                         break;   
  59.                 }   
  60.             }   
  61.         }   
  62.    
  63.         /// <summary>   
  64.         /// This function extracts access_token from the response returned from web authentication broker   
  65.         /// and uses that token to get user information using facebook graph api.    
  66.         /// </summary>   
  67.         /// <param name="accessToken">   
  68.         /// The access Token.   
  69.         /// </param>   
  70.         /// <returns>   
  71.         /// The <see cref="Task"/>.   
  72.         /// </returns>   
  73.         private async Task<UserInfo> GetFacebookUserNameAsync(string accessToken)   
  74.         {   
  75.             var httpClient = new HttpClient();   
  76.             var response = await httpClient.GetStringAsync(new Uri("https://graph.facebook.com/me?access_token=" + accessToken));   
  77.             var value = JsonValue.Parse(response).GetObject();   
  78.             var facebookUserName = value.GetNamedString("name");   
  79.    
  80.             return new UserInfo   
  81.             {   
  82.                 Name = facebookUserName,   
  83.             };   
  84.         }   
  85.    
  86.         /// <summary>   
  87.         /// Logouts this instance.   
  88.         /// </summary>   
  89.         public async void Logout()   
  90.         {   
  91.             Exception exception = null;   
  92.             try   
  93.             {   
  94.                   
  95.             }   
  96.             catch (Exception ex)   
  97.             {   
  98.                 exception = ex;   
  99.             }   
  100.             if (exception != null)   
  101.             {   
  102.                 await _logManager.LogAsync(exception);   
  103.             }   
  104.         }   
  105.   
  106. #if WINDOWS_PHONE_APP   
  107.         public async Task<Session> Finalize(WebAuthenticationBrokerContinuationEventArgs args)   
  108.         {   
  109.             Exception exception = null;   
  110.             try   
  111.             {   
  112.                 var result = args.WebAuthenticationResult;   
  113.    
  114.                 return GetSession(result);   
  115.             }   
  116.             catch (Exception e)   
  117.             {   
  118.                 exception = e;   
  119.             }   
  120.    
  121.             await _logManager.LogAsync(exception);   
  122.               
  123.             return null;   
  124.         }   
  125. #endif   
  126.         private Session GetSession(WebAuthenticationResult result)   
  127.         {   
  128.             if (result.ResponseStatus == WebAuthenticationStatus.Success)   
  129.             {   
  130.                 string accessToken;   
  131.                 string expiresIn;   
  132.                 GetKeyValues(result.ResponseData, out accessToken, out expiresIn);   
  133.    
  134.                 return new Session   
  135.                 {   
  136.                     AccessToken = accessToken,   
  137.                     ExpireDate = new DateTime(long.Parse(expiresIn)),   
  138.                     Provider = Constants.FacebookProvider   
  139.                 };   
  140.             }   
  141.             if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)   
  142.             {   
  143.                 throw new Exception("Error http");   
  144.             }   
  145.             if (result.ResponseStatus == WebAuthenticationStatus.UserCancel)   
  146.             {   
  147.                 throw new Exception("User Canceled.");   
  148.             }   
  149.             return null;   
  150.         }   
  151.     }  
In this class, in LoginAsync, we could see the directives that define the code for each platform. The first attempt was a bit complicated to define a solution for it, using null was the solution (for Windows Phone, of course!). This class doesn´t do anything in the logout method, we could remove it, but to keep the same pattern in all the classes it wasn´t removed and the session is not saved in webview, at least it is possible to login using a different account when the LoginView is shown again.

The GoogleService
 
 
public class GoogleService : IGoogleService
{
private readonly ILogManager _logManager;
/// <summary>
/// Initializes a new instance of the <see cref="GoogleService"/> class.
/// </summary>
/// <param name="logManager">
/// The log manager.
/// </param>
public GoogleService(ILogManager logManager)
{
_logManager = logManager;
}
/// <summary>
/// The login async.
/// </summary>
/// <returns>
/// The <see cref="Task"/> object.
/// </returns>
public async Task<Session> LoginAsync()
{
var googleUrl = new StringBuilder();
googleUrl.Append(Uri.EscapeDataString(Constants.GoogleClientId));
googleUrl.Append("&scope=openid%20email%20profile");
googleUrl.Append("&redirect_uri=");
googleUrl.Append(Uri.EscapeDataString(Constants.GoogleCallbackUrl));
googleUrl.Append("&state=foobar");
googleUrl.Append("&response_type=code");
var startUri = new Uri(googleUrl.ToString());
#if !WINDOWS_PHONE_APP
var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.UseTitle, startUri, endUri);
return await GetSession(webAuthenticationResult);
#else
WebAuthenticationBroker.AuthenticateAndContinue(startUri, newUri(Constants.GoogleCallbackUrl), null, WebAuthenticationOptions.None);
return null;
#endif
}
private string GetCode(string webAuthResultResponseData)
{
// Success code=4/izytpEU6PjuO5KKPNWSB4LK3FU1c
var split = webAuthResultResponseData.Split('&');
return split.FirstOrDefault(value => value.Contains("code"));
}
/// <summary>
/// The logout.
/// </summary>
public void Logout()
{
}
#if WINDOWS_PHONE_APP
public async Task<Session> Finalize(WebAuthenticationBrokerContinuationEventArgs args)
{
Exception exception = null;
try
{
return await GetSession(args.WebAuthenticationResult);
}
catch (Exception e)
{
exception = e;
}
await _logManager.LogAsync(exception);
return null;
}
#endif
private async Task<Session> GetSession(WebAuthenticationResult result)
{
if (result.ResponseStatus == WebAuthenticationStatus.Success)
{
var code = GetCode(result.ResponseData);
var serviceRequest = await GetToken(code);
return new Session
{
AccessToken = serviceRequest.access_token,
ExpireDate = new DateTime(long.Parse(serviceRequest.expires_in)),
Id = serviceRequest.id_token,
Provider = Constants.GoogleProvider
};
}
if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
{
throw new Exception("Error http");
}
if (result.ResponseStatus == WebAuthenticationStatus.UserCancel)
{
throw new Exception("User Canceled.");
}
return null;
}
private static async Task<ServiceResponse> GetToken(string code)
{
var body = new StringBuilder();
body.Append(code);
body.Append("&client_id=");
body.Append(Uri.EscapeDataString(Constants.GoogleClientId));
body.Append("&client_secret=");
body.Append(Uri.EscapeDataString(Constants.GoogleClientSecret));
body.Append("&redirect_uri=");
body.Append(Uri.EscapeDataString(Constants.GoogleCallbackUrl));
body.Append("&grant_type=authorization_code");
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, new Uri(TokenUrl))
{
Content = new StringContent(body.ToString(), Encoding.UTF8, "application/x-www-form-urlencoded")
};
var response = await client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
var serviceTequest = JsonConvert.DeserializeObject<ServiceResponse>(content);
return serviceTequest;
}
}
 
Here, we don´t have anything new, this is similar to the FacebookService.

Note: FacebookService and GoogleService are similar but the response and request are different for the reason that these classes are not joined.
Attention:
Google changed the authentication and this sample uses the last version. See more about it here .
 
 
The MicrosoftService
  1. /// <summary>   
  2. /// The microsoft service.   
  3. /// </summary>   
  4. public class MicrosoftService : IMicrosoftService   
  5. {   
  6.     private readonly ILogManager _logManager;   
  7.     private LiveAuthClient _authClient;   
  8.     private LiveConnectSession _liveSession;   
  9.   
  10.   
  11.     /// <summary>   
  12.     /// Defines the scopes the application needs.   
  13.     /// </summary>   
  14.     private List<string> _scopes;   
  15.        
  16.     /// <summary>   
  17.     /// Initializes a new instance of the <see cref="MicrosoftService"/> class.   
  18.     /// </summary>   
  19.     /// <param name="logManager">   
  20.     /// The log manager.   
  21.     /// </param>   
  22.     public MicrosoftService(ILogManager logManager)   
  23.     {   
  24.         _scopes = new List<string> { "wl.signin""wl.basic""wl.offline_access" };   
  25.         _logManager = logManager;   
  26.     }   
  27.   
  28.     /// <summary>   
  29.     /// The login async.   
  30.     /// </summary>   
  31.     /// <returns>   
  32.     /// The <see cref="Task"/> object.   
  33.     /// </returns>   
  34.     public async Task<Session> LoginAsync()   
  35.     {   
  36.   
  37.         Exception exception = null;   
  38.         try   
  39.         {   
  40.             _authClient = new LiveAuthClient();   
  41.             var loginResult = await _authClient.InitializeAsync(_scopes);   
  42.             var result = await _authClient.LoginAsync(_scopes);   
  43.             if (result.Status == LiveConnectSessionStatus.Connected)   
  44.             {   
  45.                 _liveSession = loginResult.Session;   
  46.                 var session = new Session   
  47.                 {   
  48.                     AccessToken = result.Session.AccessToken,   
  49.                     Provider = Constants.MicrosoftProvider,   
  50.                 };   
  51.   
  52.                 return session;   
  53.             }   
  54.   
  55.         }   
  56.         catch (LiveAuthException ex)   
  57.         {   
  58.             throw new InvalidOperationException("Login canceled.", ex);   
  59.         }   
  60.   
  61.         catch (Exception e)   
  62.         {   
  63.             exception = e;   
  64.         }   
  65.          await _logManager.LogAsync(exception);   
  66.   
  67.         return null;   
  68.     }   
  69.   
  70.     /// <summary>   
  71.     /// The get user info.   
  72.     /// </summary>   
  73.     /// <returns>   
  74.     /// The <see cref="Task"/> object.   
  75.     /// </returns>   
  76.     public async Task<IDictionary<stringobject>> GetUserInfo()   
  77.     {   
  78.   
  79.         Exception exception = null;   
  80.         try   
  81.         {      
  82.             var liveClient = new LiveConnectClient(_liveSession);   
  83.             LiveOperationResult operationResult = await liveClient.GetAsync("me");   
  84.   
  85.             return operationResult.Result;   
  86.         }   
  87.         catch (LiveConnectException e)   
  88.         {   
  89.             exception = e;   
  90.         }   
  91.         await _logManager.LogAsync(exception);   
  92.   
  93.         return null;   
  94.     }   
  95.   
  96.     /// <summary>   
  97.     /// The logout.   
  98.     /// </summary>   
  99.     public async void Logout()   
  100.     {   
  101.   
  102.         if (_authClient == null)   
  103.         {   
  104.             _authClient = new LiveAuthClient();   
  105.             var loginResult = await _authClient.InitializeAsync(_scopes);   
  106.         }   
  107.         if (_authClient.CanLogout)   
  108.         {   
  109.             _authClient.Logout();   
  110.         }   
  111.     }   
  112. }  
This class was reused from the sample Authentication using Facebook, Google and Microsoft account in WP8.0 App (MVVM), but for it work is required to associate the app to the store.



That will result in an additional file in the project: as in the following:



Note

 

  1. These file are removed from the sample because each developer has their own.
  2. In devices that the Microsoft account is logged the application will do the login automatically.

The SessionService

  1. /// <summary>   
  2. /// The service session.   
  3. /// </summary>   
  4. public class SessionService : ISessionService   
  5. {   
  6.     private readonly IApplicationDataService _applicationSettings;   
  7.     private readonly IFacebookService _facebookService;   
  8.     private readonly IMicrosoftService _microsoftService;   
  9.     private readonly IGoogleService _googleService;   
  10.     private readonly ILogManager _logManager;   
  11.        
  12.     /// <summary>   
  13.     /// Initializes a new instance of the <see cref="SessionService" /> class.   
  14.     /// </summary>   
  15.     /// <param name="applicationSettings">The application settings.</param>   
  16.     /// <param name="facebookService">The facebook service.</param>   
  17.     /// <param name="microsoftService">The microsoft service.</param>   
  18.     /// <param name="googleService">The google service.</param>   
  19.     /// <param name="logManager">The log manager.</param>   
  20.     public SessionService(IApplicationDataService applicationSettings,   
  21.         IFacebookService facebookService,   
  22.         IMicrosoftService microsoftService,   
  23.         IGoogleService googleService, ILogManager logManager)   
  24.     {   
  25.         _applicationSettings = applicationSettings;   
  26.         _facebookService = facebookService;   
  27.         _microsoftService = microsoftService;   
  28.         _googleService = googleService;   
  29.         _logManager = logManager;   
  30.     }   
  31.   
  32.     /// <summary>   
  33.     /// Gets the session.   
  34.     /// </summary>   
  35.     /// <returns>The session object.</returns>   
  36.     public Session GetSession()   
  37.     {   
  38.         var expiryValue = DateTime.MinValue;   
  39.         string expiryTicks = LoadEncryptedSettingValue("session_expiredate");   
  40.         if (!string.IsNullOrWhiteSpace(expiryTicks))   
  41.         {   
  42.             long expiryTicksValue;   
  43.             if (long.TryParse(expiryTicks, out expiryTicksValue))   
  44.             {   
  45.                 expiryValue = new DateTime(expiryTicksValue);   
  46.             }   
  47.         }   
  48.   
  49.         var session = new Session   
  50.         {   
  51.             AccessToken = LoadEncryptedSettingValue("session_token"),   
  52.             Id = LoadEncryptedSettingValue("session_id"),   
  53.             ExpireDate = expiryValue,   
  54.             Provider = LoadEncryptedSettingValue("session_provider")   
  55.         };   
  56.         _applicationSettings.LocalSettings[Constants.LoginToken] = true;   
  57.         return session;   
  58.     }   
  59.   
  60.     /// <summary>   
  61.     /// The save session.   
  62.     /// </summary>   
  63.     /// <param name="session">   
  64.     /// The session.   
  65.     /// </param>   
  66.     private void Save(Session session)   
  67.     {   
  68.         SaveEncryptedSettingValue("session_token", session.AccessToken);   
  69.         SaveEncryptedSettingValue("session_id", session.Id);   
  70.         SaveEncryptedSettingValue("session_expiredate", session.ExpireDate.Ticks.ToString(CultureInfo.InvariantCulture));   
  71.         SaveEncryptedSettingValue("session_provider", session.Provider);   
  72.         _applicationSettings.LocalSettings[Constants.LoginToken] = true;   
  73.     }   
  74.   
  75.     /// <summary>   
  76.     /// The clean session.   
  77.     /// </summary>   
  78.     private void CleanSession()   
  79.     {   
  80.         _applicationSettings.LocalSettings.Remove("session_token");   
  81.         _applicationSettings.LocalSettings.Remove("session_id");   
  82.         _applicationSettings.LocalSettings.Remove("session_expiredate");   
  83.         _applicationSettings.LocalSettings.Remove("session_provider");   
  84.         _applicationSettings.LocalSettings.Remove(Constants.LoginToken);   
  85.     }   
  86.   
  87.     /// <summary>   
  88.     /// The login async.   
  89.     /// </summary>   
  90.     /// <param name="provider">   
  91.     /// The provider.   
  92.     /// </param>   
  93.     /// <returns>   
  94.     /// The <see cref="Task"/> object.   
  95.     /// </returns>   
  96.     public async Task<bool?> LoginAsync(string provider)   
  97.     {   
  98.         Provider = provider;   
  99.         Exception exception;   
  100.         try   
  101.         {   
  102.             Session session = null;   
  103.             switch (provider)   
  104.             {   
  105.                 case Constants.FacebookProvider:   
  106.                     session = await _facebookService.LoginAsync();   
  107.                     break;   
  108.                 case Constants.MicrosoftProvider:   
  109.                     session = await _microsoftService.LoginAsync();   
  110.                     break;   
  111.                 case Constants.GoogleProvider:   
  112.                     session = await _googleService.LoginAsync();   
  113.                     break;   
  114.             }   
  115.             if (session == null)   
  116.             {   
  117.                 return null;   
  118.             }   
  119.             Save(session);   
  120.                
  121.             return true;   
  122.         }   
  123.         catch (Exception ex)   
  124.         {   
  125.             exception = ex;   
  126.         }   
  127.         await _logManager.LogAsync(exception);   
  128.   
  129.         return false;   
  130.     }   
  131.   
  132.     /// <summary>   
  133.     /// Gets or sets the provider.   
  134.     /// </summary>   
  135.     /// <value>   
  136.     /// The provider.   
  137.     /// </value>   
  138.     public string Provider { getset; }   
  139.   
  140.     /// <summary>   
  141.     /// The logout.   
  142.     /// </summary>   
  143.     public async void Logout()   
  144.     {   
  145.         Exception exception = null;   
  146.         try   
  147.         {   
  148.             var session = GetSession();   
  149.             switch (session.Provider)   
  150.             {   
  151.                 case Constants.FacebookProvider:   
  152.                     _facebookService.Logout();   
  153.                     break;   
  154.                 case Constants.MicrosoftProvider:   
  155.                     _microsoftService.Logout();   
  156.                     break;   
  157.                 case Constants.GoogleProvider:   
  158.                     _googleService.Logout();   
  159.                     break;   
  160.             }   
  161.             CleanSession();   
  162.         }   
  163.         catch (Exception ex)   
  164.         {   
  165.             exception = ex;   
  166.         }   
  167.         if (exception != null)   
  168.         {   
  169.             await _logManager.LogAsync(exception);   
  170.         }   
  171.     }   
  172.   
  173. WINDOWS_PHONE_APP   
  174.     public async Task<bool> Finalize(WebAuthenticationBrokerContinuationEventArgs args)   
  175.     {   
  176.         Exception exception = null;   
  177.         try   
  178.         {   
  179.             Session session = null;   
  180.             switch (Provider)   
  181.             {   
  182.                 case Constants.FacebookProvider:   
  183.                     session = await _facebookService.Finalize(args);   
  184.                     break;   
  185.                 case Constants.GoogleProvider:   
  186.                     session = await _googleService.Finalize(args);   
  187.                     break;   
  188.             }   
  189.             Save(session);   
  190.             return true;   
  191.         }   
  192.         catch (Exception e)   
  193.         {   
  194.             exception = e;   
  195.         }   
  196.         await _logManager.LogAsync(exception);   
  197.         return false;   
  198.     }   
  199. if   
  200.     /// <summary>   
  201.     /// Loads an encrypted setting value for a given key.   
  202.     /// </summary>   
  203.     /// <param name="key">   
  204.     /// The key to load.   
  205.     /// </param>   
  206.     /// <returns>   
  207.     /// The value of the key.   
  208.     /// </returns>   
  209.     private string LoadEncryptedSettingValue(string key)   
  210.     {   
  211.         string value = null;   
  212.   
  213.         var protectedBytes = _applicationSettings.LocalSettings[key];   
  214.         if (protectedBytes != null)   
  215.         {   
  216.             // todo use DataProtectionProvider   
  217.             // byte[] valueBytes = ProtectedData.Unprotect(protectedBytes, null);   
  218.             // value = Encoding.UTF8.GetString(valueBytes, 0, valueBytes.Length);   
  219.             value = protectedBytes.ToString();   
  220.         }   
  221.   
  222.         return value;   
  223.     }   
  224.   
  225.     /// <summary>   
  226.     /// Saves a setting value against a given key, encrypted.   
  227.     /// </summary>   
  228.     /// <param name="key">   
  229.     /// The key to save against.   
  230.     /// </param>   
  231.     /// <param name="value">   
  232.     /// The value to save against.   
  233.     /// </param>   
  234.     /// <exception cref="System.ArgumentOutOfRangeException">   
  235.     /// The key or value provided is unexpected.   
  236.     /// </exception>   
  237.     private void SaveEncryptedSettingValue(string key, string value)   
  238.     {   
  239.         if (!string.IsNullOrWhiteSpace(key) && !string.IsNullOrWhiteSpace(value))   
  240.         {   
  241.             // todo use DataProtectionProvider   
  242.             // byte[] valueBytes = Encoding.UTF8.GetBytes(value);   
  243.             // var dataProtectionProvider = new DataProtectionProvider();             
  244.             // // Encrypt the value by using the Protect() method.   
  245.             // byte[] protectedBytes = await dataProtectionProvider.ProtectAsync(valueBytes);   
  246.             _applicationSettings.LocalSettings[key] = value;   
  247.         }   
  248.     }   
  249. }  
This class will return null if the session is null, we need to be aware that there isn´t any error and the session is returned or if it is null, the process will be done by the Finalize method.

Here is the class diagram with all classes and interfaces created in this sample:




Now to build the User Interface and because we are using the MVVM pattern, it created a LoginViewModel to do the binding to the LoginView.

 The LoginViewModel
  1. /// <summary>   
  2.     /// The login view model.   
  3.     /// </summary>   
  4.     public class LoginViewModel : ViewModelBase   
  5.     {   
  6.         private readonly ILogManager _logManager;   
  7.         private readonly IMessageBoxService _messageBox;   
  8.         private readonly INetworkInformationService _networkInformationService;   
  9.         private readonly INavigationService _navigationService;   
  10.         private readonly ISessionService _sessionService;   
  11.         private bool _inProgress;   
  12.    
  13.         /// <summary>   
  14.         /// Initializes a new instance of the <see cref="LoginViewModel"/> class.   
  15.         /// </summary>   
  16.         /// <param name="navigationService">   
  17.         /// The navigation service.   
  18.         /// </param>   
  19.         /// <param name="sessionService">   
  20.         /// The session service.   
  21.         /// </param>   
  22.         /// <param name="messageBox">   
  23.         /// The message box.   
  24.         /// </param>   
  25.         /// <param name="networkInformationService">   
  26.         /// The network connection.   
  27.         /// </param>   
  28.         /// <param name="logManager">   
  29.         /// The log manager.   
  30.         /// </param>   
  31.         public LoginViewModel(INavigationService navigationService,   
  32.             ISessionService sessionService,   
  33.             IMessageBoxService messageBox,   
  34.             INetworkInformationService networkInformationService,   
  35.             ILogManager logManager)   
  36.         {   
  37.             _navigationService = navigationService;   
  38.             _sessionService = sessionService;   
  39.             _messageBox = messageBox;   
  40.             _networkInformationService = networkInformationService;   
  41.    
  42.             _logManager = logManager;   
  43.             LoginCommand = new RelayCommand<string>(LoginAction);   
  44.         }   
  45.    
  46.         /// <summary>   
  47.         /// Gets the navigation service.   
  48.         /// </summary>   
  49.         /// <value>   
  50.         /// The navigation service.   
  51.         /// </value>   
  52.         public INavigationService NavigationService   
  53.         {   
  54.             get { return _navigationService; }   
  55.         }   
  56.    
  57.         /// <summary>   
  58.         /// Gets or sets a value indicating whether in progress.   
  59.         /// </summary>   
  60.         /// <value>   
  61.         /// The in progress.   
  62.         /// </value>   
  63.         public bool InProgress   
  64.         {   
  65.             get { return _inProgress; }   
  66.             set { Set(() => InProgress, ref _inProgress, value); }   
  67.         }   
  68.    
  69.         /// <summary>   
  70.         /// Gets the facebook login command.   
  71.         /// </summary>   
  72.         /// <value>   
  73.         /// The facebook login command.   
  74.         /// </value>   
  75.         public ICommand LoginCommand { getprivate set; }   
  76.    
  77.         /// <summary>   
  78.         /// Facebook's login action.   
  79.         /// </summary>   
  80.         /// <param name="provider">   
  81.         /// The provider.   
  82.         /// </param>   
  83.         private async void LoginAction(string provider)   
  84.         {   
  85.             Exception exception = null;   
  86.             bool isToShowMessage = false;   
  87.             try   
  88.             {   
  89.                 if (!_networkInformationService.IsNetworkAvailable)   
  90.                 {   
  91.                     await _messageBox.ShowAsync("There isn´t network connection.",   
  92.                                           "Authentication Sample",   
  93.                                           new List<string> { "Ok" });   
  94.                     return;   
  95.                 }   
  96.                 if (Constants.GoogleClientId.Contains("<") || Constants.GoogleClientSecret.Contains("<"))   
  97.                 {   
  98.                     await _messageBox.ShowAsync("Is missing the google client id and client secret. Search for Constant.cs file.",   
  99.                                          "Authentication Sample",   
  100.                                          new List<string> { "Ok" });   
  101.                     return;   
  102.                 }   
  103.                 if (Constants.FacebookAppId.Contains("<"))   
  104.                 {   
  105.                     await _messageBox.ShowAsync("Is missing the facebook client id. Search for Constant.cs file.",   
  106.                                          "Authentication Sample",   
  107.                                          new List<string> { "Ok" });   
  108.                     return;   
  109.                 }   
  110.                 InProgress = true;   
  111.                 var auth = await _sessionService.LoginAsync(provider);   
  112.                 if (auth == null)   
  113.                 {   
  114.                     return;   
  115.                 }   
  116.                 if (!auth.Value)   
  117.                 {   
  118.                     await ShowMessage();   
  119.                 }   
  120.                 else   
  121.                 {   
  122.                     _navigationService.Navigate<MainView>();   
  123.                     InProgress = false;   
  124.                 }   
  125.    
  126.                 InProgress = false;   
  127.             }   
  128.             catch (Exception ex)   
  129.             {   
  130.                 InProgress = false;   
  131.                 exception = ex;   
  132.                 isToShowMessage = true;   
  133.             }   
  134.             if (isToShowMessage)   
  135.             {   
  136.                 await _messageBox.ShowAsync("Application fails.",   
  137.                                            "Authentication Sample",    
  138.                                             new List<string> { "Ok" });   
  139.             }   
  140.             if (exception != null)   
  141.             {   
  142.                 await _logManager.LogAsync(exception);   
  143.             }   
  144.         }   
  145.    
  146.         private async Task ShowMessage()   
  147.         {   
  148.             await _messageBox.ShowAsync("Wasn´t possible to complete the login.",   
  149.                "Authentication Sample",   
  150.                 new List<string>   
  151.                 {   
  152.                    "Ok"    
  153.                 });   
  154.         }   
  155.   
  156. #if WINDOWS_PHONE_APP   
  157.         public async void Finalize(WebAuthenticationBrokerContinuationEventArgs args)   
  158.         {   
  159.             var result = await _sessionService.Finalize(args);   
  160.             if (!result)   
  161.             {   
  162.                 await ShowMessage();   
  163.             }   
  164.             else   
  165.             {   
  166.                 _navigationService.Navigate<MainView>();   
  167.                 InProgress = false;   
  168.             }   
  169.         }   
  170. #endif   
  171.     }  
Note: In the LoginAction the parameter provider is the value of the CommandParameter received in LoginCommand, this is set in the login page.

For the final the code, let's see the code for the page.

The LoginPage.xaml
  1. <Page   
  2.     x:Class="AuthenticationSample.UniversalApps.Views.LoginView"   
  3.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"   
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"   
  5.     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"   
  6.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"   
  7.     xmlns:converters="using:Cimbalino.Toolkit.Converters"   
  8.     mc:Ignorable="d">   
  9.    
  10.     <Page.DataContext>   
  11.         <Binding Mode="OneWay"   
  12.                  Path="LoginViewModel"   
  13.                  Source="{StaticResource Locator}" />   
  14.     </Page.DataContext>   
  15.     <Page.Resources>   
  16.         <converters:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>   
  17.     </Page.Resources>   
  18.     <!--  LayoutRoot is the root grid where all page content is placed  -->   
  19.     <Grid x:Name="LayoutRoot" Background="LightGray">   
  20.         <Grid.RowDefinitions>   
  21.             <RowDefinition Height="{StaticResource HeaderHeigth}" />   
  22.             <RowDefinition Height="*" />   
  23.         </Grid.RowDefinitions>   
  24.    
  25.         <!--  TitlePanel contains the name of the application and page title  -->   
  26.         <StackPanel x:Name="TitlePanel"    
  27.                     Margin="{StaticResource HeaderMargin}"   
  28.                     VerticalAlignment="Center" Grid.Row="0">   
  29.             <TextBlock  FontSize="30"    
  30.                         Foreground="Black"   
  31.                        Text="Login"/>   
  32.         </StackPanel>   
  33.    
  34.         <!--  ContentPanel - place additional content here  -->   
  35.         <Grid x:Name="ContentPanel"   
  36.               VerticalAlignment="Center"   
  37.               HorizontalAlignment="Center"   
  38.               Grid.Row="1">   
  39.             <Grid.RowDefinitions>   
  40.                 <RowDefinition Height="Auto" />   
  41.                 <RowDefinition Height="80" />   
  42.                 <RowDefinition Height="80" />   
  43.                 <RowDefinition Height="80" />   
  44.                 <RowDefinition Height="80" />   
  45.             </Grid.RowDefinitions>   
  46.             <TextBlock Grid.Row="0"    
  47.                        FontSize="20"   
  48.                        Foreground="Black"   
  49.                        Text="Use your account"/>   
  50.             <Button Grid.Row="1" Width="300"   
  51.                     Margin="10"   
  52.                     Command="{Binding LoginCommand}"   
  53.                     CommandParameter="facebook"   
  54.                     Background="{StaticResource FacebookBlueBackgroundBrush}" >   
  55.                 <StackPanel Orientation="Horizontal">   
  56.                     <TextBlock Text=""    
  57.                                    VerticalAlignment="Center"   
  58.                                    FontFamily="/Fonts/fontawesome-webfont.ttf#FontAwesome"    
  59.                                    HorizontalAlignment="Left"/>   
  60.                     <TextBlock Margin="10,0,0,0" Text="Facebook"    
  61.                            HorizontalAlignment="Center"/>   
  62.                 </StackPanel>   
  63.             </Button>   
  64.             <Button Grid.Row="3"   
  65.                     Margin="10" Width="300"   
  66.                     Command="{Binding LoginCommand}"   
  67.                     CommandParameter="microsoft"   
  68.                     Background="{StaticResource MicrosoftBlueBackgroundBrush}" >   
  69.                 <StackPanel Orientation="Horizontal">   
  70.                     <TextBlock Text=""   
  71.                                    VerticalAlignment="Center"   
  72.                                    FontFamily="/Fonts/fontawesome-webfont.ttf#FontAwesome"    
  73.                                    HorizontalAlignment="Left"/>   
  74.                     <TextBlock Margin="10,0,0,0" Text="Microsoft"    
  75.                            HorizontalAlignment="Center"/>   
  76.                 </StackPanel>   
  77.             </Button>   
  78.             <Button Grid.Row="2" Width="300"   
  79.                     Margin="10"   
  80.                     Command="{Binding LoginCommand}"   
  81.                     CommandParameter="google"   
  82.                     Background="{StaticResource GoogleRedBackgroundBrush}" >   
  83.                 <StackPanel Orientation="Horizontal">   
  84.                     <TextBlock Text=""   
  85.                                    VerticalAlignment="Center"   
  86.                                    FontFamily="/Fonts/fontawesome-webfont.ttf#FontAwesome"    
  87.                                    HorizontalAlignment="Left"/>   
  88.                     <TextBlock Margin="10,0,0,0" Text="Google"    
  89.                            HorizontalAlignment="Center"/>   
  90.                 </StackPanel>   
  91.             </Button>   
  92.         </Grid>   
  93.         <Grid Visibility="{Binding InProgress, Converter={StaticResource BooleanToVisibilityConverter}}"   
  94.             Grid.Row="0"   
  95.                    Grid.RowSpan="2">   
  96.             <Rectangle    
  97.                    Fill="Black"   
  98.                    Opacity="0.75" />   
  99.             <TextBlock    
  100.                    HorizontalAlignment="Center"   
  101.                    VerticalAlignment="Center"   
  102.                    Text="Auth..." />   
  103.             <ProgressBar IsIndeterminate="True" IsEnabled="True" Margin="0,60,0,0"/>   
  104.         </Grid>   
  105.    
  106.     </Grid>   
  107. </Page>   
For use in the same page in Windows 8.1 Store apps and Windows Phone 8.1 Runtime was used some style.

The LoginView.xaml.cs
  1. /// <summary>   
  2.     /// An empty page that can be used on its own or navigated to within a Frame.   
  3.     /// </summary>   
  4. #if WINDOWS_PHONE_APP   
  5.        public sealed partial class LoginView : Page, IWebAuthenticationContinuable   
  6. #else   
  7.       public sealed partial class LoginView : Page   
  8. #endif   
  9.     {   
  10.         /// <summary>   
  11.         /// Initializes a new instance of the <see cref="LoginView"/> class.   
  12.         /// </summary>   
  13.         public LoginView()   
  14.         {   
  15.             InitializeComponent();   
  16.         }   
  17.    
  18.         /// <summary>   
  19.         /// The on navigated to.   
  20.         /// </summary>   
  21.         /// <param name="e">   
  22.         /// The e.   
  23.         /// </param>   
  24.         protected override void OnNavigatedTo(NavigationEventArgs e)   
  25.         {   
  26.             var viewModel = (LoginViewModel)DataContext;   
  27.             viewModel.NavigationService.RemoveBackEntry();   
  28.             base.OnNavigatedTo(e);   
  29.         }   
  30.   
  31. #if WINDOWS_PHONE_APP   
  32.    
  33.         /// <summary>   
  34.         /// Continues the web authentication.   
  35.         /// </summary>   
  36.         /// <param name="args">The <see cref="Windows.ApplicationModel.Activation.WebAuthenticationBrokerContinuationEventArgs"/> instance containing the event data.</param>   
  37.         public void ContinueWebAuthentication(Windows.ApplicationModel.Activation.WebAuthenticationBrokerContinuationEventArgs args)   
  38.         {   
  39.             var viewModel = (LoginViewModel)DataContext;   
  40.             viewModel.Finalize(args);   
  41.         }   
  42. #endif   
  43.     }  
Conclusion

In conclusion, the flow is completely different for each platform and it has some impact in the development and in sharing the code. Maybe, for this reason there isn't any package for Windows Phone 8.1 that uses authentication.

Source Code

The source code can be found here.

Source Code Files 
  • IFacebookService interface for FacebookService
  • IGoogleService interface for GoogleService
  • ILogManager interface for LogManager
  • IMicrosoftService interface for MicrosoftService
  • ISessionProvider interface for all providers interface (common methods)
  • ISessionService for SessionService
  • Session class for save the information about the session (provider, token, expired date)
  • FacebookService class that has all logic about the login / logout using Facebook provider
  • GoogleService class that has all logic about the login / logout using Google provider
  • MicrosoftService class that has all logic about the login / logout using Microsoft provider
  • SessionService class for manage login/logout (it will use all services provides described before)
  • LoginViewModel class for binding to LoginView.xaml
  • LoginView class that represent the page for login
  • MainViewModel class for binding to MainView.xaml
  • MainView class that appear after the login is ok
  • ViewModelLocator class contains static references to all the view model in application and provides an entry point for the bindings.

The solution



Build the Sample

  1. Start Visual Studio Express 2012 for Windows 8 and select File > Open > Project/Solution.
  2. Go to the directory in which you unzipped the sample. Go to the directory named for the sample and double-click the Visual Studio Express 2012 for Windows 8 Solution (.sln) file.
  3. Press F7 or use Build > Build Solution to build the sample.

Note: you can use Visual Studio 2013 in Windows 8.1.

Run the sample

To debug the app and then run it, press F5 or use Debug > Start Debugging. To run the app without debugging, press Ctrl+F5 or use Debug > Start Without Debugging

Output

The output for each target is:

  • Windows 8.1 Store App

Login Page



Microsoft Authentication



Facebook Authentication



Google Authentication


  • Windows Phone 8.1 App

Login View



Facebook Authentication



Google Authentication


 



Up Next
    Ebook Download
    View all
    Learn
    View all