can anyone explain how to decode a token in json using dart.
i done in android with this below code. But how to decode a token in dart.
public class JWTUtils {
public static String decoded(String JWTEncoded) throws Exception {
String encode = "";
try {
String[] split = JWTEncoded.split("\\.");
Log.d("JWT_DECODED", "Header: " + getJson(split[0]));
encode = getJson(split[1]);
} catch (UnsupportedEncodingException e) {
//Error
}
return encode;
}
private static String getJson(String strEncoded) throws UnsupportedEncodingException{
byte[] decodedBytes = Base64.decode(strEncoded, Base64.URL_SAFE);
return new String(decodedBytes, "UTF-8");
}
}
String encodeddata = JWTUtils.decoded(token);
Parsing JWT Payload With Dart Let's create a function tryParseJwt that takes String token and returns the payload data as a key value map. Since, there are elements of a signed JWT token, we first check if all three parts exist. if(token == null) return null; final parts = token. split('.
Flutter Application with Jwt Authentication JWT is short for Json Web Token, which is a quite popular implementation of authentication. A Json Web Token is a Json string sent from a server to a client(such as mobile app) typically after user login.
If you is interested in get the public part of token basically you have to split the token by '.' and decode the second part with base64
var text = token.split('.')[1];
var decoded = base64.decode(text);
return utf8.decode(decoded);
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));
}
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