Configure a personalized expiration time for expo-auth-session in order to interact with the Fitbit API using the React Native framework in Expo

Is it possible to customize the expiration time for Fitbit implicit auth flow? The default time is set to one day, but I would like to extend it to one year. If you are using the web version, you can modify the expires_in parameter directly in the URL.
Here is an example URL that demonstrates this:

WebBrowser.maybeCompleteAuthSession();

const useProxy = Platform.select({ web: false, default: true });
// Endpoint
const discovery = {
  authorizationEndpoint: 'https://www.fitbit.com/oauth2/authorize',
  tokenEndpoint: 'https://api.fitbit.com/oauth2/token',
  revocationEndpoint: 'https://api.fitbit.com/oauth2/revoke',
};

  const [request, response, promptAsync] = useAuthRequest(
    {
      responseType: ResponseType.Token,
      clientId: 'randomid',
      scopes: ['activity', 'profile'],
      redirectUri: makeRedirectUri({
        useProxy,
        scheme: 'nudge://',
      }),
    },
    discovery
  );

  const loginFitbit = async (token) => {
    if (token) {
      try {
        await signInFitbit(token, dispatch);
        await storeFitbitToken(token);
        setLoggedIn(true);
      } catch (e) {
        setLoggedIn(false);
        addError('Could not login Fitbit. Please try agian later.');
      }
    }
  };

  React.useEffect(() => {
    if (response?.type === 'success') {
      const { access_token } = response.params;
      console.log("res",response)
      loginFitbit(access_token);
    } else {
      console.log('error', response);
    }
  }, [response]);


  React.useEffect(() => {
    const fetchData = async () => {
      let token;
      try {
        token = await getFitbitToken();
        setLoggedIn(true);
      } catch (e) {
        setLoggedIn(false);
        console.error(e);
      }
      dispatch({ type: 'RESTORE_FITBIT_TOKEN', token: token });
    };

    fetchData();
  }, [dispatch])

Answer №1

For applications using the Authorization Code Grant Flow, access tokens automatically expire after 8 hours (28800 seconds) and cannot be adjusted.

If you want users to have control over how long your application can access their data, you will need to switch to the Implicit Grant Flow. This allows users to choose the duration of consent they give to your application (1 day, 1 week, 30 days, or 1 year).

More information can be found at:

Answer №2

To include additional query parameters in your authentication request, you must include an extraParams object with your personalized fields.

const [request, response, promptAsync] = useAuthRequest(
  {
    responseType: ResponseType.Token,
    clientId: "uniqueid",
    scopes: ["activity", "profile"],
    redirectUri: makeRedirectUri({
      useProxy,
      scheme: "nudge://",
    }),
    extraParams: {
      expires_in: 3600, // <--- customized value
    },
  },
  discovery
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Working with JSON data in javascript

While trying to parse JSON data from a server, I came across a strange issue. The data consists of rows of data - essentially a list of lists - and it looks something like this: [[1,2,3],[4,5,6],[7,8,9]] When viewing the JSON data in FF (using Firebug), ...

Looking to retrieve selections when the inputValue changes in react-select?

I'm working with a react-select component and I would like to implement a feature where an API request is triggered as soon as the user starts typing in the react-select field. This request should fetch items related to the keyword entered by the user ...

update of the camera's close-range capabilities

Is there a way to adjust the near and far parameters of the camera without having to recreate it? I've noticed that the camera stops displaying objects when I attempt to make changes to these parameters. In some cases, it results in a black screen, ...

Troubleshooting: Angular CLI project encountering issues on Internet Explorer

Today, I encountered an issue when attempting to create a new project using the Angular CLI. An exception is thrown on IE11 and the console displays the following error message: SCRIPT5007: Unable to get property 'call' of undefined or null ref ...

Tips for Using AJAX and JavaScript to Save an XML File

My current task involves attempting to insert an element into an XML file. Upon inspecting the program with a debugger, I noticed that the element is successfully added to the XML file. However, when I stop the program from running, the changes are not sav ...

What is the best way to create a React text box that exclusively accepts numeric values or remains empty, and automatically displays the number keypad on mobile devices?

While there are numerous similar questions on StackOverflow, none of them fully address all of my requirements in a single solution. Any assistance would be greatly appreciated. The Issue at Hand Within my React application, I am in need of a text box tha ...

Redux state not reflecting changes until second click

My redux store has a simple boolean setup to track whether a sidebar is expanded or not. However, I'm encountering an issue where, even though the default value is false, clicking the toggle button outputs false first. Ideally, if it's initially ...

Remove the innerHTML content of dynamically added elements using jQuery

After researching, it seems that event handlers are commonly added using methods such as .live(), .on(), .bind(), or .delegate(). My previous question may not have been clear, so I decided to delete it and ask a simpler one. Is there a way to clear the in ...

MUI Autocomplete causing a never-ending cycle of requests

One of the challenges I'm facing involves an Autocomplete component in my code. Here's a snippet of the code: <Autocomplete filterOptions={(x) => x} options={items} getOptionLabel= ...

The use of ExpressJs res.sendFile is not effective following the implementation of middleware

Currently, my focus is on mastering JWT and its implementation in Node.js with Express. I've developed a middleware that aims to authenticate users using a token: app.use(function(req, res, next) { if(req.headers.cookie) { var authentication = req.h ...

The checkbox is not being triggered when an <a> tag is placed within a <label>

I have a unique case where I need to incorporate <a> within a <label> tag. This is due to the fact that various CSS styles in our current system are specifically designed for <a> elements. The <a> tag serves a purpose of styling and ...

Modifying paragraph content with JavaScript based on selected radio button values and troubleshooting the onclick event not triggering

I am working on implementing a language selection feature on my website where users can choose between English and Spanish. The idea is to have two radio buttons, one for each language, and a button. When the button is clicked, the text of the paragraphs s ...

Insert a Facebook like button within a designated div

Can anyone figure out why the Facebook button isn't functioning properly? ---- ...

Having difficulty accessing a function within the SignalR connection function

I am currently facing an issue while trying to access a specific function within a SignalR connection function. Below is the code snippet showcasing the entire script for better understanding: $(function() { var chat = $.connection.chatHub; chat.c ...

Column Reordering in DataTable Causes Data to be Mapped Incorrectly

I have created a JSBin where you can view the code. However, due to CORS policy restrictions, the ajax URL I used is not functioning properly. The output generated shows that the data is mapped incorrectly in the columns. Can someone please help me figure ...

What is the best way to incorporate a formArray into a formGroup?

Before anything else, I want to apologize for any errors in my English. I seem to be having trouble adding an array field to a formGroup. My issue arises when attempting to use the push method to add a formArray to my rate formGroup. It appears that the ...

Guide to making a sliding animation appear when hovering over a menu using jQuery

I have noticed a common feature on many websites, but I am unsure of how to explain it. At times, there are sliding elements in the navigation, like an arrow under menu items that moves when the user hovers over different links. Here is an example of a s ...

Is there a concept in JavaScript that includes a data structure called a "matrix" with elements arranged in a grid-like format accessed by

I'm not familiar with the terminology, but I'd like to simplify it: var topicList1 =['hello','hallo', ..., 'hej']; var topicList2 =['a','b',...,'c']; ... var topicList999 =['x,&apo ...

Instructions on how to eliminate the minutes button from Material UI datetime picker

I'm currently working on customizing a datetimepicker from materialUI in ReactJS. My goal is to prevent the user from seeing or selecting minutes in the picker interface. Despite setting the views prop to include only year, month, date, and hours, use ...

How can I display components using Angular CLI 5 without any visual output?

The index.html page is not displaying anything, not even the "App works" message that should appear in a basic initial project ng --version Angular CLI: 1.6.0 Node: 8.9.1 OS: darwin x64 Angular: 5.1.0 ... animations, common, compiler, compiler-cli, core, ...