refreshNoContext method

Future<CarpUser> refreshNoContext()

Get a new access token for the current user based on the previously granted refresh token, using the Identity Server discovery URL. Need to have run any of the authenticate functions first.

Use only if you know what you are doing! This method is used only if the refresh method does not work for you, i.e. you do not have access to a BuildContext. Use this if you used authenticateWithUsernamePasswordNoContext to authenticate.

This method uses a POST request to the Identity Server to get an access token. The discovery URL is used to find the Identity Server.

This method is typically used when the access token has expired, and a new access token is needed to access the CARP web service. The refresh token expiration date is OAuthToken.expiresAt, as a DateTime.

Returns the signed in user (with a new OAuthToken access token), if successful. Throws a CarpServiceException if not successful.

Implementation

Future<CarpUser> refreshNoContext() async {
  final url = app.authURL.replace(pathSegments: [
    ...app.authURL.pathSegments,
    'protocol',
    'openid-connect',
    'token',
  ]);

  final body = {
    'client_id': app.clientId,
    'client_secret': app.clientSecret ?? '',
    'grant_type': 'refresh_token',
    'refresh_token': currentUser.token!.refreshToken,
  };
  final headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
  };

  final response = await http.post(url, body: body, headers: headers);

  // Json to map the response
  final jsonResponse = json.decode(response.body);
  final tokenResponse =
      convertToTokenResponse(jsonResponse as Map<String, dynamic>);
  CarpUser user = getCurrentUserProfile(tokenResponse);
  user.authenticated(OAuthToken.fromTokenResponse(tokenResponse));

  currentUser = user;

  return user;
}