Expo - React Native: How to read User data from Google Fit API

1.2k Views Asked by At

thanks in advance for any assistance that can be provided. My goal is to use OAuth2 to get users’ step data from the Google Fit API. I am able to authenticate using Expo's expo-app-auth package, and receive an accessToken, but, when I try to read from the Fit API, I get an error that the authentication credential is missing.

Relevant Code:

let config = {
  issuer: 'https://accounts.google.com',
  scopes: ['openid', 'profile', 'https://www.googleapis.com/auth/fitness.activity.read'],
  /* This is the CLIENT_ID generated from a Firebase project */
  clientId: 'xxx.apps.googleusercontent.com',
};

let authState = await AppAuth.authAsync(config); // this returns an idToken, accessToken, list of scopes configured, including the fitness.activity.read

const url = 'https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate';
const today = new Date().getTime();
const past = today - (5 * 24 * 60 * 60 * 100);
const body = {
  "aggregateBy": [{
    "dataTypeName": "com.google.step_count.delta",
    "dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps"
  }],
  "bucketByTime": { "durationMillis": 86400000 },
  "startTimeMillis": today,
  "endTimeMillis": past
}

const header = {
  'Content-Type': 'application/json',
  'Authorization': `BEARER ${authState.accessToken}`
}

const req = await fetch(url, {
  method: 'POST',
  headers: header,
  body: JSON.stringify(body)
});

const resp = await req.json();
/*
Object {
  "error": Object {
    "code": 401,
    "errors": Array [
      Object {
        "domain": "global",
        "location": "Authorization",
        "locationType": "header",
        "message": "Login Required.",
        "reason": "required",
      },
    ],
    "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED",
  },
}
*/


I am able to produce this issue using a built apk on a real device. For the standalone build, I am using an OAuth2 clientId from Google Console as clientId in the config, and the Fitness API is enabled.

Does anyone know what I might be doing incorrectly?

0

There are 0 best solutions below