Previous posts in this sequence:
Getting Started with Xamarin.Forms and Multi-Targeting in Visual Studio
Getting Started with Xamarin.Forms and SDK Versions
Getting Started with Xamarin.Forms with MvvmCross
Getting Started with Xamarin.Forms and Authenticating with ADAL
In this post I’m going to do a bit of a refactor based on the work completed in the previous post where we added code directly into the MainViewModel to use the Azure Active Directory Authentication Library. This would be fine if the MainViewModel was the only view model in the application that needed access to the Authenticate method. As I will probably want to make use of it elsewhere, I’ve decided to refactor that code into a class called CredentialService.
When I wired up MvvmCross a couple of posts ago, I did so without going into much detail on how the relationship between view models and their corresponding page is setup. I’m not going to delve into the inner workings of MvvmCross but suffice to say that there is some reflection magic that goes on based on the names of the classes. A view model with the name MainViewModel will be paired with a page called MainPage.
In addition to the magic that glues the view model and pages together (and thus the navigation model) MvvmCross also has a quite powerful dependency injection framework. The CredentialService that I’ll be creating will be registered with the DI framework as a singleton that can be easily accessed.
Let’s start by creating the CredentialService and it’s corresponding interface ICredentialService in a folder called Services in the Core library.
public partial class CredentialService:ICredentialService
{
private const string AuthEndpoint = “https://login.microsoftonline.com/{0}/oauth2/token”;
private const string ResourceId = “https://graph.windows.net/”;
private const string TenantId = “[your tenantId]”;
private const string ClientId = “[your clientId]”;
private const string RedirectURI = “[your redirectURI]”;
public string AccessToken { get; set; }
public async Task<string> Authenticate()
{
string authority = string.Format(CultureInfo.InvariantCulture, AuthEndpoint, TenantId);
var authContext = new AuthenticationContext(authority);
var result = await authContext.AcquireTokenAsync(ResourceId, ClientId, new Uri(RedirectURI), this.PlatformParameters);
AccessToken = result.AccessToken;
return AccessToken;
}
}public interface ICredentialService
{
Task<string> Authenticate();
}
The platform specific code will need to be extracted out of the MainViewModel.Platform.cs into the corresponding CredentialService.Platform.cs. For example the UWP class would be:
public partial class CredentialService
{
private IPlatformParameters PlatformParameters => new PlatformParameters(PromptBehavior.Always, false);
}
In order to register the CredentialService with the DI framework, we just need to add a small bit of code to the Initialize method of the App class in the Core library
public override void Initialize()
{
CreatableTypes()
.EndingWith(“Service”)
.AsInterfaces()
.RegisterAsLazySingleton();
RegisterAppStart<MainViewModel>();
}
The last step is to make use of the service in the MainViewModel. We do this by adding a parameter of type ICredentialService to the MainViewModel constructor.
private ICredentialService CredentialService { get; }
public MainViewModel(ICredentialService credentialService)
{
CredentialService = credentialService;
}
private async Task Authenticate()
{
Debug.WriteLine(await CredentialService.Authenticate());
}
And that’s it – we haven’t changed any functionality but the solution is better organised and structured in a way that services can easily be added without cluttering up view models.