4

I'm having trouble creating a JWT token on Dart. I already tried dart_jwt package, but it didn't work following the examples ("Encoding" section HERE).

I would be glad if anyone could help me on creating a JWT token on Dart, even with a different package.

Suragch
  • 428,106
  • 278
  • 1,284
  • 1,317
Felipe
  • 366
  • 2
  • 5
  • 14
  • What does "didn't work mean"? Error message, wrong result, ... – Günter Zöchbauer Jul 16 '15 at 06:02
  • 1
    @GünterZöchbauer: It's an error message. JwtClaimSet is an abstract class and you cannot instantiate it (it's the link I've posted). But, there's no need to be dart_jwt. That's why I asked for other packages too, because, maybe, other people did it. – Felipe Jul 16 '15 at 12:24
  • 1
    I also didn't find a similar question. dart_jwt is the most recent package and it's from @andersmholmgren. If the example doesn't work I would create an issue in the GitHub repo. – Günter Zöchbauer Jul 16 '15 at 12:26
  • Sorry I downvote this question, but you better use other JWT package https://pub.dartlang.org/packages?q=jwt as the package you pointed to is no longer maintained, and is said to be Dart 2 incompatible. – TruongSinh Mar 28 '19 at 04:59

2 Answers2

0

you need to use one of the subclass and not the abstract class like in the readme.md see

final DateTime issuedAt   = new DateTime.now();
final DateTime expiresAt  = issuedAt.add(const Duration(minutes: 5));
String iss                = 'xxxxxxx';

final claimSet            = new OpenIdJwtClaimSet.build(issuer:  iss, subject: 'xxxx', expiry: expiresAt, issuedAt: issuedAt);
final signatureContext    = new JwaSymmetricKeySignatureContext(app.api.secret);
final jwt                 = new JsonWebToken.jws(claimSet, signatureContext);
return jwt.encode();
fredtma
  • 987
  • 1
  • 13
  • 24
0

A JWT token is just a JSON header, payload and signature encoded in Base64Url format. (See an example.) You could do it all yourself, but there are packages that will do it for you. The jaguar_jwt package is being actively maintained and has worked well for me.

// import 'package:jaguar_jwt/jaguar_jwt.dart';

final claimSet = JwtClaim(
  issuer: 'Me',
  subject: '${userId}',
  issuedAt: DateTime.now(),
  maxAge: const Duration(hours: 12)
);

const String secret = 'myreallysecretpassword';
String token = issueJwtHS256(claimSet, secret);

See also

Suragch
  • 428,106
  • 278
  • 1,284
  • 1,317