JWT
suggest changeJSON Web Token (JWT) is an open standard (RFC 7519) for securely transmitting information between parties as a compact, URL-safe JSON object. In Dart and Flutter applications, JWTs are commonly used for stateless API authentication, authorization, and information exchange between mobile clients and backend servers (such as Shelf or Dart Frog).
Installing dart_jsonwebtoken
The most widely adopted package for generating, signing, and verifying JWTs in Dart is dart_jsonwebtoken.
Add the dependency to your pubspec.yaml:
dependencies:
dart_jsonwebtoken: ^3.4.1
Run dart pub get to download the package.
Generating and Signing a Token
A JWT consists of three parts separated by dots (.): a header, a payload (claims), and a signature. You can sign a token with a symmetric key (HMAC SHA-256) or asymmetric keys (RSA, ECDSA, Ed25519).
Symmetric Signing with HMAC SHA-256
import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';
void main() {
// Define custom claims
final claims = {
'id': 12345,
'roles': ['user', 'admin'],
'email': 'developer@example.com',
};
// Create the JWT instance
final jwt = JWT(
claims,
issuer: 'https://auth.example.com',
subject: '12345',
audience: Audience(['https://api.example.com']),
);
// Sign the token using SecretKey (HMAC-SHA256 by default)
final secret = SecretKey('your-256-bit-secret-key-string-here');
final token = jwt.sign(
secret,
algorithm: JWTAlgorithm.HS256,
expiresIn: const Duration(hours: 2),
);
print('Generated JWT:');
print(token);
}
Verifying and Decoding Tokens
When an incoming request arrives with a Bearer token, you must verify the signature and ensure the token has not expired or been tampered with.
import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';
void verifyToken(String token, String secretKey) {
try {
// Verify signature and standard claims
final jwt = JWT.verify(
token,
SecretKey(secretKey),
issuer: 'https://auth.example.com',
audience: Audience(['https://api.example.com']),
);
print('Token is valid!');
print('Subject (User ID): ${jwt.subject}');
print('Payload data: ${jwt.payload}');
final payload = jwt.payload as Map<String, dynamic>;
final email = payload['email'];
final roles = List<String>.from(payload['roles'] ?? []);
print('User email: $email, roles: $roles');
} on JWTExpiredException {
print('Token has expired. Please refresh credentials.');
} on JWTUndefinedException catch (e) {
print('Invalid token structure: ${e.message}');
} on JWTInvalidException catch (e) {
print('Invalid signature or claim mismatch: ${e.message}');
}
}
Decoding Without Verification (Client-Side Inspection)
On a client (such as Flutter), you may wish to inspect claims (like expiration or user ID) without needing the server's private secret.
import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';
void inspectToken(String token) {
// Decode without checking signature
final jwt = JWT.decode(token);
print('Header: ${jwt.header}');
print('Payload: ${jwt.payload}');
if (jwt.payload is Map<String, dynamic>) {
final payload = jwt.payload as Map<String, dynamic>;
if (payload.containsKey('exp')) {
final expTimestamp = payload['exp'] as int;
final expiry = DateTime.fromMillisecondsSinceEpoch(expTimestamp * 1000);
print('Expires at: $expiry');
}
}
}
Warning: Never trust unverified claims for authorization or security-critical decisions on the server side. Always use
JWT.verify.
Asymmetric Signing (RSA / RS256)
In distributed architectures or microservices, auth servers sign tokens with a private key, and API gateways or resource servers verify them using the corresponding public key.
import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';
// Sign token on the Auth Server using the Private Key (PEM format)
String createRsaToken(String privateKeyPem) {
final jwt = JWT({'role': 'admin'}, subject: 'user_99');
final rsaPrivKey = RSAPrivateKey(privateKeyPem);
return jwt.sign(rsaPrivKey, algorithm: JWTAlgorithm.RS256, expiresIn: const Duration(minutes: 30));
}
// Verify token on the Resource Server using the Public Key (PEM format)
JWT verifyRsaToken(String token, String publicKeyPem) {
final rsaPubKey = RSAPublicKey(publicKeyPem);
return JWT.verify(token, rsaPubKey);
}
Shelf Middleware for Dart Backends
In a Dart backend using shelf, you can extract the Authorization: Bearer <token> header and attach the verified user identity to the request context:
import 'package:shelf/shelf.dart';
import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';
Middleware jwtAuthMiddleware(String secret) {
return (Handler innerHandler) {
return (Request request) async {
final authHeader = request.headers['Authorization'];
if (authHeader == null || !authHeader.startsWith('Bearer ')) {
return Response(401, body: 'Missing or malformed Authorization header');
}
final token = authHeader.substring(7).trim();
try {
final jwt = JWT.verify(token, SecretKey(secret));
// Attach verified JWT payload to request context for downstream handlers
final updatedRequest = request.change(context: {'user': jwt.payload});
return await innerHandler(updatedRequest);
} on JWTExpiredException {
return Response(401, body: 'Token expired');
} on JWTException catch (e) {
return Response(403, body: 'Invalid token: ${e.message}');
}
};
};
}
Best Practices
- Keep payloads minimal: JWT payloads are Base64URL-encoded, not encrypted. Do not store sensitive secrets, passwords, or personal identifiable information (PII) inside claims.
- Short expiration times: Use short Time-To-Live (TTL) for access tokens (e.g., 15–60 minutes) alongside rotating refresh tokens.
- Always validate standard claims: Check
iss(issuer),aud(audience), andexp(expiration timestamp) during verification. - Use secure key storage: Keep HMAC secrets and RSA private keys in environment variables or a key management vault, never hardcoded in repository sources.