-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathjwt_decoder.dart
More file actions
37 lines (30 loc) · 988 Bytes
/
Copy pathjwt_decoder.dart
File metadata and controls
37 lines (30 loc) · 988 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import 'dart:convert';
import 'package:flutter/material.dart';
Map<String, dynamic>? tryDecodeJwt(String token) {
try {
final parts = token.split('.');
if (parts.length != 3) return null;
final payload = parts[1];
final normalized = base64Url.normalize(payload);
final resp = utf8.decode(base64Url.decode(normalized));
return json.decode(resp);
} catch (e) {
debugPrint('Error decoding JWT: $e');
return null;
}
}
bool isTokenExpired(String token) {
final jwtData = tryDecodeJwt(token);
if (jwtData == null) return true;
final exp = jwtData['exp'];
if (exp == null) return true;
final expiryDate = DateTime.fromMillisecondsSinceEpoch(exp * 1000);
return expiryDate.isBefore(DateTime.now());
}
DateTime? getTokenExpiry(String token) {
final jwtData = tryDecodeJwt(token);
if (jwtData == null) return null;
final exp = jwtData['exp'];
if (exp == null) return null;
return DateTime.fromMillisecondsSinceEpoch(exp * 1000);
}