Fitbit Authentication in Xamarin using WebAuthenticator

Vipin Johney
5 min readAug 30, 2020

--

This is, I hope, will be the first article among a series, which explains various implementations in Xamarin Forms.

I assume you know the basics of Xamarin Forms development and basic understanding on how OAuth works. We will be using ‘WebAuthenticator’ which is part of Xamarin.Essentials package link for showing Fitbit login screen to user.

Just a note on steps Fitbit follows. First implement the login and on successful login we get code as response. This code is used to fetch access token, refresh token and few other details. Once token details is received, we can use those to fetch any data which was approved by the user during login. The scopes are listed here link.

First Part — Fitbit developer account registration

Fitbit development page https://dev.fitbit.com/apps/new . Main parts in the page are OAuth 2.0 Application Type, which is client and Callback URL which should be unique follow a format as displayed in the image.

Second Part — Xamarin Development

Create a Xamarin Forms project with Android and iOS support. Here is the link to complete project in GitHub which helps you understand this tutorial.

1 . Add required packages

Once your project is ready add the packages missing from below list

  • Xamarin.Essentials
  • Newtonsoft.Json
  • RestSharp

2 . Have all the details from Fitbit in your project

Now we need to have all the details of our app registered at Fitbit developer site in our app for using at various steps.

public class FitbitConfiguration
{
// Fitbit
public const string ClientId = "{client_id}";
public const string ClientSecret = "{client_secret}";
public const string Callback = "com.vipxam.webauthenticator-12345://callback";
public const string CallbackExcaped = "com.vipxam.webauthenticator-12345%3A%2F%2Fcallback";
public const string CallbackScheme = "com.vipxam.webauthenticator-652145";
public const string Auth2Url = "https://www.fitbit.com/oauth2/authorize?";
public const string ScopesEscaped = "activity%20profile";
public const string ExpireIn = "604800";
}

3 . iOS specific setup

Open info.plist and add URL Types as shown in the image. The URL schemes has to be same as the base part of your callback url.

After that open AppDelegate class and override OpenUrl

public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options)
{
if (Xamarin.Essentials.Platform.OpenUrl(app, url, options))
{
return true;
}
return base.OpenUrl(app, url, options);
}

4 . Android specific setup

Add the following class to Android project

[Activity(NoHistory = true, LaunchMode = LaunchMode.SingleTop)]
[IntentFilter(new[] { Android.Content.Intent.ActionView },
Categories = new[] { Android.Content.Intent.CategoryDefault, Android.Content.Intent.CategoryBrowsable },
DataScheme = FitbitConfiguration.CallbackScheme)]
public class WebAuthenticationCallbackActivity : Xamarin.Essentials.WebAuthenticatorCallbackActivity
{
protected override void OnResume()
{
base.OnResume();
Xamarin.Essentials.Platform.OnResume();
}

}

5 . Implement Fitbit login

With all dependencies and requirement now in place, we can get started with the OAuth. As I had mentioned earlier, we will be using WebAuthenticator for showing the login screen.

Login Url which need to passed on to WebAuthenticator will be created based on you registered app details which we have already have in the project. This is an important part so make sure you are creating a valid url.

public static string BuildAuthenticationUrl()
{
return $"{FitbitConfiguration.Auth2Url}" +
$"response_type=code" +
$"&client_id={FitbitConfiguration.ClientId}" +
$"&redirect_uri={FitbitConfiguration.CallbackExcaped}" +
$"&scope={FitbitConfiguration.ScopesEscaped}" +
$"&expires_in={FitbitConfiguration.ExpireIn}";
}

Next is passing the login url and callback url on to WebAuthenticator

var callbackUrl = new Uri(FitbitConfiguration.Callback);                var loginUrl = new Uri(FitbitServices.BuildAuthenticationUrl());                var authenticationResult = await WebAuthenticator.AuthenticateAsync(loginUrl, callbackUrl);var code = authenticationResult.Properties["code"];              code = code.Replace("#_=_", "");

WebAuthenticator.AuthenticateAsync will invoke the login in a browser page and once user logs in, the result is returned back.

Make sure you are passing the url details correctly. If you face any issue here go to your app page in Fitbit and you find the link to ‘OAuth 2.0 tutorial page and click on it. Fitbit will show you how the login url looks like here.

On successful login we get a response which contains a code. Code is followed by ‘#_=_’ which need to be removed and this is used for fetching token.

6 . Fetch Access token

From now on everything is API calls. You can get list of APIs supported from Fitbit page here. Below is the sample for reference, incase you use some other library instead of RestSharp just make sure to pass all required items.

Here we fetch the access token.

var client = new RestClient("https://api.fitbit.com/oauth2/token")
{
Timeout = -1
};
var _authorization = "Basic " + FitbitServices.Base64String();var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", _authorization);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", FitbitConfiguration.GrantType);
request.AddParameter("clientId", FitbitConfiguration.ClientId);
request.AddParameter("redirect_uri", FitbitConfiguration.Callback);
request.AddParameter("code", code);
IRestResponse response = await client.ExecuteAsync(request);

Value in _authorization variable is the base64 string of client_id and client_secret concatenated with a colon (:) between them.

Response of this request will look like below with actual values against fields. You will need to save this till user revokes tokens.

{
"access_token": “{access_token}”,
"expires_in": 28800,
"refresh_token": “{refresh_token}”,
"scope": "profile activity",
"token_type": "Bearer",
"user_id": “{user_id}”
}

7 . Fetch User Profile

In order to fetch user profile we will need only 1 thing, the access token from above response. ‘user_id’ is part of that access token so you don’t have to pass anything else to identify the user.

var requestUri = "https://api.fitbit.com/1/user/-/profile.json";
var client = new RestClient(requestUri)
{
Timeout = -1
};
var request = new RestRequest(Method.GET);var bearerToken = "Bearer " + accessToken;
request.AddHeader("Authorization", bearerToken);
IRestResponse response = await client.ExecuteAsync(request);
Console.WriteLine(response.Content);

8 . Fetch Activity

Other than user details we also needed daily activity. Code is same as in the previous, but URL changes to as show below. Here user_id need to be passed with the request. The other item which need to be passed is the activity date.

var requestUri = "https://api.fitbit.com/1/user/" + userId + "/activities/date/" + date + ".json";

Date format is yyyy-MM-dd.

9 . Other APIs

Fitbit API page will have information on what need to be passed for getting respective details.

10 . Conclusion

There is an expiry time for the access token and once it expires you will need to request another.

Hope this tutorial helps someone. I know there are lot of improvements required for my writing. Hoping it will improve as I start adding more like this. Please do let know your thoughts in comments.

Logo and images used are sole property of respective owners. All rights/credits reserved to respective owner.

--

--