Search code examples
oauthfitbit

FitBit - Authenticate on behalf of user


In short we don't want our clients to authenticate each time that they log in to the site and want to sync their Fitbit data on our website.

We want them to authenticate once, and then save the tokens and use that to automatically sync the data. I can't seem to get the authorization to work. I'm using .Net.

Here is my code, but keeps getting 401 - Unauthorized

:

string consumerKey = "KEY";
        string authToken = "TOKEN";
        string secrectKey = "SECRET"; 

        string baseUrl = "http://api.fitbit.com/1/user/-/profile.xml";
        string auth_nonce = DateTime.Now.Ticks.ToString();
        string timestamp = ( ( Int32 )( DateTime.UtcNow.Subtract( new DateTime( 1970, 1, 1 ) ) ).TotalSeconds ).ToString();
        string signingKey = string.Empty;
        string authSignature = string.Empty;


        string parameters = "oauth_consumer_key=" + consumerKey + "&oauth_nonce=" + auth_nonce + "&oauth_signature_method=HMAC-SHA1&oauth_timestamp=" + timestamp + "&oauth_token=" + authToken + "&oauth_version=1.0";


        //1. percent encode
        parameters = HttpUtility.UrlEncode( parameters );

        //encode baseURL
        baseUrl = HttpUtility.UrlEncode( baseUrl );

        //add POST
        //signature base string
        parameters = "GET&" + baseUrl + "&" + parameters;

        //signing key
        signingKey = secrectKey + "&" + authToken;


        //generate key
        //base64 signature srting
        authSignature = Convert.ToBase64String( Generate( signingKey, parameters ) );

        //url for request
        WebRequest g = HttpWebRequest.Create( "http://api.fitbit.com/1/user/-/profile.xml" );

        //add headers
        g.Headers.Add( HttpRequestHeader.Authorization, "OAuth realm=\"api.fitbit.com\" oauth_token=\"" + authToken + "\", oauth_consumer_key=\"" + consumerKey + "\", oauth_nonce=\"" + auth_nonce + "\",  oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"" + timestamp + "\", oauth_version=\"1.0\", oauth_signature=\"" + authSignature.Replace( "=", "%3D" ) + "\"" );

        //get response from server
        var response = g.GetResponse();

Does anyone have a sample code or can see where the issue is?

Kind Regards


Solution

  • I wrote something similar for our office's internal fitbit league

    The code is here on github NewOrbit Fitbit League

    It uses Azure table storage as it's backing store to keep the tokens but you should be able to change it based on your needs, it also supports users using the Move app

    [Edit] I also used Fitbit.net as the client library