verifyIdToken method
Verifies the Firebase ID token idToken of a user and returns its claims.
Checks, as the Firebase documentation lists them: the header (alg RS256, a kid among Google's current
keys), the RS256 signature, aud (the project id), iss (https://securetoken.google.com/<projectId>),
sub (non-empty, at most 128 characters), exp in the future, iat and auth_time in the past. Times
may be off by clockSkew (default defaultClockSkew, at most maxClockSkew).
The keys are fetched from idTokenCertificatesUri and kept for the max-age of its Cache-Control
header.
With checkRevoked the user is looked up too (one more request): user-disabled if the account is
disabled, id-token-revoked if revokeRefreshTokens was called after the user signed in.
In emulator mode (FirebaseAdminApp.emulator) the token must be unsigned (alg: none), as the emulator
issues them; the claims are checked the same way. Outside emulator mode an unsigned token is refused.
Throws a FirebaseAuthAdminException: id-token-expired, argument-error for any other failed check,
internal-error if the keys cannot be fetched, and the errors of getUser with checkRevoked.
Implementation
Future<VerifiedIdToken> verifyIdToken(
String idToken, {
bool checkRevoked = false,
Duration clockSkew = defaultClockSkew,
}) async {
_checkOpen();
if (clockSkew.isNegative || clockSkew > maxClockSkew) {
throw ArgumentError.value(
clockSkew,
'clockSkew',
'Must be between zero and $maxClockSkew',
);
}
Never invalid(String why) => throw FirebaseAuthAdminException(
code: 'argument-error',
message: 'The Firebase ID token is not valid: $why.',
);
final List<String> parts = idToken.split('.');
if (parts.length != 3) {
invalid('it is not a JWT');
}
final Map<String, Object?> header;
final Map<String, Object?> payload;
final Uint8List signature;
try {
header = decodeJsonSegment(parts[0]);
payload = decodeJsonSegment(parts[1]);
signature = decodeSegment(parts[2]);
} on FormatException {
invalid('it is not a well-formed JWT');
}
final Object? alg = header['alg'];
if (isEmulator) {
if (alg != 'none' || signature.isNotEmpty) {
invalid(
'in emulator mode the token must be unsigned (alg "none"), as the emulator issues them',
);
}
} else {
if (alg == 'none') {
invalid(
'it is unsigned (alg "none"); only the Auth emulator issues such tokens',
);
}
if (alg != 'RS256') {
invalid('the algorithm must be RS256');
}
final Object? kid = header['kid'];
if (kid is! String || kid.isEmpty) {
invalid('it has no "kid" header');
}
final RsaPublicKey? key = (await _publicKeys()).keys[kid];
if (key == null) {
invalid('its "kid" does not match a current Google public key');
}
if (!key.verifyRs256(
ascii.encode('${parts[0]}.${parts[1]}'),
signature,
)) {
invalid('its signature is invalid');
}
}
if (payload['aud'] != projectId) {
invalid('its audience ("aud") is not the project "$projectId"');
}
if (payload['iss'] != 'https://securetoken.google.com/$projectId') {
invalid(
'its issuer ("iss") is not https://securetoken.google.com/$projectId',
);
}
final Object? sub = payload['sub'];
if (sub is! String || sub.isEmpty || sub.length > 128) {
invalid(
'its subject ("sub") must be a non-empty string of at most 128 characters',
);
}
final Object? exp = payload['exp'];
final Object? iat = payload['iat'];
final Object? authTime = payload['auth_time'];
if (exp is! num || iat is! num || authTime is! num) {
invalid('"exp", "iat" and "auth_time" must be numbers');
}
final double now = app.now().millisecondsSinceEpoch / 1000;
final int skew = clockSkew.inSeconds;
if (exp <= now - skew) {
throw const FirebaseAuthAdminException(
code: 'id-token-expired',
message:
'The Firebase ID token has expired. Get a fresh token from your client and try again.',
);
}
if (iat > now + skew) {
invalid('it was issued in the future ("iat")');
}
if (authTime > now + skew) {
invalid('its "auth_time" is in the future');
}
final VerifiedIdToken token = VerifiedIdToken(payload);
if (checkRevoked) {
final AdminUser user = await getUser(sub);
if (user.disabled) {
throw const FirebaseAuthAdminException(
code: 'user-disabled',
message: 'The user record is disabled.',
);
}
final DateTime? validAfter = user.tokensValidAfter;
if (validAfter != null &&
authTime * 1000 < validAfter.millisecondsSinceEpoch) {
throw const FirebaseAuthAdminException(
code: 'id-token-revoked',
message: 'The Firebase ID token has been revoked.',
);
}
}
return token;
}