Authenticating Users with an Identity Provider

Using the Xamarin.Auth component for authentication

PDF for offline use
Sample Code:
Related Articles:
Related SDKs:

Let us know how you feel about this


0/250

last updated: 2017-02

Xamarin.Auth is a cross-platform SDK for authenticating users and storing their accounts. It includes OAuth authenticators that provide support for consuming identity providers such as Google, Microsoft, Facebook, and Twitter. This article explains how to use Xamarin.Auth to manage the authentication process in a Xamarin.Forms application.

OAuth is an open standard for authentication, and enables a resource owner to notify a resource provider that permission should be granted to a third party in order to access their information without sharing the resource owners identity. An example of this would be enabling a user to notify an identity provider (such as Google, Microsoft, Facebook, or Twitter) that permission should be granted to an application to access their data, without sharing the users identity. It is commonly used as an approach for users to login to websites and applications using an identity provider, but without exposing their password to the website or application.

Xamarin.Auth is a cross-platform API for authenticating users and storing their accounts. It includes OAuth authenticators that provide support for consuming identity providers such as Google, Microsoft, Facebook, and Twitter. The authentication flow when consuming an OAuth identity provider is as follows:

  1. The application redirects a browser to an identity provider URL. The URL query parameters indicate the type of access being requested.
  2. The identity provider handles user authentication, and returns an authorization code to the application.
  3. The application exchanges the authorization code, client ID, and client secret for an access token from the identity provider.
  4. The application uses the access token to access APIs on the identity provider, such as requesting basic user data.

The application uses the OAuth2Authenticator and OAuth2Request classes, provided by Xamarin.Auth, to implement the application side of the authentication flow.

While Google is used as the identity provider in this topic, the approach is equally applicable to other identity providers. For more information about authentication using Google's OAuth 2.0 endpoint, see Using OAuth2.0 to Access Google APIs on Google's website.

In iOS 9 and greater, App Transport Security (ATS) enforces secure connections between internet resources (such as the app's back-end server) and the app, thereby preventing accidental disclosure of sensitive information. Since ATS is enabled by default in apps built for iOS 9, all connections will be subject to ATS security requirements. If connections do not meet these requirements, they will fail with an exception.

ATS can be opted out of if it is not possible to use the HTTPS protocol and secure communication for internet resources. This can be achieved by updating the app's Info.plist file. For more information see App Transport Security.

Using Xamarin.Auth to Authenticate Users

A high-level overview of how the application uses Xamarin.Auth to authenticate users and retrieve their basic data is shown in the following diagram:

The application requests an access token from Google using the OAuth2Authenticator class. An access token is returned once the user is successfully authenticated with Google through their login page. The application then uses the access token to sign the request to Google for basic user data. This request is made with the OAuth2Request class.

Creating and Configuring an Authenticator

The OAuth2Authenticator class is responsible for communicating with authentication services. The following code example shows the instantiation of the OAuth2Authenticator class:

var auth = new OAuth2Authenticator(
  Constants.ClientId,
  Constants.ClientSecret,
  Constants.Scope,
  new Uri (Constants.AuthorizeUrl),
  new Uri (Constants.RedirectUrl),
  new Uri (Constants.AccessTokenUrl));

The OAuth2Authenticator class requires a number of parameters, as shown in the following list:

  • Client ID – this identifies the client that is making the request.
  • Client Secret – this identifies the client that is making the request.
  • Scope – this identifies the API access being requested by the application, and the value informs the consent screen that is shown to the user. For more information about scopes, see Authorizing API request on Google's website.
  • Authorize URL – this identifies the URL where the authorization code will be obtained from.
  • Redirect URL – this identifies the URL where the response will be sent. The value of this parameter must match one of the values that appears in the Credentials page for the project in the Google Developers Console.
  • AccessToken Url — this identifies the URL used to request access tokens after an authorization code is obtained.

Authenticating the User

The login screen in the sample application is shown below:

While Google is used as the identity provider, a variety of other identity providers can be used, including Facebook, Microsoft, and Twitter.

Xamarin.Auth defines the following mechanism for presenting the authentication UI to the user:

  1. Each platform project should implement a class to display the authentication UI.
  2. Each platform project registers the class with Xamarin.Auth's PlatformLogin Action, when the application starts.
  3. The Portable Class Library (PCL) invokes authentication by creating a new Xamarin.Auth.Presenters.OAuthLoginPresenter object, and invoking the object's Login method.

The following code example shows the OAuthLoginPresenter class, which displays the authentication UI on the iOS platform:

public class OAuthLoginPresenter
{
  UIViewController rootViewController;

  public void Login(Authenticator authenticator)
  {
    authenticator.Completed += AuthenticatorCompleted;

    rootViewController = UIApplication.SharedApplication.KeyWindow.RootViewController;
    rootViewController.PresentViewController(authenticator.GetUI(), true, null);
  }

  void AuthenticatorCompleted(object sender, AuthenticatorCompletedEventArgs e)
  {
    rootViewController.DismissViewController(true, null);
    ((Authenticator)sender).Completed -= AuthenticatorCompleted;
  }
}

The following code example shows the OAuthLoginPresenter class, which displays the authentication UI on the Android platform:

public class OAuthLoginPresenter
{
  public void Login(Authenticator authenticator)
  {
    Xamarin.Forms.Forms.Context.StartActivity(authenticator.GetUI(Xamarin.Forms.Forms.Context));
  }
}

Each platform project must register the OAuthLoginPresenter class with Xamarin.Auth's PlatformLogin Action, when the application starts, as shown in the following code example:

Xamarin.Auth.Presenters.OAuthLoginPresenter.PlatformLogin = (authenticator) =>
{
  var oAuthLogin = new OAuthLoginPresenter();
  oAuthLogin.Login(authenticator);
};

The Portable Class Library (PCL) can then invoke the login presenter as follows:

var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
presenter.Login(auth);

The argument to the Login method is the OAuth2Authenticator instance.

Note that an event handler for the Completed event must be registered before presenting the UI. This event will fire when the user successfully authenticates or cancels the login. The login can be cancelled by pressing the Cancel button in iOS or by pressing the Back button in Android, in which case the user remains unauthenticated and the identity provider UI is removed from the screen.

In the event handler the AuthenticatorCompletedEventArgs.IsAuthenticated property identifies whether authentication succeeded, as shown in the following code example:

async void OnAuthCompleted (object sender, AuthenticatorCompletedEventArgs e)
{
  ...
  if (e.IsAuthenticated) {
    ...
  }
}

The data gathered from a successful authentication is available in the AuthenticatorCompletedEventArgs.Account property. The result of a successful OAuth2 authentication is an access token, which can then be used to sign requests for data to an API.

Making Requests for Data

After the application obtains an access token, it is used to make a request to the https://www.googleapis.com/oauth2/v2/userinfo API, in order to request basic user data from the identity provider on behalf of the user. This request is made with the OAuth2Request class, which represents a request that is authenticated using an account retrieved from an OAuth2Authenticator instance, as shown in the following code example:

// UserInfoUrl = https://www.googleapis.com/oauth2/v2/userinfo
var request = new OAuth2Request ("GET", new Uri (Constants.UserInfoUrl), null, e.Account);
var response = await request.GetResponseAsync ();
if (response != null)
{
  string userJson = response.GetResponseText ();
  App.User = JsonConvert.DeserializeObject<User> (userJson);
}

As well as the HTTP method and API URL, the OAuth2Request instance also specifies an Account instance that contains the access token that signs the request to the URL specified by the Constants.UserInfoUrl property. The identity provider then returns basic user data as a JSON response, including the users' name and email address, provided that it recognizes the access token as being valid. The JSON response is then read and deserialized into the App.User property.

For more information, see Calling a Google API on Google's website.

Storing and Retrieving Account Information on Devices

Xamarin.Auth securely stores Account objects in an account store so that applications do not always have to re-authenticate users. The AccountStore class is responsible for storing account information, and is backed by Keychain services in iOS, and the KeyStore class in Android.

The following code example shows how an Account object is securely saved:

AccountStore.Create ().Save (e.Account, Constants.AppName);

Saved accounts are uniquely identified using a key composed of the account's Username property and a service ID, which is a string that is used when fetching accounts from the account store. If an Account was previously saved, calling the Save method again will overwrite it.

Account objects for a service can be retrieved by calling the FindAccountsForService method, as shown in the following code example:

var account = AccountStore.Create ().FindAccountsForService (Constants.AppName).FirstOrDefault();

The FindAccountsForService method returns an IEnumerable collection of Account objects, with the first item in the collection being set as the matched account.

Summary

This article explained how to use the Xamarin.Auth SDK to manage the authentication process in a Xamarin.Forms application. This SDK provides the OAuth2Authenticator and OAuth2Request classes that are used by Xamarin.Forms applications to consume identity providers such as Google, Microsoft, Facebook, and Twitter.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.