authorization property

Authorization? authorization
getter/setter pair

Authorization Configuration

The Authorization class configures secure communication between the SDK and your server, adding bearer or shared-access tokens to every HTTP request and automatically refreshing them when expired or rejected by the server.

Overview

When Config.authorization is defined:

  • All HTTP requests include the Authorization header automatically:
    • "JWT"Authorization: Bearer {accessToken}
    • "SAS"Authorization: {accessToken}
  • When a 401 Unauthorized response occurs, the SDK can automatically:
    1. Send a POST request to Authorization.refreshUrl using Authorization.refreshPayload.
    2. Merge headers as described in Header merge order.
    3. Parse the JSON response for new tokens and expiry.
    4. Persist new values and retry the failed request transparently.

You do not need to manually configure HttpConfig.headers for authentication.

Auto-refresh requirements

Automatic refresh occurs only when all the following are true:

Include one field whose value is the literal "{refreshToken}". This placeholder is replaced at runtime with the configured Authorization.refreshToken.

Refresh request details

Method: POST Body encoding: application/x-www-form-urlencoded

  • The body is always form-encoded. Sending JSON is not supported.
  • Values in Authorization.refreshPayload are converted to strings. Only string values are eligible for {refreshToken} substitution.

Header merge order

When performing a refresh:

  1. Global headers from HttpConfig.headers are applied first (excluding content-type).
  2. The Content-Type header is fixed to application/x-www-form-urlencoded.
  3. Authorization.refreshHeaders are applied last and can override previous entries.

Template variables

You may reference dynamic credential values using placeholders:

Defaults

Response handling

The server’s response to Authorization.refreshUrl must be JSON. The SDK scans the object recursively for:

Token Type Pattern Match (case-insensitive) Example Key Names
Access Token access, auth, id_token "accessToken"
Refresh Token renew, refresh "refreshToken"
Expiry Timestamp expire, expires, expiration "expires_at"

Matching values are extracted and applied automatically. When successful, an AuthorizationEvent is fired and the original HTTP request is retried. On failure, the event contains error details.

Security and Logging

Authorization data is redacted from logs when serialized to prevent credential leakage.

Example

import 'package:flutter_background_geolocation/flutter_background_geolocation.dart' as bg;

Future<void> main() async {
  final token = await fetchTokenFromServer();

  await bg.BackgroundGeolocation.ready(bg.Config(
    http: bg.HttpConfig(
      url: 'https://api.example.com/locations',
      autoSync: true,
    ),
    authorization: bg.Authorization(
      strategy: 'JWT',
      accessToken: token['accessToken'],
      refreshToken: token['refreshToken'],
      refreshUrl: 'https://auth.example.com/tokens',
      refreshPayload: const {
        'grant_type': 'refresh_token',
        'refresh_token': '{refreshToken}',
      },
      refreshHeaders: const {
        'Authorization': 'Bearer {accessToken}',
        'X-Tenant': 'acme',
      },
      expires: 1699999999,
    ),
  ));

  bg.BackgroundGeolocation.onAuthorization((event) {
    if (event.success) {
      print('[authorization] Refresh OK');
    } else {
      print('[authorization] Refresh FAILED: ${event.error}');
    }
  });
}

FAQ

  • Can I send the refresh request as JSON? No. The SDK always uses application/x-www-form-urlencoded.

  • Can I include booleans or numbers in refreshPayload? Convert them to strings first. Only string values are accepted.

  • Can I override the Content-Type header? No. The content type for refresh requests is fixed and cannot be changed.

  • Can I disable automatic headers for the refresh request? Yes. Provide refreshHeaders: const {} to prevent automatic Authorization headers.

Implementation

Authorization? authorization;