Search code examples
angularoauthangular7fitbit

Using OAuth 2.0 with angular 7


I am trying to use the FitBit Web API. Before accessing the API, I have to use the OAuth2.0 framework. So from the FitBit API Documentation Page, there is an example that is:

https://www.fitbit.com/oauth2/authorize?response_type=code&client_id=22942C&redirect_uri=http%3A%2F%2Fexample.com%2Ffitbit_auth&scope=activity%20nutrition%20heartrate%20location%20nutrition%20profile%20settings%20sleep%20social%20weight

The first question is: Should I use GET or POST method? The information needed is located inside the URL created, so my intuition says I should use GET.

When using GET method, the response is weird. I expect some kinf of code so I can use in the next API call that will get the actual measurements. The call I am trying to make is:

this.http.get('https://api.fitbit.com/1/user/userID/activities/heart/date/today/1d.json')

but I do not know exactly how to use the token, the OAuth2.0 process does NOT return.

Sorry for the long question, but any ideas?


Solution

  • "When using GET method, the response is weird"

    The response is HTML because you have made a GET request to their authentication portal. What you are supposed to do is actually redirect the user to the url:

    https://www.fitbit.com/oauth2/authorize?response_type=code&client_id=22942C&redirect_uri=http%3A%2F%2Fexample.com%2Ffitbit_auth&scope=activity%20nutrition%20heartrate%20location%20nutrition%20profile%20settings%20sleep%20social%20weight
    

    ...and then in the url replace the redirect_uri param with a link to your site (or localhost if you are in dev).

    After the user has authenticated with Fitbit and allowed access to your app fitbit will redirect the user to the url provided along with an access_token. See doc

    {
        "access_token": "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0MzAzNDM3MzUsInNjb3BlcyI6Indwcm8gd2xvYyB3bnV0IHdzbGUgd3NldCB3aHIgd3dlaSB3YWN0IHdzb2MiLCJzdWIiOiJBQkNERUYiLCJhdWQiOiJJSktMTU4iLCJpc3MiOiJGaXRiaXQiLCJ0eXAiOiJhY2Nlc3NfdG9rZW4iLCJpYXQiOjE0MzAzNDAxMzV9.z0VHrIEzjsBnjiNMBey6wtu26yHTnSWz_qlqoEpUlpc",
        "expires_in": 3600,
        "refresh_token": "c643a63c072f0f05478e9d18b991db80ef6061e4f8e6c822d83fed53e5fafdd7",
        "token_type": "Bearer",
        "user_id": "26FWFL"
    }
    

    You can then use this access token to make future requests.