Chilkat Online Tools

Obtain Fitbit OAuth2 Access Token

This tool demonstrates how to get a Fitbit OAuth2 access token using three-legged OAuth2 in an ASP.NET application. This is also known as the "authorization code grant flow". This is when your ASP.NET app acts on the behalf of a third-party user, your app must obtain the user's permission before it can make requests that access and update that third-party's confidential resources. A User access token carries a third-party's authorization to access specific resources, and this type of token is obtained through the authorization code grant flow.

The C# Source Code for this Page

             
@{

    Layout = "~/_LayoutPage1.cshtml";
}

@functions {

    // Exchange the authorization code for an access token returned in jsonToken.
    private static bool ExchangeCodeForToken(string url, string clientId, string clientSecret, string code, string redirectUri, Chilkat.JsonObject jsonToken)
    {
        Chilkat.Http http = new Chilkat.Http();
        http.Login = clientId;
        http.Password = clientSecret;

        Chilkat.HttpRequest req = new Chilkat.HttpRequest();
        req.AddParam("code", code);
        req.AddParam("grant_type", "authorization_code");
        req.AddParam("redirect_uri", redirectUri);

        Chilkat.HttpResponse resp = http.PostUrlEncoded(url, req);
        if (resp == null) return false;
        jsonToken.Load(resp.BodyStr);
        return (resp.StatusCode == 200) && jsonToken.HasMember("access_token");
    }

}

@{
    Chilkat.Global glob = new Chilkat.Global();
    string unlockCode = "<unlockCode>Anything for 30-day trial</unlockCode>";
    glob.UnlockBundle(unlockCode.Replace("<unlockCode>", "").Replace("</unlockCode>", ""));

    string access_token = "";
    string state = "";
    string redirect_uri = "https://tools.chilkat.io/fitbit_oauth2.cshtml";
    string clientId = "22CHH4";
    string clientSecret ="<secret>CLIENT_SECRET</secret>";
    Chilkat.JsonObject jsonAccessToken = new Chilkat.JsonObject();


    // Check to see if this is our redirect containing the access token.
    if (!string.IsNullOrEmpty(Request.Params["state"]))
    {
        state = Request["state"];

        // Make sure this is the redirect for our session.
        if (!state.Equals(Session["oauth2_state"]))
        {
            access_token = "invalid_state";
        }
        else if (!string.IsNullOrEmpty(Request.Params["code"]))
        {
            string authorizationCode = Request["code"];

            clientSecret = clientSecret.Replace("<secret>", "").Replace("</secret>", "");
            if (ExchangeCodeForToken("https://api.fitbit.com/oauth2/token", clientId, clientSecret, authorizationCode, redirect_uri, jsonAccessToken))
            {
                access_token = jsonAccessToken.StringOf("access_token");
            }
            else
            {
                jsonAccessToken.EmitCompact = false;
                access_token = jsonAccessToken.Emit();
            }

        }
    }
}

@{

    Chilkat.HttpRequest req = new Chilkat.HttpRequest();
    req.AddParam("client_id", clientId);
    req.AddParam("redirect_uri", redirect_uri);
    req.AddParam("response_type", "code");
    req.AddParam("scope", "profile activity");
    string stateData = "12345678";  // Replace this with random data..
    req.AddParam("state", stateData);
    Session["oauth2_state"] = stateData;

    string auth_url = "https://www.fitbit.com/oauth2/authorize?" + req.GetUrlEncodedParams();

}

<div class="container">
    <h2>Obtain Fitbit OAuth2 Access Token</h2>
    <p>
        This tool demonstrates how to get a Fitbit OAuth2 access token using
        three-legged OAuth2 in an ASP.NET application.  This is also known as the "authorization code grant flow".
        This is when your ASP.NET app acts on the behalf of a third-party user, your app must obtain the user's permission
        before it can make requests that access and update that third-party's confidential resources. A User access token carries
        a third-party's authorization to access specific resources, and this type of token is obtained through the authorization code grant flow.
    </p>
    <div class="panel panel-default">
        <div class="panel-body">
            <a href="@auth_url" class="btn btn-primary" role="button">Begin OAuth2</a>
        </div>
    </div>
    <div class="panel panel-default">
        @{
            if (!string.IsNullOrEmpty(access_token))
            {
                @:<p><b>Fitbit access token:</b> @access_token</p>
            }
            if (!string.IsNullOrEmpty(state))
            {
                @:<p>state: @state</p>
            }
        }
    </div>

    <div class="panel panel-default">
        <h2>The C# Source Code for this Page</h2>
        <pre>
        @{ 
            Chilkat.FileAccess fac = new Chilkat.FileAccess();
            string path = Server.MapPath("~/fitbit_oauth2.cshtml");
            string src = fac.ReadEntireTextFile(path,"utf-8");
            Chilkat.StringBuilder sbTemp = new Chilkat.StringBuilder();
            sbTemp.Append(src);
            sbTemp.ReplaceAllBetween("<secret>", "</secret>", "CLIENT_SECRET", false);
            sbTemp.ReplaceAllBetween("<unlockCode>", "</unlockCode>", "Anything for 30-day trial", false);
            src = sbTemp.GetAsString();
            @: @src
        }
        </pre>
    </div>
</div>