verifyJwtHS256Signature function

JwtClaim verifyJwtHS256Signature(
  1. String token,
  2. String hmacKey, {
  3. JOSEHeaderCheck? headerCheck = defaultJWTHeaderCheck,
  4. bool defaultIatExp = true,
  5. Duration maxAge = JwtClaim.defaultMaxAge,
})

Implementation

JwtClaim verifyJwtHS256Signature(String token, String hmacKey,
    {JOSEHeaderCheck? headerCheck = defaultJWTHeaderCheck,
    bool defaultIatExp = true,
    Duration maxAge = JwtClaim.defaultMaxAge}) {
  try {
    final hmac = Hmac(sha256, hmacKey.codeUnits);

    final parts = token.split('.');
    if (parts.length != 3) {
      throw JwtException.invalidToken;
    }

    final headerString = Base64Encryption.decodeUtf8(parts[0]);

    final dynamic header = json.decode(headerString);
    if (header is Map) {
      if (headerCheck != null && !headerCheck(header.cast<String, dynamic>())) {
        throw JwtException.invalidToken;
      }

      if (header['alg'] != 'HS256') {
        throw JwtException.hashMismatch;
      }
    } else {
      throw JwtException.headerNotJson;
    }

    final data = '${parts[0]}.${parts[1]}';
    final calcSig = hmac.convert(data.codeUnits).bytes;
    final tokenSig = Base64Encryption.decodeBase64(parts[2]);

    if (!secureCompareIntList(calcSig, tokenSig)) {
      throw JwtException.hashMismatch;
    }
    final payloadString = Base64Encryption.decodeUtf8(parts[1]);
    final dynamic payload = json.decode(payloadString);
    if (payload is Map) {
      return JwtClaim.fromMap(payload.cast(),
          defaultIatExp: defaultIatExp, maxAge: maxAge);
    } else {
      throw JwtException.payloadNotJson;
    }
  } on FormatException {
    throw JwtException.invalidToken;
  }
}