title: flutter firebase auto refresh user session with refreshToken
body: <p>I want user in my app to stay logged in. I'm using the firebase authentification with IDToken which lasts for 1hour until it expires. I want to auto refresh the session everytime if it is going to expire.</p>
  <p>what Ive read so far here <a href="https://firebase.google.com/docs/reference/rest/auth/#section-refresh-token" rel="noreferrer">https://firebase.google.com/docs/reference/rest/auth/#section-refresh-token</a> it should be somehow possible with <code>https://securetoken.googleapis.com/v1/token?key=[API_KEY]</code></p>
  <p>This is my full code for authentification right now (flutter)</p>
  <pre><code>import 'dart:convert';
  import 'package:flutter/material.dart';
  import 'package:http/http.dart' as http;
  import '../provider/http_exception.dart';
  import 'dart:async';
  import 'package:shared_preferences/shared_preferences.dart';
  
  class Auth with ChangeNotifier {
    String _token;
    DateTime _expiryDate;
    String _userId;
    Timer _authTimer;
    bool wasLoggedOut = false;
    bool onBoarding = false;
  
    Future&lt;void&gt; createUser(String email, String firstName, String lastName) async {
      final url = 'https://test45.firebaseio.com/users/$userId.json?auth=$token';
      final response = await http.put(url, body: json.encode({
        'userEmail': email,
        'userIsArtist': false,
        'userFirstName': firstName,
        'userLastName': lastName,
      }));
      print('post ist done');
      print(json.decode(response.body));
    }
  
    bool get isAuth {
      return token != null;
    }
  
    String get userId {
      return _userId;
    }
  
    String get token {
      if (_expiryDate != null &amp;&amp;
          _expiryDate.isAfter(DateTime.now()) &amp;&amp;
          _token != null) {
        return _token;
      }
      return null;
    }
  
    Future&lt;void&gt; authenticate(
        String email, String password, String urlSegement) async {
      final url = 'https://identitytoolkit.googleapis.com/v1/accounts:$urlSegement?key=AIzaSyD8pb3M325252dfsDC-4535dfd';
  
      try {
        final response = await http.post(url,
            body: json.encode({
              'email': email,
              'password': password,
              'returnSecureToken': true,
            }));
        final responseData = json.decode(response.body);
        if (responseData['error'] != null) {
          throw HttpException(responseData['error']['message']);
        }
        _token = responseData['idToken'];
        _userId = responseData['localId'];
        _expiryDate = DateTime.now().add(Duration(seconds: int.parse(responseData['expiresIn'])));
        _autoLogout();
       
        notifyListeners();
  
        final prefs = await SharedPreferences.getInstance();
        final userData = json.encode({
          'token': _token,
          'userId': _userId,
          'expiryDate': _expiryDate.toIso8601String(),
        });
        prefs.setString('userData', userData);
      } catch (error) {
        throw error;
      }
    }
  
    Future&lt;void&gt; signup(String email, String password) async {
      return authenticate(email, password, 'signUp');
    }
  
    Future&lt;void&gt; signin(String email, String password) async {
      return authenticate(email, password, 'signInWithPassword');
    }
  
    Future&lt;bool&gt; tryAutoLogin() async {
      final prefs = await SharedPreferences.getInstance();
      if(!prefs.containsKey('userData')){
        return false;
      }
      final extractedUserData = json.decode(prefs.getString('userData')) as Map&lt;String, Object&gt;;
      final expiryDate = DateTime.parse(extractedUserData['expiryDate']);
  
      if(expiryDate.isBefore(DateTime.now())) {
        return false;
      }
  
      _token = extractedUserData['token'];
      _userId = extractedUserData['userId'];
      _expiryDate = expiryDate;
  
      notifyListeners();
      _autoLogout();
      return true;
    }
  
  
    Future&lt;void&gt; logout() async {
      _token = null;
      _userId = null;
      _expiryDate = null;
      if(_authTimer != null){
        _authTimer.cancel();
        _authTimer = null;
      }
      notifyListeners();
      final prefs = await SharedPreferences.getInstance();
      prefs.remove('userData');
    }
  
    void _autoLogout() {
      if(_authTimer != null) {
        _authTimer.cancel();
      }
    final timetoExpiry =  _expiryDate.difference(DateTime.now()).inSeconds;
      _authTimer = Timer(Duration(seconds: timetoExpiry), logout);
    }
  }
  </code></pre>
  <p>how to modify my <code>auth.dart</code> to achieve the auto refreshing?</p>
  <p>EDIT:</p>
  <p>As mentioned in the comments, im working with providers where I have the following functions to retrieve the token:</p>
  <pre><code>update(String token, id, List&lt;items&gt; itemsList) {
      authToken = token;
      userId = id;
    }
  </code></pre>
  <p>also in every of my API calls im using the auth parameter already:</p>
  <pre><code>var url = 'https://test45.firebaseio.com/folder/$inside/$ym.json?auth=$authToken';
  </code></pre>
  <p>I just need somebody who can show me how to modify my code with the refresh token.</p>
  <p>Thanks in advance!</p>
  <p>EDIT:</p>
  <p>I tried to implement it, but im getting an infinite loop, please help:</p>
  <pre><code>String get token {
      if (_expiryDate != null &amp;&amp;
          _expiryDate.isAfter(DateTime.now()) &amp;&amp;
          _token != null) {
        return _token;
      }
      refreshSession();
    }
  
    Future&lt;void&gt; refreshSession() async {
          final url = 'https://securetoken.googleapis.com/v1/token?key=5437fdjskfsdk38438?grant_type=refresh_token?auth=$token';
        
        try {
        final response = await http.post(url,
            body: json.encode({
    'token_type': 'Bearer',
            }));
        final responseData = json.decode(response.body);
        if (responseData['error'] != null) {
          throw HttpException(responseData['error']['message']);
        }
        _token = responseData['id_token'];
        _userId = responseData['user_id'];
        _expiryDate = DateTime.now().add(Duration(seconds: int.parse(responseData['expires_in'])));
        _autoLogout();
       
        notifyListeners();
  
        final prefs = await SharedPreferences.getInstance();
        final userData = json.encode({
          'token': _token,
          'userId': _userId,
          'expiryDate': _expiryDate.toIso8601String(),
        });
        prefs.setString('userData', userData);
      } catch (error) {
        throw error;
      }
        }
  </code></pre>