createCustomToken method

Future<String> createCustomToken(
  1. String uid, {
  2. Map<String, Object?>? claims,
  3. String? tenantId,
})

Mints a custom token for uid: the client signs in with it (FirebaseUserAuth.signInWithCustomToken), and claims then appear in the user's ID tokens and in request.auth.token of the security rules.

The token is a JWT (RS256, base64url) issued by the service account, for the Identity Toolkit audience, and valid for one hour. It is signed locally with AdminCredential.serviceAccount, by the IAM Credentials API (signBlob) with AdminCredential.iam, and not at all in emulator mode (alg: none, which only the emulator accepts). tenantId adds tenant_id, for projects with multi-tenancy.

Throws a FirebaseAuthAdminException with code argument-error if uid is empty or longer than 128 characters, or claims use a reserved name (reservedClaims) or are not JSON.

The token is a credential for one hour: send it to the one client that signs in with it, never log it.

Implementation

Future<String> createCustomToken(
  String uid, {
  Map<String, Object?>? claims,
  String? tenantId,
}) async {
  _checkOpen();
  if (uid.isEmpty || uid.length > 128) {
    throw const FirebaseAuthAdminException(
      code: 'argument-error',
      message:
          'The uid must be a non-empty string of at most 128 characters.',
    );
  }
  if (tenantId != null && tenantId.isEmpty) {
    throw const FirebaseAuthAdminException(
      code: 'argument-error',
      message: 'The tenant id must be a non-empty string.',
    );
  }
  if (claims != null) {
    for (final String name in claims.keys) {
      if (reservedClaims.contains(name)) {
        throw FirebaseAuthAdminException(
          code: 'argument-error',
          message:
              'Developer claim "$name" is reserved and cannot be specified.',
        );
      }
    }
    _encodeClaims(claims, 'argument-error');
  }

  final String issuer = await _guard(() => app.signerEmail('auth'));
  final int now = app.now().millisecondsSinceEpoch ~/ 1000;
  final Map<String, Object?> payload = <String, Object?>{
    'aud': customTokenAudience,
    'iat': now,
    'exp': now + 3600,
    'iss': issuer,
    'sub': issuer,
    'uid': uid,
    'tenant_id': ?tenantId,
    if (claims != null && claims.isNotEmpty) 'claims': claims,
  };
  final String header = encodeJsonSegment(<String, Object?>{
    'alg': isEmulator ? 'none' : 'RS256',
    'typ': 'JWT',
  });
  final String input = '$header.${encodeJsonSegment(payload)}';
  if (isEmulator) {
    return '$input.';
  }
  final List<int> signature = await _guard(
    () => app.signRs256(ascii.encode(input), issuer, 'auth'),
  );
  return '$input.${base64UrlNoPadding(signature)}';
}