I am writing a Flutter/Dart application and am getting a JWT back from an auth server that has some claims I need to use. I have looked at various (4 so far) Dart JWT libraries -- but all are either too old and no longer work with Dart 2, etc. or they need the secret to decode the JWT which makes no sense and isn't correct (or possible since I have no access ).
So -- how can one get a JWT and get the claims from it within a "modern" Dart/Flutter application?
Each JWT contains a payload. The payload is a base64 encoded JSON object that sits between the two periods in the token. We can decode this payload by using atob() to decode the payload to a JSON string and use JSON. parse() to parse the string into an object.
import 'package:flutter_secure_storage/flutter_secure_storage. dart'; // Create storage final storage = new FlutterSecureStorage(); // Write value await storage. write(key: 'jwt', value: token);
JWT claims Claims constitute the payload part of a JSON web token and represent a set of information exchanged between two parties. The JWT standard distinguishes between reserved claims, public claims, and private claims. In API Gateway context, both public claims and private claims are considered custom claims.
JSON Web Token (JWT) A dart implementation of the famous javascript library jsonwebtoken . JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties. https://jwt.io allows you to decode, verify and generate JWT.
JWT tokens are just base64 encoded JSON strings (3 of them, separated by dots):
import 'dart:convert'; Map<String, dynamic> parseJwt(String token) { final parts = token.split('.'); if (parts.length != 3) { throw Exception('invalid token'); } final payload = _decodeBase64(parts[1]); final payloadMap = json.decode(payload); if (payloadMap is! Map<String, dynamic>) { throw Exception('invalid payload'); } return payloadMap; } String _decodeBase64(String str) { String output = str.replaceAll('-', '+').replaceAll('_', '/'); switch (output.length % 4) { case 0: break; case 2: output += '=='; break; case 3: output += '='; break; default: throw Exception('Illegal base64url string!"'); } return utf8.decode(base64Url.decode(output)); }
Use 'base64Url.normalize()' function. That's what _decodeBase64() does from the answer above!
String getJsonFromJWT(String splittedToken){ String normalizedSource = base64Url.normalize(encodedStr); return utf8.decode(base64Url.decode(normalizedSource)); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With