sign method

String sign(
  1. JWTKey key, {
  2. JWTAlgorithm algorithm = JWTAlgorithm.HS256,
  3. Duration? expiresIn,
  4. Duration? notBefore,
  5. bool noIssueAt = false,
})

Sign and generate a new token.

key must be

  • SecretKey with HMAC algorithm
  • RSAPrivateKey with RSA algorithm
  • ECPrivateKey with ECDSA algorithm
  • EdDSAPrivateKey with EdDSA algorithm

Implementation

String sign(
  JWTKey key, {
  JWTAlgorithm algorithm = JWTAlgorithm.HS256,
  Duration? expiresIn,
  Duration? notBefore,
  bool noIssueAt = false,
}) {
  try {
    if (payload is Map<String, dynamic> || payload is Map<dynamic, dynamic>) {
      try {
        payload = Map<String, dynamic>.from(payload);

        if (!noIssueAt) payload['iat'] = secondsSinceEpoch(clock.now());
        if (expiresIn != null) {
          payload['exp'] = secondsSinceEpoch(clock.now().add(expiresIn));
        }
        if (notBefore != null) {
          payload['nbf'] = secondsSinceEpoch(clock.now().add(notBefore));
        }
        if (audience != null) payload['aud'] = audience!.toJson();
        if (subject != null) payload['sub'] = subject;
        if (issuer != null) payload['iss'] = issuer;
        if (jwtId != null) payload['jti'] = jwtId;
      } catch (ex) {
        assert(
          payload is Map<String, dynamic>,
          'If payload is a Map its must be a Map<String, dynamic>',
        );
      }
    }

    final tokenHeader = Map.from(header ?? {});
    tokenHeader.putIfAbsent('alg', () => algorithm.name);
    tokenHeader.putIfAbsent('typ', () => 'JWT');

    final b64Header = base64Unpadded(jsonBase64.encode(tokenHeader));

    String b64Payload;
    try {
      b64Payload = base64Unpadded(
        payload is String
            ? base64.encode(utf8.encode(payload))
            : jsonBase64.encode(payload),
      );
    } catch (ex) {
      throw JWTException(
        'invalid payload json format (Map keys must be String type)',
      );
    }

    final body = '$b64Header.$b64Payload';
    final signature = base64Unpadded(
      base64Url.encode(
        algorithm.sign(
          key,
          Uint8List.fromList(utf8.encode(body)),
        ),
      ),
    );

    return body + '.' + signature;
  } catch (ex, stackTrace) {
    if (ex is Exception && ex is! JWTException) {
      throw JWTUndefinedException(ex, stackTrace);
    } else {
      rethrow;
    }
  }
}