jwt_generator 0.0.8
jwt_generator: ^0.0.8 copied to clipboard
A simple pure dart package used for creating and validating Json Web Tokens using the private and public key provided, refer to documentation for more information.
example/jwt_generator_example.dart
// ignore_for_file: avoid_print, lines_longer_than_80_chars
// (Examples print to console and embed PEM blocks; we don't want lints here.)
import 'package:jwt_generator/jwt_generator.dart';
/// For local testing only. Never commit real keys.
/// Generate with:
/// openssl genrsa -out private.pem 2048
/// openssl rsa -in private.pem -pubout -out public.pem
const String pemPrivateKey = '''
-----BEGIN RSA PRIVATE KEY-----
# put a real private key here when you test locally
-----END RSA PRIVATE KEY-----
''';
const String pemPublicKey = '''
-----BEGIN PUBLIC KEY-----
# matching public key goes here
-----END PUBLIC KEY-----
''';
void main() {
// 1) Parse keys from PEM
final parser = RsaKeyParser();
final rsaPrivateKey = parser.extractPrivateKey(pemPrivateKey);
final rsaPublicKey = parser.extractPublicKey(pemPublicKey);
// 2) Build a token (RS256) using your DTO
final tokenDto = FcmTokenDto(iss: 'you@example.com', iat: DateTime.now());
final rs256Signifier = RsaSignifier(privateKey: rsaPrivateKey);
final jwtBuilder = JwtBuilder(signifier: rs256Signifier);
final jwt = jwtBuilder.buildToken(tokenDto);
print('JWT (RS256): $jwt');
// 3) Verify RS256 with public key
// Helper (recommended)
final bool okHelper = verifyJwtRs256(jwt, rsaPublicKey);
print('RS256 verify (helper): $okHelper');
// Manual flow using the generic verifier (verifier takes BYTES)
final parsed = ParsedJwt.parse(jwt);
final rsaVerifier = RsaSignatureVerifier(publicKey: rsaPublicKey);
final bool okManual = rsaVerifier.verify(
parsed.signingInputBytes,
parsed.signatureBytes,
);
print('RS256 verify (manual): $okManual');
// 4) HS256 example (shared secret)
final List<int> secret = 'super-secret-change-me'.codeUnits;
final hmacBuilder = JwtBuilder(signifier: HmacSignifier(secret: secret));
final hmacJwt = hmacBuilder.buildToken(
FcmTokenDto(iss: 'you@example.com', iat: DateTime.now()),
);
print('JWT (HS256): $hmacJwt');
// Verify HS256
final parsedHs = ParsedJwt.parse(hmacJwt);
final hmacVerifier = HmacSignatureVerifier(secret: secret);
final bool okHs = hmacVerifier.verify(
parsedHs.signingInputBytes,
parsedHs.signatureBytes(),
);
print('HS256 verify: $okHs');
}