5

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
  • 484,302
  • 314
  • 1,365
  • 1,393
Felipe
  • 376
  • 2
  • 5
  • 15
  • 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

3 Answers3

2

For generating Json Web Token we can use this library

First we have to create one dart file where we will store all JWT Constant

abstract class JWTConstants {
  static const String accesssTokenSecretKey =
      'QBBS0P1H2NLLOTVRWIHR6WXI55G2ZYHH';
  static const String refreshTokenSecretKey =
      'KF4DMA5VAYCGM60T7N0A46BLOEHXSNX7';
}

We Have to create one class which is responsible for generate Jsons Web Tokens.

import 'package:auth_pro/core/constant/jwt_constant.dart';
import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';

abstract class JWTUtils {
  static String generateAccessToken({required String userId}) {
    final jwt = JWT({
      'userId': userId,
    });

    return jwt.sign(
      SecretKey(JWTConstants.accesssTokenSecretKey),
      expiresIn: const Duration(days: 30),
    );
  }

  static bool verifyAccessToken({required String accessToken}) {
    try {
      JWT.verify(accessToken, SecretKey(JWTConstants.accesssTokenSecretKey));
      return true;
    } catch (_) {
      return false;
    }
  }

  static String getUserIdFromToken({required String accessToken}) {
    final jwt = JWT.decode(accessToken);
    // ignore: avoid_dynamic_calls
    return jwt.payload['userId'] as String;
  }
}

We can use this methods

// For generate Token

final accessToken = JWTUtils.generateAccessToken(userId: user.userId);

// For Validate Tokens

  JWTUtils.verifyAccessToken(accessToken: accessToken)
Shailendra Rajput
  • 2,131
  • 17
  • 26
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
  • 1,007
  • 2
  • 17
  • 27
  • It's worth noting that the two common JWT Dart libraries on pub.dev use different methods for setting the issuedAt and expiresAt claim. `jaguar_jwt` converts the current time to UTC (which was required by the service I was integrating with.) `dart_jsonwebtoken` does NOT convert, so the local time will be used which, if your expiresAt is very close to the issuedAt time, will cause your JWT to immediately be considered invalid by the server. – Jeff Neet Dec 03 '22 at 07:56
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
  • 484,302
  • 314
  • 1,365
  • 1,393