getExpiryDate static method

DateTime? getExpiryDate(
  1. String token
)

Get an expiry date from a JWT token, if specified.

The token is not validated in any way.

Implementation

static DateTime? getExpiryDate(String token) {
  try {
    List<String> parts = token.split('.');
    if (parts.length == 3) {
      // dart:convert doesn't like missing padding
      final rawData = base64Url.decode(base64.normalize(parts[1]));
      final text = Utf8Decoder().convert(rawData);
      Map<String, dynamic> payload = jsonDecode(text);
      if (payload.containsKey('exp') && payload['exp'] is int) {
        return DateTime.fromMillisecondsSinceEpoch(payload['exp'] * 1000);
      }
    }
    return null;
  } catch (e) {
    return null;
  }
}